feature/implementacion de hub en EFC
This commit is contained in:
@@ -2,3 +2,4 @@ VITE_DEBUG_MODE=false
|
||||
|
||||
VITE_EFC_API_URL=https://api.efc-aduanasoft.com/api/v1
|
||||
VITE_EFC_MICROSERVICE_URL=https://api.efc-aduanasoft.com/microservice/api/v1
|
||||
VITE_HUB_URL=http://localhost:3001
|
||||
|
||||
@@ -28,11 +28,12 @@ import TableroAlmacenamiento from './pages/TableroAlmacenamiento';
|
||||
import Notificaciones from './pages/Notificaciones';
|
||||
import ForgotPassword from './pages/ForgotPassword';
|
||||
import PasswordResetConfirm from './pages/PasswordResetConfirm';
|
||||
import SSOCallback from './pages/SSOCallback';
|
||||
|
||||
// Componente para manejar el layout condicional
|
||||
function AppContent() {
|
||||
const location = useLocation();
|
||||
const isAuthPage = location.pathname === '/login' || location.pathname === '/' || location.pathname === '/forgot-password' || location.pathname.startsWith('/user/password-reset-confirm/');
|
||||
const isAuthPage = location.pathname === '/login' || location.pathname === '/' || location.pathname === '/forgot-password' || location.pathname.startsWith('/user/password-reset-confirm/') || location.pathname === '/auth/sso';
|
||||
|
||||
if (isAuthPage) {
|
||||
return (
|
||||
@@ -42,6 +43,7 @@ function AppContent() {
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/forgot-password" element={<ForgotPassword />} />
|
||||
<Route path="/user/password-reset-confirm/:uid/:token/" element={<PasswordResetConfirm />} />
|
||||
<Route path="/auth/sso" element={<SSOCallback />} />
|
||||
</Routes>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,24 +1,74 @@
|
||||
const API_URL = import.meta.env.VITE_EFC_API_URL;
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'https://workspace.aduanasoft.com';
|
||||
|
||||
export async function login(username, password) {
|
||||
const response = await fetch(`${API_URL}/token/`, {
|
||||
/**
|
||||
* Login directo email/password via Hub.
|
||||
* Devuelve { access_token, user_id, email, ... }
|
||||
* o { needs_tenant: true, tenants: [...] } si es multi-tenant.
|
||||
*/
|
||||
export async function login(username, password, tenant_slug) {
|
||||
const body = { username, password };
|
||||
if (tenant_slug) body.tenant_slug = tenant_slug;
|
||||
|
||||
const response = await fetch(`${API_URL}/auth/login/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
credentials: 'include', // recibir cookie HTTP-only
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Credenciales inválidas');
|
||||
}
|
||||
return response.json(); // { access, refresh }
|
||||
if (response.status === 401) throw new Error('Credenciales inválidas');
|
||||
if (response.status === 403) throw new Error('Usuario inactivo o sin permisos');
|
||||
if (!response.ok) throw new Error('Error al iniciar sesión');
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// export async function refreshToken(refresh) {
|
||||
// const res = await fetch(`${API_URL}/token/refresh/`, {
|
||||
// method: 'POST',
|
||||
// headers: { 'Content-Type': 'application/json' },
|
||||
// body: JSON.stringify({ refresh }),
|
||||
// });
|
||||
// if (!res.ok) throw new Error('SESSION_EXPIRED');
|
||||
// return res.json(); // { access: '...' }
|
||||
// }
|
||||
/** Canjea relay token del Hub por sesión local (SSO entre productos / Microsoft). */
|
||||
export async function ssoExchange(relay_token) {
|
||||
const response = await fetch(`${API_URL}/auth/sso/exchange/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ relay_token }),
|
||||
});
|
||||
|
||||
if (response.status === 401) throw new Error('Relay token inválido o expirado');
|
||||
if (!response.ok) throw new Error('Error al completar inicio de sesión SSO');
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/** Usuario autenticado actual. */
|
||||
export async function getMe(token) {
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (token) headers['Authorization'] = `Bearer ${token}`;
|
||||
|
||||
const response = await fetch(`${API_URL}/auth/me/`, {
|
||||
headers,
|
||||
credentials: 'include',
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error('No autenticado');
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/** Cierra sesión: limpia estado local de inmediato, backend en background. */
|
||||
export function logout() {
|
||||
// 1. Limpiar localStorage inmediatamente (síncrono, sin esperar al servidor)
|
||||
['access', 'refresh', 'user_id', 'username', 'user_email',
|
||||
'user_first_name', 'user_last_name', 'user_groups',
|
||||
'user_is_importador', 'user_permissions'].forEach(k => localStorage.removeItem(k));
|
||||
|
||||
// 2. Notificar a los componentes que la sesión terminó
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
|
||||
// 3. Llamar al backend en segundo plano para limpiar cookies (fire and forget)
|
||||
fetch(`${API_URL}/auth/logout/`, { method: 'POST', credentials: 'include' }).catch(() => {});
|
||||
}
|
||||
|
||||
/** URL para login con Microsoft (redirige al Hub). */
|
||||
export function getMicrosoftLoginUrl() {
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
return `${HUB_URL}/login?return_to=${returnTo}&idp=microsoft`;
|
||||
}
|
||||
|
||||
@@ -1,17 +1,12 @@
|
||||
import React from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { logout } from '../api/auth';
|
||||
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
|
||||
export default function LogoutButton() {
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
|
||||
// Disparar evento para actualizar el navbar
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
|
||||
navigate('/login');
|
||||
logout(); // limpia estado + llama backend en bg
|
||||
window.location.href = `${HUB_URL}/login`;
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Link, useLocation } from 'react-router-dom';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { colors } from '../theme';
|
||||
|
||||
const hubLoginUrl = () => {
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
return `${HUB_URL}/login?return_to=${returnTo}`;
|
||||
};
|
||||
|
||||
export default function Navbar() {
|
||||
const [isLoggedIn, setIsLoggedIn] = useState(false);
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
@@ -18,11 +24,11 @@ export default function Navbar() {
|
||||
return () => window.removeEventListener('authStateChanged', checkAuthStatus);
|
||||
}, []);
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
window.location.href = '/';
|
||||
const logout = async () => {
|
||||
const { logout: doLogout } = await import('../api/auth');
|
||||
doLogout(); // limpia estado + llama backend en bg
|
||||
const hubUrl = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${hubUrl}/login`;
|
||||
};
|
||||
|
||||
const navLinks = [
|
||||
@@ -97,15 +103,15 @@ export default function Navbar() {
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<Link
|
||||
to="/login"
|
||||
<a
|
||||
href={hubLoginUrl()}
|
||||
className="bg-gradient-to-r from-navy-600 to-navy-700 hover:from-navy-700 hover:to-navy-800 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 flex items-center space-x-2 shadow-lg hover:shadow-xl transform hover:scale-105"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1" />
|
||||
</svg>
|
||||
<span>Ingresar</span>
|
||||
</Link>
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import React from 'react';
|
||||
import { Navigate } from 'react-router-dom';
|
||||
|
||||
// Esta función verifica si el usuario está autenticado (por ejemplo, si hay un token en localStorage)
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'https://workspace.aduanasoft.com';
|
||||
|
||||
function isAuthenticated() {
|
||||
const token = localStorage.getItem('access');
|
||||
return !!token;
|
||||
return !!localStorage.getItem('access');
|
||||
}
|
||||
|
||||
export default function RequireAuth({ children }) {
|
||||
const authenticated = isAuthenticated();
|
||||
|
||||
if (!authenticated) {
|
||||
return <Navigate to="/login" replace />;
|
||||
if (!isAuthenticated()) {
|
||||
// Sesión expirada o no iniciada → redirigir al Hub con return_to
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
window.location.href = `${HUB_URL}/login?return_to=${returnTo}`;
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return children;
|
||||
}
|
||||
|
||||
@@ -29,19 +29,11 @@ export default function Sidebar({ isMobileOpen, onMobileClose }) {
|
||||
const navigate = useNavigate();
|
||||
const { user: currentUser, loading } = useUser();
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
localStorage.removeItem('user_id');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
localStorage.removeItem('user_groups');
|
||||
localStorage.removeItem('user_permissions');
|
||||
localStorage.removeItem('username');
|
||||
localStorage.removeItem('user_email');
|
||||
localStorage.removeItem('user_first_name');
|
||||
localStorage.removeItem('user_last_name');
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
navigate('/login');
|
||||
const handleLogout = async () => {
|
||||
const { logout } = await import('../api/auth');
|
||||
logout(); // limpia estado + llama backend en bg
|
||||
const hubUrl = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${hubUrl}/login`;
|
||||
};
|
||||
|
||||
// Cerrar menú móvil cuando se navega o cuando la pantalla es grande
|
||||
@@ -114,7 +106,7 @@ export default function Sidebar({ isMobileOpen, onMobileClose }) {
|
||||
title: 'Servicios',
|
||||
items: [
|
||||
{
|
||||
name: 'Procesos',
|
||||
name: 'Historial de Procesos',
|
||||
path: '/procesos',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
@@ -140,47 +132,62 @@ export default function Sidebar({ isMobileOpen, onMobileClose }) {
|
||||
{
|
||||
title: 'Documentación',
|
||||
items: [
|
||||
// Mostrar Reportes siempre
|
||||
{
|
||||
name: 'Reportes',
|
||||
path: '/reports',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
name: 'Expedientes',
|
||||
path: '/expedientes',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="3" y="7" width="18" height="13" rx="2" ry="2" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M16 3H8a2 2 0 00-2 2v2h12V5a2 2 0 00-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
name: 'Documentos',
|
||||
path: '/documents',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
)
|
||||
},
|
||||
{
|
||||
name: 'Datastage',
|
||||
path: '/datastage',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<ellipse cx="12" cy="7" rx="8" ry="3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M4 7v10c0 1.657 3.582 3 8 3s8-1.343 8-3V7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M4 17c0 1.657 3.582 3 8 3s8-1.343 8-3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
),
|
||||
onClick: () => navigate('/datastage')
|
||||
}
|
||||
...(
|
||||
hasPermission('reportes.view')
|
||||
? [{
|
||||
name: 'Reportes',
|
||||
path: '/reports',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
|
||||
</svg>
|
||||
)
|
||||
}]
|
||||
: []
|
||||
),
|
||||
...(
|
||||
hasPermission('pedimentos.view')
|
||||
? [{
|
||||
name: 'Expedientes',
|
||||
path: '/expedientes',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<rect x="3" y="7" width="18" height="13" rx="2" ry="2" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M16 3H8a2 2 0 00-2 2v2h12V5a2 2 0 00-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
)
|
||||
}]
|
||||
: []
|
||||
),
|
||||
...(
|
||||
hasPermission('documentos.view')
|
||||
? [{
|
||||
name: 'Documentos',
|
||||
path: '/documents',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
|
||||
</svg>
|
||||
)
|
||||
}]
|
||||
: []
|
||||
),
|
||||
...(
|
||||
hasPermission('datastage.view')
|
||||
? [{
|
||||
name: 'Datastage',
|
||||
path: '/datastage',
|
||||
icon: (
|
||||
<svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<ellipse cx="12" cy="7" rx="8" ry="3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M4 7v10c0 1.657 3.582 3 8 3s8-1.343 8-3V7" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
<path d="M4 17c0 1.657 3.582 3 8 3s8-1.343 8-3" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
|
||||
</svg>
|
||||
),
|
||||
onClick: () => navigate('/datastage')
|
||||
}]
|
||||
: []
|
||||
),
|
||||
]
|
||||
},
|
||||
// Nueva sección Tableros - Solo mostrar si DEBUG_MODE es true y tiene cards.view
|
||||
|
||||
@@ -6,14 +6,11 @@ export default function Sidebar() {
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
|
||||
// Disparar evento para actualizar el navbar
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
|
||||
navigate('/login');
|
||||
const handleLogout = async () => {
|
||||
const { logout } = await import('../api/auth');
|
||||
logout(); // limpia estado + llama backend en bg
|
||||
const hubUrl = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${hubUrl}/login`;
|
||||
};
|
||||
|
||||
const menuItems = [
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { useNavigate, useLocation } from 'react-router-dom';
|
||||
import { useTaskProgress } from '../context/TaskProgressContext';
|
||||
import { useServerSentEvents } from '../hooks/useServerSentEvents';
|
||||
import { fetchWithAuth } from '../fetchWithAuth';
|
||||
|
||||
const API_URL = import.meta.env.VITE_EFC_API_URL;
|
||||
|
||||
const STATUS_LABEL = {
|
||||
submitted: 'Enviando...',
|
||||
@@ -10,13 +13,6 @@ const STATUS_LABEL = {
|
||||
failed: 'Error',
|
||||
};
|
||||
|
||||
const STATUS_COLOR = {
|
||||
submitted: 'bg-slate-100 border-slate-300 text-slate-700',
|
||||
processing: 'bg-blue-50 border-blue-300 text-blue-800',
|
||||
completed: 'bg-green-50 border-green-300 text-green-800',
|
||||
failed: 'bg-red-50 border-red-300 text-red-800',
|
||||
};
|
||||
|
||||
const BADGE_COLOR = {
|
||||
submitted: 'bg-slate-200 text-slate-700',
|
||||
processing: 'bg-blue-100 text-blue-700',
|
||||
@@ -24,18 +20,19 @@ const BADGE_COLOR = {
|
||||
failed: 'bg-red-100 text-red-700',
|
||||
};
|
||||
|
||||
/** Conecta SSE para UNA tarea y actualiza el contexto con los eventos recibidos. */
|
||||
const AUTH_PATHS = new Set(['/', '/login', '/forgot-password', '/auth/sso']);
|
||||
|
||||
/** Conecta SSE para UNA tarea y actualiza el contexto. Se mantiene vivo independientemente del estado del panel. */
|
||||
function TaskSSEConnector({ task }) {
|
||||
const { updateTask } = useTaskProgress();
|
||||
|
||||
useServerSentEvents(
|
||||
task.status === 'completed' || task.status === 'failed' ? null : task.task_id,
|
||||
{
|
||||
onUpdate(data) {
|
||||
updateTask(task.task_id, {
|
||||
status: data.status,
|
||||
message: data.message,
|
||||
progress: data.progress ?? task.progress,
|
||||
status: data.status,
|
||||
message: data.message,
|
||||
progress: data.progress ?? task.progress,
|
||||
resultado: data.resultado ?? task.resultado,
|
||||
});
|
||||
},
|
||||
@@ -47,111 +44,258 @@ function TaskSSEConnector({ task }) {
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Card individual de una tarea. */
|
||||
/** Card compacta de una tarea dentro del panel expandido. */
|
||||
function SingleTaskCard({ task }) {
|
||||
const { dismissTask, openTaskInAuditor } = useTaskProgress();
|
||||
const navigate = useNavigate();
|
||||
const isActive = task.status === 'submitted' || task.status === 'processing';
|
||||
const [downloading, setDownloading] = useState(false);
|
||||
const isActive = task.status === 'submitted' || task.status === 'processing';
|
||||
const isReport = task.taskType === 'report';
|
||||
|
||||
const handleVerResultado = () => {
|
||||
openTaskInAuditor(task.task_id);
|
||||
navigate('/auditor');
|
||||
};
|
||||
|
||||
const handleDescargarReporte = async () => {
|
||||
const reportId = task.resultado?.report_id ?? task.report_id;
|
||||
if (!reportId) { navigate('/reports'); return; }
|
||||
setDownloading(true);
|
||||
try {
|
||||
const res = await fetchWithAuth(`${API_URL}/reports/report-document-download/${reportId}/`);
|
||||
if (!res.ok) { navigate('/reports'); return; }
|
||||
const blob = await res.blob();
|
||||
const disposition = res.headers.get('Content-Disposition');
|
||||
let filename = '';
|
||||
if (disposition) {
|
||||
const match = disposition.match(/filename="?([^";\s]+)"?/);
|
||||
if (match) filename = match[1];
|
||||
}
|
||||
if (!filename) filename = `reporte_${reportId}.xlsx`;
|
||||
const link = document.createElement('a');
|
||||
link.href = window.URL.createObjectURL(blob);
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
dismissTask(task.task_id);
|
||||
} catch {
|
||||
navigate('/reports');
|
||||
} finally {
|
||||
setDownloading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={task.resultado ? handleVerResultado : undefined}
|
||||
className={`flex flex-col gap-2 p-3 rounded-xl border shadow-md text-sm w-72 ${STATUS_COLOR[task.status] ?? STATUS_COLOR.submitted} ${task.resultado ? 'cursor-pointer hover:shadow-lg transition-shadow' : ''}`}
|
||||
>
|
||||
{/* Encabezado */}
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div className="flex flex-col gap-0.5 min-w-0">
|
||||
<span className="font-semibold truncate">{task.label}</span>
|
||||
<span className={`self-start px-1.5 py-0.5 rounded text-xs font-medium ${BADGE_COLOR[task.status]}`}>
|
||||
<div className="flex flex-col gap-1.5 p-2.5 rounded-lg border border-gray-100 bg-gray-50 text-xs">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<div className="flex items-center gap-1.5 min-w-0">
|
||||
<span className="font-semibold truncate text-gray-800">{task.label}</span>
|
||||
<span className={`px-1.5 py-0.5 rounded text-xs font-medium flex-shrink-0 ${BADGE_COLOR[task.status]}`}>
|
||||
{STATUS_LABEL[task.status] ?? task.status}
|
||||
</span>
|
||||
</div>
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); dismissTask(task.task_id); }}
|
||||
aria-label="Cerrar"
|
||||
className="text-gray-400 hover:text-gray-600 flex-shrink-0 mt-0.5"
|
||||
onClick={() => dismissTask(task.task_id)}
|
||||
aria-label="Descartar tarea"
|
||||
className="text-gray-300 hover:text-gray-500 flex-shrink-0"
|
||||
>
|
||||
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Mensaje */}
|
||||
{task.message && (
|
||||
<p className="text-xs opacity-75 truncate">{task.message}</p>
|
||||
<p className="text-xs text-gray-400 truncate">{task.message}</p>
|
||||
)}
|
||||
|
||||
{/* Barra de progreso */}
|
||||
{isActive && (
|
||||
<div className="w-full bg-blue-100 rounded-full h-1.5 overflow-hidden">
|
||||
<div className="w-full bg-blue-100 rounded-full h-1 overflow-hidden">
|
||||
<div
|
||||
className="bg-blue-500 h-1.5 rounded-full transition-all duration-500"
|
||||
className="bg-blue-500 h-1 rounded-full transition-all duration-500"
|
||||
style={{ width: `${task.progress ?? 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Aviso de navegación libre cuando está en progreso */}
|
||||
{isActive && (
|
||||
<p className="text-xs text-blue-600 font-medium">
|
||||
Puedes seguir navegando — te avisamos cuando termine.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Botón "Ver resultado" cuando completó */}
|
||||
{task.status === 'completed' && (
|
||||
{task.status === 'completed' && isReport && (
|
||||
<button
|
||||
onClick={(e) => { e.stopPropagation(); handleVerResultado(); }}
|
||||
className="mt-1 w-full py-1.5 px-3 rounded-lg bg-green-600 hover:bg-green-700 text-white text-xs font-semibold transition-colors"
|
||||
onClick={handleDescargarReporte}
|
||||
disabled={downloading}
|
||||
className="w-full py-1 px-2 rounded bg-green-600 hover:bg-green-700 disabled:bg-green-400 text-white text-xs font-semibold transition-colors flex items-center justify-center gap-1"
|
||||
>
|
||||
Ver resultado en Panel de Auditoría →
|
||||
{downloading ? (
|
||||
<>
|
||||
<svg className="w-3 h-3 animate-spin" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
Descargando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
Descargar reporte
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Mensaje de error */}
|
||||
{task.status === 'failed' && (
|
||||
<p className="text-xs text-red-600 font-medium">
|
||||
La tarea falló. Revisa el Panel de Auditoría.
|
||||
{task.status === 'completed' && !isReport && (
|
||||
<button
|
||||
onClick={handleVerResultado}
|
||||
className="w-full py-1 px-2 rounded bg-green-600 hover:bg-green-700 text-white text-xs font-semibold transition-colors"
|
||||
>
|
||||
Ver resultado en Auditoría →
|
||||
</button>
|
||||
)}
|
||||
|
||||
{task.status === 'failed' && isReport && (
|
||||
<p className="text-xs text-red-500">
|
||||
Falló — revisa el historial en{' '}
|
||||
<button onClick={() => navigate('/reports')} className="underline">Reportes</button>.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{task.status === 'failed' && !isReport && (
|
||||
<p className="text-xs text-red-500">Falló — revisa el Panel de Auditoría.</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* TaskProgressCard — contenedor flotante que renderiza todas las tareas activas/completadas.
|
||||
* Se monta globalmente en App.jsx y persiste durante toda la navegación.
|
||||
* TaskProgressCard — pill minimizado en bottom-left.
|
||||
* Las conexiones SSE viven siempre; el panel es solo visual y no bloquea la UI.
|
||||
* Se auto-expande cuando una tarea pasa a completada o fallida.
|
||||
*/
|
||||
export default function TaskProgressCard() {
|
||||
const { visibleTasks } = useTaskProgress();
|
||||
const location = useLocation();
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const prevStatusesRef = useRef({});
|
||||
const containerRef = useRef(null);
|
||||
|
||||
if (visibleTasks.length === 0) return null;
|
||||
// Cierra el panel al hacer click fuera del componente
|
||||
useEffect(() => {
|
||||
if (!expanded) return;
|
||||
function handleClickOutside(e) {
|
||||
if (containerRef.current && !containerRef.current.contains(e.target)) {
|
||||
setExpanded(false);
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside);
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||
}, [expanded]);
|
||||
|
||||
// Auto-expandir cuando una tarea activa pasa a estado terminal
|
||||
useEffect(() => {
|
||||
let shouldExpand = false;
|
||||
visibleTasks.forEach(t => {
|
||||
const prev = prevStatusesRef.current[t.task_id];
|
||||
if (
|
||||
(t.status === 'completed' || t.status === 'failed') &&
|
||||
prev !== undefined && prev !== 'completed' && prev !== 'failed'
|
||||
) {
|
||||
shouldExpand = true;
|
||||
}
|
||||
prevStatusesRef.current[t.task_id] = t.status;
|
||||
});
|
||||
if (shouldExpand) setExpanded(true);
|
||||
}, [visibleTasks]);
|
||||
|
||||
// Solo renderizar dentro de la app autenticada
|
||||
const isAuthPage = AUTH_PATHS.has(location.pathname)
|
||||
|| location.pathname.startsWith('/user/password-reset-confirm/');
|
||||
|
||||
if (isAuthPage || visibleTasks.length === 0) return null;
|
||||
|
||||
const activeTasks = visibleTasks.filter(t => t.status === 'submitted' || t.status === 'processing');
|
||||
const completedTasks = visibleTasks.filter(t => t.status === 'completed');
|
||||
const failedTasks = visibleTasks.filter(t => t.status === 'failed');
|
||||
|
||||
// Estilo y contenido del pill según estado dominante
|
||||
let pillLabel, pillClass, pillIconType;
|
||||
if (activeTasks.length > 0) {
|
||||
pillLabel = `${activeTasks.length} tarea${activeTasks.length > 1 ? 's' : ''} en proceso`;
|
||||
pillClass = 'bg-blue-600 text-white border-blue-700 hover:bg-blue-700';
|
||||
pillIconType = 'spinner';
|
||||
} else if (failedTasks.length > 0 && completedTasks.length === 0) {
|
||||
pillLabel = `${failedTasks.length} tarea${failedTasks.length > 1 ? 's' : ''} fallida${failedTasks.length > 1 ? 's' : ''}`;
|
||||
pillClass = 'bg-red-50 text-red-700 border-red-300 hover:bg-red-100';
|
||||
pillIconType = 'x';
|
||||
} else {
|
||||
pillLabel = `${completedTasks.length} tarea${completedTasks.length > 1 ? 's' : ''} completada${completedTasks.length > 1 ? 's' : ''}`;
|
||||
pillClass = 'bg-green-50 text-green-700 border-green-300 hover:bg-green-100';
|
||||
pillIconType = 'check';
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Conectores SSE — uno por tarea en progreso, sin UI propia */}
|
||||
{visibleTasks.map((task) => (
|
||||
<TaskSSEConnector key={task.task_id} task={task} />
|
||||
))}
|
||||
{/* Conectores SSE — siempre activos, independientes del estado del panel */}
|
||||
{visibleTasks
|
||||
.filter(t => t.status === 'processing' || t.status === 'submitted')
|
||||
.map(task => <TaskSSEConnector key={task.task_id} task={task} />)}
|
||||
|
||||
{/*
|
||||
Dock flotante en top-right. El pill queda arriba y el panel se expande hacia abajo.
|
||||
items-end alinea todo a la derecha.
|
||||
*/}
|
||||
<div ref={containerRef} className="fixed top-4 right-4 z-40 flex flex-col items-end gap-2">
|
||||
|
||||
{/* Pill — botón de toggle siempre visible, arriba */}
|
||||
<button
|
||||
onClick={() => setExpanded(e => !e)}
|
||||
className={`flex items-center gap-1.5 pl-2.5 pr-3 py-1.5 rounded-full text-xs font-semibold shadow-md border transition-all ${pillClass}`}
|
||||
>
|
||||
{pillIconType === 'spinner' && (
|
||||
<svg className="w-3 h-3 animate-spin flex-shrink-0" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
|
||||
</svg>
|
||||
)}
|
||||
{pillIconType === 'check' && (
|
||||
<svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M5 13l4 4L19 7" />
|
||||
</svg>
|
||||
)}
|
||||
{pillIconType === 'x' && (
|
||||
<svg className="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
)}
|
||||
<span>{pillLabel}</span>
|
||||
</button>
|
||||
|
||||
{/* Panel expandido — aparece debajo del pill */}
|
||||
{expanded && (
|
||||
<div className="bg-white border border-gray-200 rounded-xl shadow-xl w-72 overflow-hidden">
|
||||
<div className="flex items-center justify-between px-3 py-2 bg-gray-50 border-b border-gray-100">
|
||||
<span className="text-xs font-semibold text-gray-500 uppercase tracking-wide">
|
||||
Tareas en segundo plano
|
||||
</span>
|
||||
<button
|
||||
onClick={() => setExpanded(false)}
|
||||
aria-label="Minimizar panel"
|
||||
className="text-gray-400 hover:text-gray-600"
|
||||
>
|
||||
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 15l7-7 7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div className="p-2 flex flex-col gap-1.5 max-h-72 overflow-y-auto">
|
||||
{visibleTasks.map(task => <SingleTaskCard key={task.task_id} task={task} />)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Cards flotantes en esquina inferior derecha */}
|
||||
<div
|
||||
className="fixed bottom-4 right-4 flex flex-col gap-2 z-50"
|
||||
style={{ maxHeight: '80vh', overflowY: 'auto' }}
|
||||
>
|
||||
{visibleTasks.map((task) => (
|
||||
<SingleTaskCard key={task.task_id} task={task} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -35,7 +35,20 @@ export function useTaskProgress() {
|
||||
function loadFromStorage() {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
return raw ? JSON.parse(raw) : [];
|
||||
if (!raw) return [];
|
||||
const tasks = JSON.parse(raw);
|
||||
const cutoff = Date.now() - 24 * 60 * 60 * 1000; // 24 horas
|
||||
// Auto-descartar tareas "processing/submitted" con más de 24h (nunca terminaron)
|
||||
return tasks.map(t => {
|
||||
if (
|
||||
(t.status === 'processing' || t.status === 'submitted') &&
|
||||
t.started_at &&
|
||||
new Date(t.started_at).getTime() < cutoff
|
||||
) {
|
||||
return { ...t, dismissed: true, status: 'failed', message: 'Tarea expirada' };
|
||||
}
|
||||
return t;
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const API_URL = import.meta.env.VITE_EFC_API_URL;
|
||||
const API_URL = import.meta.env.VITE_EFC_API_URL; // e.g. http://localhost:8000/api/v1
|
||||
const BASE_URL = API_URL.replace(/\/api\/v1\/?$/, ''); // e.g. http://localhost:8000
|
||||
|
||||
// Variable para controlar si ya hay una renovación de token en proceso
|
||||
let isRefreshing = false;
|
||||
@@ -17,72 +18,69 @@ const processQueue = (error, token = null) => {
|
||||
failedQueue = [];
|
||||
};
|
||||
|
||||
// Función para renovar el token usando el refresh token
|
||||
/**
|
||||
* Intenta renovar el token. Estrategia:
|
||||
* 1. Nuevo endpoint cookie-based (SSO / hub-frontend): no requiere body,
|
||||
* lee el refresh_token desde la cookie HTTP-only.
|
||||
* 2. Fallback legacy (apps antiguas): lee refresh de localStorage y llama
|
||||
* al endpoint de SimpleJWT.
|
||||
*/
|
||||
const refreshToken = async () => {
|
||||
try {
|
||||
const refresh = localStorage.getItem('refresh');
|
||||
if (!refresh) {
|
||||
throw new Error('No refresh token available');
|
||||
}
|
||||
|
||||
// Intentar primero con el endpoint completo
|
||||
let refreshEndpoint = `${API_URL}/token/refresh/`;
|
||||
|
||||
let response = await fetch(refreshEndpoint, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refresh: refresh
|
||||
}),
|
||||
});
|
||||
|
||||
// Si falla con 404, intentar con el endpoint alternativo
|
||||
if (response.status === 404) {
|
||||
refreshEndpoint = `${API_URL}/token/refresh/`;
|
||||
response = await fetch(refreshEndpoint, {
|
||||
// ── Intento 1: SimpleJWT refresh (login directo EFC) ──────────────────
|
||||
// Usa el endpoint estándar de SimpleJWT con el token de localStorage.
|
||||
const refresh = localStorage.getItem('refresh');
|
||||
if (refresh) {
|
||||
try {
|
||||
// Endpoint SimpleJWT estándar (login EFC directo) — campo "refresh"
|
||||
const res = await fetch(`${BASE_URL}/api/v1/token/refresh/`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
refresh: refresh
|
||||
}),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh }),
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const newAccess = data.access;
|
||||
if (newAccess) {
|
||||
localStorage.setItem('access', newAccess);
|
||||
if (data.refresh) localStorage.setItem('refresh', data.refresh);
|
||||
return newAccess;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// continúa al fallback
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Failed to refresh token: ${response.status} - ${errorText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
// Guardar el nuevo access token
|
||||
localStorage.setItem('access', data.access);
|
||||
|
||||
// Si viene un nuevo refresh token, guardarlo también
|
||||
if (data.refresh) {
|
||||
localStorage.setItem('refresh', data.refresh);
|
||||
}
|
||||
|
||||
return data.access;
|
||||
} catch (error) {
|
||||
// Si falla la renovación, limpiar tokens y redirigir al login
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
localStorage.removeItem('user_id');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
localStorage.removeItem('user_permissions');
|
||||
|
||||
// Redirigir al login después de un pequeño delay
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1000);
|
||||
|
||||
throw new Error('SESSION_EXPIRED');
|
||||
try {
|
||||
// Fallback: endpoint SSO local (tokens HS256 de sesiones Hub)
|
||||
const res = await fetch(`${API_URL}/auth/session/refresh/`, {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
});
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const newAccess = data.access_token || data.access;
|
||||
if (newAccess) {
|
||||
localStorage.setItem('access', newAccess);
|
||||
return newAccess;
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// ── Fallo total: limpiar sesión y redirigir al Hub ─────────────────────
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
localStorage.removeItem('user_id');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
localStorage.removeItem('user_permissions');
|
||||
|
||||
const hubUrl = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
setTimeout(() => {
|
||||
window.location.href = `${hubUrl}/login?return_to=${returnTo}`;
|
||||
}, 1000);
|
||||
|
||||
throw new Error('SESSION_EXPIRED');
|
||||
};
|
||||
|
||||
// Función principal para hacer peticiones con manejo automático de tokens
|
||||
@@ -108,85 +106,66 @@ export const fetchWithAuth = async (url, options = {}) => {
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
// Hacer la petición inicial
|
||||
let response = await fetch(url, finalOptions);
|
||||
// Helper: ejecutar fetch con reintento ante error de red (Fix E)
|
||||
const safeFetch = async (u, opts, retries = 1) => {
|
||||
for (let i = 0; i <= retries; i++) {
|
||||
try {
|
||||
return await fetch(u, opts);
|
||||
} catch (networkErr) {
|
||||
if (i === retries) throw networkErr;
|
||||
await new Promise(r => setTimeout(r, 300 * (i + 1))); // backoff 300ms
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Si la respuesta es 401 (Unauthorized), manejar renovación de token
|
||||
try {
|
||||
let response = await safeFetch(url, finalOptions);
|
||||
|
||||
// 401 → intentar renovar token
|
||||
if (response.status === 401) {
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
|
||||
try {
|
||||
// Renovar el token
|
||||
const newToken = await refreshToken();
|
||||
|
||||
// Procesar la cola de peticiones pendientes
|
||||
processQueue(null, newToken);
|
||||
|
||||
// Actualizar el header de autorización y reintentar la petición original
|
||||
finalOptions.headers['Authorization'] = `Bearer ${newToken}`;
|
||||
response = await fetch(url, finalOptions);
|
||||
|
||||
response = await safeFetch(url, finalOptions);
|
||||
} catch (refreshError) {
|
||||
// Si falla la renovación, procesar la cola con error
|
||||
processQueue(refreshError, null);
|
||||
throw refreshError;
|
||||
} finally {
|
||||
isRefreshing = false;
|
||||
}
|
||||
} else {
|
||||
// Ya hay un refresh en proceso, agregar esta petición a la cola
|
||||
// Otro refresh en curso — encolar y esperar
|
||||
return new Promise((resolve, reject) => {
|
||||
failedQueue.push({
|
||||
resolve: (token) => {
|
||||
finalOptions.headers['Authorization'] = `Bearer ${token}`;
|
||||
fetch(url, finalOptions)
|
||||
.then(resolve)
|
||||
.catch(reject);
|
||||
resolve: (tok) => {
|
||||
finalOptions.headers['Authorization'] = `Bearer ${tok}`;
|
||||
safeFetch(url, finalOptions).then(resolve).catch(reject);
|
||||
},
|
||||
reject
|
||||
reject,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Si todavía hay un 401 después del intento de renovación, verificar si realmente es un problema de auth
|
||||
|
||||
// 401 persistente después del retry → la sesión expiró definitivamente
|
||||
if (response.status === 401) {
|
||||
// Verificar si tenemos un token válido en localStorage
|
||||
const currentToken = localStorage.getItem('access');
|
||||
|
||||
// Intentar obtener más información del error
|
||||
let errorDetails = '';
|
||||
try {
|
||||
const errorText = await response.text();
|
||||
errorDetails = errorText;
|
||||
} catch (e) {
|
||||
// Error al leer respuesta
|
||||
}
|
||||
|
||||
// Si no hay token o el error indica problema de autenticación, limpiar sesión
|
||||
if (!currentToken || errorDetails.includes('token') || errorDetails.includes('auth')) {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
localStorage.removeItem('user_id');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1000);
|
||||
|
||||
throw new Error('SESSION_EXPIRED');
|
||||
} else {
|
||||
// Si hay token pero sigue fallando, podría ser un problema del servidor
|
||||
// No limpiar la sesión, dejar que el error se propague
|
||||
}
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
localStorage.removeItem('user_id');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
localStorage.removeItem('user_permissions');
|
||||
const hubUrl = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
setTimeout(() => { window.location.href = `${hubUrl}/login?return_to=${returnTo}`; }, 800);
|
||||
throw new Error('SESSION_EXPIRED');
|
||||
}
|
||||
|
||||
return response;
|
||||
|
||||
} catch (error) {
|
||||
// Si hay un error de red o cualquier otro error, propagarlo
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -88,7 +88,8 @@ export default function Documents() {
|
||||
localStorage.removeItem('refresh');
|
||||
showMessage('Tu sesión ha expirado, por favor inicia sesión de nuevo.', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
const _hub = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${_hub}/login?return_to=${encodeURIComponent(window.location.origin + '/auth/sso')}`;
|
||||
}, 2000);
|
||||
} else if (error) {
|
||||
showMessage(error.message, 'error');
|
||||
|
||||
@@ -140,7 +140,8 @@ export default function Documents() {
|
||||
localStorage.removeItem('refresh');
|
||||
showMessage('Tu sesión ha expirado, por favor inicia sesión de nuevo.', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
const _hub = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${_hub}/login?return_to=${encodeURIComponent(window.location.origin + '/auth/sso')}`;
|
||||
}, 2000);
|
||||
} else if (error) {
|
||||
showMessage(error.message, 'error');
|
||||
@@ -1004,12 +1005,16 @@ const downloadExpediente = async (pedimentoId, pedimentoName, setSuccess, showMe
|
||||
value={contribuyenteInput}
|
||||
onChange={e => {
|
||||
setContribuyenteInput(e.target.value);
|
||||
setContribuyenteFilter(e.target.value);
|
||||
setCurrentPage(1);
|
||||
}}
|
||||
onBlur={e => {
|
||||
setContribuyenteFilter(e.target.value);
|
||||
// Solo limpiar el filtro cuando el input queda vacío.
|
||||
// El filtro real se aplica al hacer clic en una sugerencia del dropdown.
|
||||
// Actualizar el filtro con RFC parcial causa fuga de datos: el backend
|
||||
// omite silenciosamente el filtro cuando el RFC no existe en Importador.
|
||||
if (!e.target.value) {
|
||||
setContribuyenteFilter('');
|
||||
setCurrentPage(1);
|
||||
}
|
||||
}}
|
||||
onBlur={() => {}}
|
||||
placeholder="Buscar o escribir..."
|
||||
className="w-full border border-gray-300 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white shadow-sm transition-all duration-200 hover:shadow-md"
|
||||
autoComplete="off"
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { colors, tailwindClasses } from '../theme';
|
||||
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
const hubLoginUrl = () => {
|
||||
const returnTo = encodeURIComponent(`${window.location.origin}/auth/sso`);
|
||||
return `${HUB_URL}/login?return_to=${returnTo}`;
|
||||
};
|
||||
|
||||
export default function LandingAnimated() {
|
||||
const [isScrolled, setIsScrolled] = useState(false);
|
||||
const [activeSection, setActiveSection] = useState('inicio');
|
||||
@@ -199,8 +204,8 @@ export default function LandingAnimated() {
|
||||
</nav>
|
||||
</div>
|
||||
<div className="flex items-center space-x-4">
|
||||
<Link
|
||||
to="/login"
|
||||
<a
|
||||
href="/login"
|
||||
className="px-6 py-2 rounded-full text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5 text-white"
|
||||
style={{
|
||||
background: 'linear-gradient(to right, #1B2A41, #4DA6FF)',
|
||||
@@ -213,7 +218,7 @@ export default function LandingAnimated() {
|
||||
}}
|
||||
>
|
||||
Acceder
|
||||
</Link>
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -313,8 +318,8 @@ export default function LandingAnimated() {
|
||||
: 'opacity-0 translate-y-10'
|
||||
}`}
|
||||
>
|
||||
<Link
|
||||
to="/login"
|
||||
<a
|
||||
href="/login"
|
||||
className="inline-flex items-center px-8 py-4 text-lg font-semibold transition-all duration-300 transform rounded-full shadow-2xl group hover:shadow-3xl hover:-translate-y-1 hover:scale-105"
|
||||
style={{
|
||||
color: '#1B2A41',
|
||||
@@ -331,7 +336,7 @@ export default function LandingAnimated() {
|
||||
<svg className="w-5 h-5 ml-2 transition-transform duration-200 group-hover:translate-x-1" fill="currentColor" viewBox="0 0 20 20">
|
||||
<path fillRule="evenodd" d="M10.293 3.293a1 1 0 011.414 0l6 6a1 1 0 010 1.414l-6 6a1 1 0 01-1.414-1.414L14.586 11H3a1 1 0 110-2h11.586l-4.293-4.293a1 1 0 010-1.414z" clipRule="evenodd" />
|
||||
</svg>
|
||||
</Link>
|
||||
</a>
|
||||
<button
|
||||
onClick={() => scrollToSection('caracteristicas')}
|
||||
className="inline-flex items-center px-8 py-4 text-lg font-semibold text-white transition-all duration-300 bg-transparent border-2 rounded-full group border-white/30 hover:border-white hover:bg-white/10 backdrop-blur-sm"
|
||||
|
||||
@@ -1,100 +1,123 @@
|
||||
import React, { useState } from 'react';
|
||||
import { login } from '../api/auth';
|
||||
import { login, getMicrosoftLoginUrl } from '../api/auth';
|
||||
import { Link } from 'react-router-dom';
|
||||
import { colors } from '../theme';
|
||||
|
||||
const HUB_URL = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
|
||||
export default function Login() {
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [username, setUsername] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showPassword, setShowPassword] = useState(false);
|
||||
const [tenantChoices, setTenantChoices] = useState(null);
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
const handleSubmit = async (e, tenantSlug) => {
|
||||
if (e) e.preventDefault();
|
||||
setError('');
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await login(username, password);
|
||||
localStorage.setItem('access', data.access);
|
||||
localStorage.setItem('refresh', data.refresh);
|
||||
const data = await login(username, password, tenantSlug || undefined);
|
||||
|
||||
// Obtener y guardar la información del usuario autenticado
|
||||
const apiUrl = import.meta.env.VITE_EFC_API_URL || '';
|
||||
const token = data.access;
|
||||
try {
|
||||
const [resUser, resPerms] = await Promise.all([
|
||||
fetch(`${apiUrl}/user/users/me/`, { headers: { 'Authorization': `Bearer ${token}` } }),
|
||||
fetch(`${apiUrl}/rbac/my-permissions/`, { headers: { 'Authorization': `Bearer ${token}` } }),
|
||||
]);
|
||||
if (resUser.ok) {
|
||||
const user = await resUser.json();
|
||||
if (user && user.username) {
|
||||
localStorage.setItem('username', user.username);
|
||||
if (user.email) localStorage.setItem('user_email', user.email);
|
||||
if (user.id) localStorage.setItem('user_id', String(user.id));
|
||||
if (user.groups) localStorage.setItem('user_groups', JSON.stringify(user.groups));
|
||||
if (user.first_name) localStorage.setItem('user_first_name', user.first_name);
|
||||
if (user.last_name) localStorage.setItem('user_last_name', user.last_name);
|
||||
if (typeof user.is_importador !== 'undefined') localStorage.setItem('user_is_importador', String(user.is_importador));
|
||||
}
|
||||
}
|
||||
if (resPerms.ok) {
|
||||
const permsData = await resPerms.json();
|
||||
if (permsData && permsData.permissions) {
|
||||
localStorage.setItem('user_permissions', JSON.stringify(permsData.permissions));
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
// Si falla, continuar igual
|
||||
console.error('No se pudo guardar info de usuario en localStorage', e);
|
||||
if (data.needs_tenant) {
|
||||
setTenantChoices(data.tenants || []);
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Disparar evento personalizado para que el navbar se actualice
|
||||
// SimpleJWT devuelve "access" y "refresh" (tokens estándar de EFC)
|
||||
const accessToken = data.access || data.access_token;
|
||||
const refreshToken = data.refresh || data.refresh_token;
|
||||
if (accessToken) localStorage.setItem('access', accessToken);
|
||||
if (refreshToken) localStorage.setItem('refresh', refreshToken);
|
||||
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
|
||||
// Redirigir al dashboard
|
||||
window.location.href = '/admin';
|
||||
if (data.first_login) {
|
||||
// Primera vez: acaba de ser provisionado en Hub.
|
||||
// Redirigir al Hub para que establezca su sesión KC y conozca el workspace.
|
||||
const returnTo = encodeURIComponent('/app-launcher');
|
||||
window.location.href = `${HUB_URL}/login?return_to=${returnTo}`;
|
||||
} else {
|
||||
// Ya estaba migrado: ir directo al dashboard de EFC.
|
||||
window.location.href = '/admin';
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
setError('Usuario o contraseña incorrectos');
|
||||
setError(err.message || 'Usuario o contraseña incorrectos');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8" style={{ backgroundColor: '#F2F4F7' }}>
|
||||
<div
|
||||
className="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8"
|
||||
style={{ backgroundColor: '#F2F4F7' }}
|
||||
>
|
||||
{/* Background pattern */}
|
||||
<div className="absolute inset-0 opacity-20">
|
||||
<div className="absolute inset-0" style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fillRule='evenodd'%3E%3Cg fill='%231B2A41' fillOpacity='0.1'%3E%3Ccircle cx='30' cy='30' r='2'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`
|
||||
}}></div>
|
||||
<div
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
backgroundImage: `url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fillRule='evenodd'%3E%3Cg fill='%231B2A41' fillOpacity='0.1'%3E%3Ccircle cx='30' cy='30' r='2'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E")`,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
<div className="relative max-w-md w-full">
|
||||
{/* Main Card */}
|
||||
<div className="bg-white backdrop-blur-md rounded-3xl shadow-2xl border border-gray-200 overflow-hidden">
|
||||
{/* Header with navy background */}
|
||||
|
||||
{/* Header */}
|
||||
<div className="px-8 py-10 text-center" style={{ backgroundColor: '#1B2A41' }}>
|
||||
<div className="mb-4">
|
||||
<Link to="/" className="inline-block">
|
||||
<h1 className="text-4xl font-bold text-white">
|
||||
EFC
|
||||
</h1>
|
||||
<h1 className="text-4xl font-bold text-white">EFC</h1>
|
||||
</Link>
|
||||
</div>
|
||||
<h2 className="text-2xl font-bold text-white mb-2">
|
||||
Bienvenido de vuelta
|
||||
</h2>
|
||||
<p className="text-sm" style={{ color: 'rgba(255, 255, 255, 0.8)' }}>
|
||||
<h2 className="text-2xl font-bold text-white mb-2">Bienvenido de vuelta</h2>
|
||||
<p className="text-sm" style={{ color: 'rgba(255,255,255,0.8)' }}>
|
||||
Inicia sesión para acceder a tu plataforma aduanal
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Form */}
|
||||
<div className="px-8 py-8">
|
||||
<form onSubmit={handleSubmit} className="space-y-6">
|
||||
{/* Username Field */}
|
||||
|
||||
{/* Selector multi-tenant */}
|
||||
{tenantChoices && (
|
||||
<div className="mb-6">
|
||||
<p className="text-sm font-semibold mb-3" style={{ color: '#333333' }}>
|
||||
Tu cuenta tiene acceso a varias organizaciones. Selecciona una:
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
{tenantChoices.map(t => (
|
||||
<button
|
||||
key={t.id}
|
||||
type="button"
|
||||
onClick={() => handleSubmit(null, t.slug)}
|
||||
className="w-full py-3 px-4 rounded-xl border text-left text-sm font-medium transition-all duration-200 hover:shadow-md"
|
||||
style={{ borderColor: '#4DA6FF', color: '#1B2A41', backgroundColor: '#F8FAFF' }}
|
||||
>
|
||||
{t.name}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setTenantChoices(null)}
|
||||
className="mt-3 text-xs font-medium"
|
||||
style={{ color: '#7A7A7A' }}
|
||||
>
|
||||
← Volver
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form
|
||||
onSubmit={handleSubmit}
|
||||
className={`space-y-6 ${tenantChoices ? 'hidden' : ''}`}
|
||||
>
|
||||
{/* Username */}
|
||||
<div>
|
||||
<label htmlFor="username" className="block text-sm font-semibold mb-2" style={{ color: '#333333' }}>
|
||||
Usuario
|
||||
@@ -107,47 +130,20 @@ export default function Login() {
|
||||
</div>
|
||||
<input
|
||||
id="username"
|
||||
name="username"
|
||||
type="text"
|
||||
required
|
||||
className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:border-transparent transition duration-200"
|
||||
style={{
|
||||
color: '#333333',
|
||||
borderColor: '#d1d5db',
|
||||
':focus': {
|
||||
ringColor: '#4DA6FF',
|
||||
borderColor: 'transparent'
|
||||
},
|
||||
':hover': {
|
||||
borderColor: '#4DA6FF'
|
||||
}
|
||||
}}
|
||||
className="block w-full pl-10 pr-3 py-3 border border-gray-300 rounded-xl focus:outline-none transition duration-200"
|
||||
style={{ color: '#333333', borderColor: '#d1d5db' }}
|
||||
placeholder="Ingresa tu usuario"
|
||||
value={username}
|
||||
onChange={e => setUsername(e.target.value)}
|
||||
onFocus={(e) => {
|
||||
e.target.style.borderColor = 'transparent';
|
||||
e.target.style.boxShadow = '0 0 0 2px #4DA6FF';
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
e.target.style.borderColor = '#d1d5db';
|
||||
e.target.style.boxShadow = 'none';
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (document.activeElement !== e.target) {
|
||||
e.target.style.borderColor = '#4DA6FF';
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (document.activeElement !== e.target) {
|
||||
e.target.style.borderColor = '#d1d5db';
|
||||
}
|
||||
}}
|
||||
onFocus={e => { e.target.style.borderColor = 'transparent'; e.target.style.boxShadow = '0 0 0 2px #4DA6FF'; }}
|
||||
onBlur={e => { e.target.style.borderColor = '#d1d5db'; e.target.style.boxShadow = 'none'; }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Password Field */}
|
||||
{/* Password */}
|
||||
<div>
|
||||
<label htmlFor="password" className="block text-sm font-semibold mb-2" style={{ color: '#333333' }}>
|
||||
Contraseña
|
||||
@@ -160,47 +156,27 @@ export default function Login() {
|
||||
</div>
|
||||
<input
|
||||
id="password"
|
||||
name="password"
|
||||
type={showPassword ? "text" : "password"}
|
||||
type={showPassword ? 'text' : 'password'}
|
||||
required
|
||||
className="block w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none focus:ring-2 focus:border-transparent transition duration-200"
|
||||
style={{
|
||||
color: '#333333',
|
||||
borderColor: '#d1d5db'
|
||||
}}
|
||||
className="block w-full pl-10 pr-12 py-3 border border-gray-300 rounded-xl focus:outline-none transition duration-200"
|
||||
style={{ color: '#333333', borderColor: '#d1d5db' }}
|
||||
placeholder="Ingresa tu contraseña"
|
||||
value={password}
|
||||
onChange={e => setPassword(e.target.value)}
|
||||
onFocus={(e) => {
|
||||
e.target.style.borderColor = 'transparent';
|
||||
e.target.style.boxShadow = '0 0 0 2px #4DA6FF';
|
||||
}}
|
||||
onBlur={(e) => {
|
||||
e.target.style.borderColor = '#d1d5db';
|
||||
e.target.style.boxShadow = 'none';
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (document.activeElement !== e.target) {
|
||||
e.target.style.borderColor = '#4DA6FF';
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (document.activeElement !== e.target) {
|
||||
e.target.style.borderColor = '#d1d5db';
|
||||
}
|
||||
}}
|
||||
onFocus={e => { e.target.style.borderColor = 'transparent'; e.target.style.boxShadow = '0 0 0 2px #4DA6FF'; }}
|
||||
onBlur={e => { e.target.style.borderColor = '#d1d5db'; e.target.style.boxShadow = 'none'; }}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center transition-colors duration-200"
|
||||
className="absolute inset-y-0 right-0 pr-3 flex items-center"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
>
|
||||
{showPassword ? (
|
||||
<svg className="h-5 w-5 hover:opacity-70" style={{ color: '#7A7A7A' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="h-5 w-5" style={{ color: '#7A7A7A' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L8.464 8.464m1.414 1.414L12 12m0 0l2.122 2.122m0 0l1.414 1.414" />
|
||||
</svg>
|
||||
) : (
|
||||
<svg className="h-5 w-5 hover:opacity-70" style={{ color: '#7A7A7A' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="h-5 w-5" style={{ color: '#7A7A7A' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
|
||||
</svg>
|
||||
@@ -209,73 +185,61 @@ export default function Login() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Message */}
|
||||
{/* Error */}
|
||||
{error && (
|
||||
<div className="rounded-xl bg-red-50 border p-4 animate-pulse" style={{ borderColor: 'rgba(198, 40, 40, 0.2)' }}>
|
||||
<div className="rounded-xl bg-red-50 border p-4" style={{ borderColor: 'rgba(198,40,40,0.2)' }}>
|
||||
<div className="flex">
|
||||
<div className="flex-shrink-0">
|
||||
<svg className="h-5 w-5" style={{ color: '#C62828' }} viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="ml-3">
|
||||
<h3 className="text-sm font-medium" style={{ color: '#C62828' }}>
|
||||
{error}
|
||||
</h3>
|
||||
</div>
|
||||
<svg className="h-5 w-5 flex-shrink-0" style={{ color: '#C62828' }} viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
<p className="ml-3 text-sm font-medium" style={{ color: '#C62828' }}>{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Login Button */}
|
||||
<div>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-semibold rounded-xl text-white focus:outline-none focus:ring-2 focus:ring-offset-2 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
|
||||
style={{
|
||||
backgroundColor: '#1B2A41',
|
||||
'--tw-ring-color': '#1B2A41'
|
||||
}}
|
||||
onMouseEnter={(e) => {
|
||||
if (!loading) {
|
||||
e.target.style.backgroundColor = '#162234';
|
||||
}
|
||||
}}
|
||||
onMouseLeave={(e) => {
|
||||
if (!loading) {
|
||||
e.target.style.backgroundColor = '#1B2A41';
|
||||
}
|
||||
}}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
|
||||
</svg>
|
||||
Ingresando...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Ingresar</span>
|
||||
<svg className="ml-2 w-4 h-4 group-hover:translate-x-1 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7l5 5m0 0l-5 5m5-5H6" />
|
||||
</svg>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{/* Botón login */}
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="w-full flex justify-center items-center py-3 px-4 rounded-xl text-sm font-semibold text-white disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
|
||||
style={{ backgroundColor: '#1B2A41' }}
|
||||
onMouseEnter={e => { if (!loading) e.currentTarget.style.backgroundColor = '#162234'; }}
|
||||
onMouseLeave={e => { if (!loading) e.currentTarget.style.backgroundColor = '#1B2A41'; }}
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-white" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
|
||||
</svg>
|
||||
Verificando…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>Ingresar</span>
|
||||
<svg className="ml-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13 7l5 5m0 0l-5 5m5-5H6" />
|
||||
</svg>
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{/* Divider */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex-1 border-t border-gray-200" />
|
||||
<span className="text-xs" style={{ color: '#7A7A7A' }}>o continúa con</span>
|
||||
<div className="flex-1 border-t border-gray-200" />
|
||||
</div>
|
||||
|
||||
{/* Additional Links */}
|
||||
{/* Links */}
|
||||
<div className="text-center space-y-3">
|
||||
<div className="text-sm">
|
||||
<Link
|
||||
to="/forgot-password"
|
||||
className="font-medium transition-colors duration-200"
|
||||
style={{ color: '#4DA6FF' }}
|
||||
onMouseEnter={(e) => e.target.style.color = '#1976D2'}
|
||||
onMouseLeave={(e) => e.target.style.color = '#4DA6FF'}
|
||||
onMouseEnter={e => e.target.style.color = '#1976D2'}
|
||||
onMouseLeave={e => e.target.style.color = '#4DA6FF'}
|
||||
>
|
||||
¿Olvidaste tu contraseña?
|
||||
</Link>
|
||||
@@ -283,12 +247,12 @@ export default function Login() {
|
||||
<div className="border-t border-gray-200 pt-4">
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex items-center text-sm font-medium group transition-colors duration-200"
|
||||
className="inline-flex items-center text-sm font-medium transition-colors duration-200"
|
||||
style={{ color: '#4DA6FF' }}
|
||||
onMouseEnter={(e) => e.target.style.color = '#1976D2'}
|
||||
onMouseLeave={(e) => e.target.style.color = '#4DA6FF'}
|
||||
onMouseEnter={e => e.target.style.color = '#1976D2'}
|
||||
onMouseLeave={e => e.target.style.color = '#4DA6FF'}
|
||||
>
|
||||
<svg className="mr-2 w-4 h-4 group-hover:-translate-x-1 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<svg className="mr-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M11 17l-5-5m0 0l5-5m-5 5h12" />
|
||||
</svg>
|
||||
Volver al inicio
|
||||
@@ -311,9 +275,9 @@ export default function Login() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Floating elements */}
|
||||
<div className="absolute -top-4 -left-4 w-24 h-24 rounded-full blur-xl" style={{ backgroundColor: 'rgba(255, 255, 255, 0.1)' }}></div>
|
||||
<div className="absolute -bottom-4 -right-4 w-32 h-32 rounded-full blur-xl" style={{ backgroundColor: 'rgba(27, 42, 65, 0.2)' }}></div>
|
||||
{/* Floating decorations */}
|
||||
<div className="absolute -top-4 -left-4 w-24 h-24 rounded-full blur-xl" style={{ backgroundColor: 'rgba(255,255,255,0.1)' }} />
|
||||
<div className="absolute -bottom-4 -right-4 w-32 h-32 rounded-full blur-xl" style={{ backgroundColor: 'rgba(27,42,65,0.2)' }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -342,6 +342,7 @@ const handleDeleteSelectedPedimentoDocuments = async () => {
|
||||
const [selectedPartidas, setSelectedPartidas] = useState([]);
|
||||
const [downloadingPartidas, setDownloadingPartidas] = useState(false);
|
||||
const [downloadingAllPartidas, setDownloadingAllPartidas] = useState(false);
|
||||
const [downloadingPartidasDocs, setDownloadingPartidasDocs] = useState(false);
|
||||
|
||||
// Estados para credenciales VUCEM
|
||||
const [credenciales, setCredenciales] = useState([]);
|
||||
@@ -2474,8 +2475,42 @@ const handleDeleteSelectedPedimentoDocuments = async () => {
|
||||
|
||||
};
|
||||
|
||||
const handleDownloadSelectedPartidaVU = async () => {
|
||||
if (selectedPartidas.length === 0) {
|
||||
showMessage('No hay partidas seleccionadas para descargar', 'warning');
|
||||
return;
|
||||
}
|
||||
setDownloadingPartidasDocs(true);
|
||||
try {
|
||||
const response = await fetchWithAuth(`${API_URL}/record/documents/bulk-download-partidas-vu/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: selectedPartidas })
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.error || errorData?.message || `Error ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `partidas_vu_${selectedPartidas.length}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
showMessage('Documentos descargados exitosamente', 'success');
|
||||
} catch (error) {
|
||||
showMessage(`Error durante la descarga: ${error.message}`, 'error');
|
||||
} finally {
|
||||
setDownloadingPartidasDocs(false);
|
||||
}
|
||||
};
|
||||
|
||||
//--- Funciones de seleccion de Coves --- //
|
||||
const [selectedCoves, setSelectedCoves] = useState([]);
|
||||
const [downloadingCovesDocs, setDownloadingCovesDocs] = useState(false);
|
||||
|
||||
const allCoveIds=coves.map(cove => cove.id);
|
||||
const allCovesSelected=selectedCoves.length === allCoveIds.length && allCoveIds.length > 0;
|
||||
@@ -2536,6 +2571,39 @@ const handleDeleteSelectedPedimentoDocuments = async () => {
|
||||
|
||||
};
|
||||
|
||||
const handleDownloadSelectedCovesVU = async () => {
|
||||
if (selectedCoves.length === 0) {
|
||||
showMessage('No hay COVEs seleccionados para descargar', 'warning');
|
||||
return;
|
||||
}
|
||||
setDownloadingCovesDocs(true);
|
||||
try {
|
||||
const response = await fetchWithAuth(`${API_URL}/record/documents/bulk-download-coves-vu/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: selectedCoves })
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.error || errorData?.message || `Error ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `coves_vu_${selectedCoves.length}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
showMessage('Documentos descargados exitosamente', 'success');
|
||||
} catch (error) {
|
||||
showMessage(`Error durante la descarga: ${error.message}`, 'error');
|
||||
} finally {
|
||||
setDownloadingCovesDocs(false);
|
||||
}
|
||||
};
|
||||
|
||||
//--- Funciones seleccion de Pedimentos --- //
|
||||
const [selectedPedimentos, setSelectedPedimentos] = useState([]);
|
||||
const [isSelectAllPedimentos, setIsSelectAllPedimentos] = useState(false);
|
||||
@@ -2607,6 +2675,7 @@ const handleDeleteSelectedPedimentoDocuments = async () => {
|
||||
|
||||
//--- Funciones seleccion de Edocuments --- //
|
||||
const [selectedEdocs, setSelectedEdocs] = useState([]);
|
||||
const [downloadingEdocsDocs, setDownloadingEdocsDocs] = useState(false);
|
||||
|
||||
const allEdocIds=edocs.map(edoc => edoc.id);
|
||||
const allEdocsSelected=selectedEdocs.length === allEdocIds.length && allEdocIds.length > 0;
|
||||
@@ -2667,7 +2736,40 @@ const handleDeleteSelectedPedimentoDocuments = async () => {
|
||||
|
||||
};
|
||||
|
||||
//
|
||||
const handleDownloadSelectedEdocsVU = async () => {
|
||||
if (selectedEdocs.length === 0) {
|
||||
showMessage('No hay EDocuments seleccionados para descargar', 'warning');
|
||||
return;
|
||||
}
|
||||
setDownloadingEdocsDocs(true);
|
||||
try {
|
||||
const response = await fetchWithAuth(`${API_URL}/record/documents/bulk-download-edocs-vu/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ids: selectedEdocs })
|
||||
});
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null);
|
||||
throw new Error(errorData?.error || errorData?.message || `Error ${response.status}`);
|
||||
}
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `edocs_vu_${selectedEdocs.length}.zip`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
showMessage('Documentos descargados exitosamente', 'success');
|
||||
} catch (error) {
|
||||
showMessage(`Error durante la descarga: ${error.message}`, 'error');
|
||||
} finally {
|
||||
setDownloadingEdocsDocs(false);
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
const downloadAllPartidas = async () => {
|
||||
setDownloadingAllPartidas(true);
|
||||
try {
|
||||
@@ -2982,7 +3084,7 @@ const isEdoc = selectedDocumentForUpload?.tab === 'edoc';
|
||||
.then((d) => { setCoves(d.results || []); setCovesCount(d.count || 0); })
|
||||
.catch(err => console.error('Error recargando coves:', err));
|
||||
} else if (tab === 'edoc') {
|
||||
fetchPedimentoEdocs && fetchPedimentoEdocs(edocsPage, edocsPageSize, edocsFilters)
|
||||
fetchPedimentoEdocuments && fetchPedimentoEdocuments(edocsPage, edocsPageSize, edocsFilters)
|
||||
.then((d) => { setEdocs(d.results || []); setEdocsCount(d.count || 0); })
|
||||
.catch(err => console.error('Error recargando edocs:', err));
|
||||
}
|
||||
@@ -4668,6 +4770,16 @@ useEffect(() => {
|
||||
</svg>
|
||||
Eliminar seleccionados
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownloadSelectedPartidaVU}
|
||||
disabled={downloadingPartidasDocs}
|
||||
className="inline-flex items-center px-4 py-2 font-medium text-white transition-colors duration-200 bg-blue-600 rounded-lg shadow-sm hover:bg-blue-700 hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
{downloadingPartidasDocs ? 'Descargando...' : 'Descargar seleccionados'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -4722,7 +4834,7 @@ useEffect(() => {
|
||||
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
Descargar seleccionadas ({selectedPartidas.length})
|
||||
Procesar Descargas ({selectedPartidas.length})
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
@@ -4756,7 +4868,7 @@ useEffect(() => {
|
||||
if (errorCount > 0) showMessage(`${errorCount} partida(s) no se pudieron procesar`, 'error');
|
||||
}}
|
||||
>
|
||||
Descargar partidas
|
||||
Procesar Descarga partidas
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -5016,13 +5128,13 @@ useEffect(() => {
|
||||
onClick={handleDownloadAllAcuseCoves}
|
||||
className="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-green-600 border border-transparent rounded-md shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||
>
|
||||
Descargar todos los AcuseCoves
|
||||
Procesar Descargar de Acuses
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownloadAllCoves}
|
||||
className="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
|
||||
>
|
||||
Descargar todos los COVEs
|
||||
Procesar Descarga de COVEs
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -5128,10 +5240,20 @@ useEffect(() => {
|
||||
</svg>
|
||||
Eliminar seleccionados
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownloadSelectedCovesVU}
|
||||
disabled={downloadingCovesDocs}
|
||||
className="inline-flex items-center px-4 py-2 font-medium text-white transition-colors duration-200 bg-blue-600 rounded-lg shadow-sm hover:bg-blue-700 hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
{downloadingCovesDocs ? 'Descargando...' : 'Descargar seleccionados'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
)}
|
||||
|
||||
{covesLoading ? (
|
||||
<div className="flex items-center justify-center py-12">
|
||||
@@ -5441,7 +5563,7 @@ useEffect(() => {
|
||||
if (errorCount > 0) showMessage(`${errorCount} EDoc(s) no se pudieron procesar`, 'error');
|
||||
}}
|
||||
>
|
||||
Descargar todos los EDocs
|
||||
Procesar Descarga de EDocs
|
||||
</button>
|
||||
<button
|
||||
className="inline-flex items-center px-4 py-2 text-sm font-medium text-white transition-colors bg-green-600 border border-transparent rounded-md shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500"
|
||||
@@ -5469,7 +5591,7 @@ useEffect(() => {
|
||||
if (errorCount > 0) showMessage(`${errorCount} acuse(s) de EDoc no se pudieron descargar`, 'error');
|
||||
}}
|
||||
>
|
||||
Descargar Todos los acuses
|
||||
Procesar Descarga de acuses
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
@@ -5636,6 +5758,16 @@ useEffect(() => {
|
||||
</svg>
|
||||
Eliminar seleccionados
|
||||
</button>
|
||||
<button
|
||||
onClick={handleDownloadSelectedEdocsVU}
|
||||
disabled={downloadingEdocsDocs}
|
||||
className="inline-flex items-center px-4 py-2 font-medium text-white transition-colors duration-200 bg-blue-600 rounded-lg shadow-sm hover:bg-blue-700 hover:shadow-md disabled:opacity-50 disabled:cursor-not-allowed"
|
||||
>
|
||||
<svg className="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
|
||||
</svg>
|
||||
{downloadingEdocsDocs ? 'Descargando...' : 'Descargar seleccionados'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -553,7 +553,7 @@ useEffect(() => {
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<h1 className="flex flex-col gap-2 mb-1 text-2xl font-extrabold tracking-tight text-white sm:text-3xl lg:text-4xl sm:flex-row sm:items-center">
|
||||
<span>Procesos del Sistema</span>
|
||||
<span>Historial de Procesos del Sistema</span>
|
||||
{count > 0 && (
|
||||
<span className="inline-block px-3 py-1 text-xs font-semibold text-white rounded-full shadow-lg bg-white/20 backdrop-blur-sm sm:text-sm animate-fade-in">
|
||||
{count} procesos
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import React, { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTaskProgress } from '../context/TaskProgressContext';
|
||||
import { getCurrentUser } from '../api/users';
|
||||
// Helper to get current user with fetchWithAuth
|
||||
const fetchCurrentUserWithAuth = async () => {
|
||||
@@ -62,13 +63,16 @@ export default function Reports() {
|
||||
fetchOrgId();
|
||||
}, []);
|
||||
|
||||
const { tasks, addTask } = useTaskProgress();
|
||||
const pendingReportTasksRef = useRef(new Set());
|
||||
const pollingIntervalRef = useRef(null);
|
||||
|
||||
// Handler for Generar Reporte in Cumplimiento tab
|
||||
const handleGenerarReporteCumplimiento = async () => {
|
||||
if (!organizacionId) {
|
||||
showMessage('No se pudo obtener el ID de organización. Intenta de nuevo más tarde.', 'warning');
|
||||
return;
|
||||
}
|
||||
// Build query params from filtersCumplimiento and add organizacion_id
|
||||
const paramsObj = { ...filtersCumplimiento, organizacion_id: organizacionId };
|
||||
const params = Object.entries(paramsObj)
|
||||
.filter(([_, v]) => v)
|
||||
@@ -81,7 +85,19 @@ export default function Reports() {
|
||||
const errMsg = await extractApiError(res);
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
showMessage('Reporte solicitado correctamente. Aparecerá en el historial cuando esté listo.', 'success');
|
||||
const data = await res.json();
|
||||
if (data.task_id) {
|
||||
addTask({
|
||||
task_id: data.task_id,
|
||||
label: 'Reporte de Cumplimiento',
|
||||
organizacion_id: organizacionId,
|
||||
taskType: 'report',
|
||||
report_id: data.report_id,
|
||||
status: 'submitted',
|
||||
});
|
||||
pendingReportTasksRef.current.add(data.task_id);
|
||||
}
|
||||
showMessage('Reporte solicitado. Puedes ver el progreso en la barra inferior.', 'success');
|
||||
} catch (err) {
|
||||
showMessage(err.message || 'No se pudo generar el reporte', 'error');
|
||||
}
|
||||
@@ -142,6 +158,8 @@ export default function Reports() {
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
showMessage('Reporte solicitado correctamente. Aparecerá en el historial cuando esté listo.', 'success');
|
||||
fetchReports();
|
||||
startPolling();
|
||||
} catch (err) {
|
||||
showMessage(err.message || 'No se pudo generar el reporte', 'error');
|
||||
}
|
||||
@@ -182,10 +200,15 @@ export default function Reports() {
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
let filename = `reporte_${reportId}.csv`;
|
||||
const disposition = res.headers.get('Content-Disposition');
|
||||
if (disposition && disposition.includes('filename=')) {
|
||||
filename = disposition.split('filename=')[1].replace(/"/g, '').trim();
|
||||
let filename = '';
|
||||
if (disposition) {
|
||||
const match = disposition.match(/filename="?([^";\s]+)"?/);
|
||||
if (match) filename = match[1];
|
||||
}
|
||||
if (!filename) {
|
||||
const isXlsx = blob.type.includes('spreadsheetml') || blob.type.includes('openxmlformats');
|
||||
filename = `reporte_${reportId}.${isXlsx ? 'xlsx' : 'csv'}`;
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
link.href = window.URL.createObjectURL(blob);
|
||||
@@ -208,6 +231,7 @@ export default function Reports() {
|
||||
const [organizaciones, setOrganizaciones] = useState([]);
|
||||
const [importadores, setImportadores] = useState([]);
|
||||
const [rfcOptions, setRfcOptions] = useState([]);
|
||||
const [rfcsCumplimiento, setRfcsCumplimiento] = useState([]);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchOrganizaciones = async () => {
|
||||
@@ -242,6 +266,22 @@ export default function Reports() {
|
||||
fetchImportadores();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!organizacionId) return;
|
||||
const load = async () => {
|
||||
try {
|
||||
const url = `${API_URL}/reports/exportmodel/datastage/?organizacion=${organizacionId}`;
|
||||
const res = await fetchWithAuth(url);
|
||||
if (!res.ok) return;
|
||||
const data = await res.json();
|
||||
setRfcsCumplimiento(data.rfcs || []);
|
||||
} catch {
|
||||
setRfcsCumplimiento([]);
|
||||
}
|
||||
};
|
||||
load();
|
||||
}, [organizacionId]);
|
||||
|
||||
const [globalFilters, setGlobalFilters] = useState({
|
||||
rfc: '',
|
||||
fecha_pago_desde: '',
|
||||
@@ -493,8 +533,19 @@ export default function Reports() {
|
||||
// Estado para formato de exportación personalizado
|
||||
const [showFormatSelector, setShowFormatSelector] = useState(false);
|
||||
|
||||
// Estado para pestañas
|
||||
const [activeTab, setActiveTab] = useState('pedimentos');
|
||||
// Estado para pestañas — persiste en URL (?tab=...)
|
||||
const VALID_TABS = ['pedimentos', 'control_pedimentos', 'datastage', 'Cumplimiento', 'coves'];
|
||||
const [activeTab, setActiveTab] = useState(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const tab = params.get('tab');
|
||||
return VALID_TABS.includes(tab) ? tab : 'pedimentos';
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
params.set('tab', activeTab);
|
||||
history.replaceState(null, '', `${window.location.pathname}?${params.toString()}`);
|
||||
}, [activeTab]);
|
||||
|
||||
// Mostrar Cumplimiento en producción: eliminar lógica que oculta la pestaña
|
||||
|
||||
@@ -655,22 +706,59 @@ export default function Reports() {
|
||||
setTourStep(0);
|
||||
};
|
||||
|
||||
// Fetch report list from API
|
||||
useEffect(() => {
|
||||
const fetchReports = async () => {
|
||||
try {
|
||||
const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-list/`;
|
||||
const res = await fetchWithAuth(url);
|
||||
if (!res.ok) throw new Error('Error al obtener el historial de reportes');
|
||||
const data = await res.json();
|
||||
setReports(data);
|
||||
} catch (err) {
|
||||
setReports([]);
|
||||
}
|
||||
};
|
||||
fetchReports();
|
||||
const fetchReports = useCallback(async () => {
|
||||
try {
|
||||
const url = `${import.meta.env.VITE_EFC_API_URL}/reports/report-document-list/`;
|
||||
const res = await fetchWithAuth(url);
|
||||
if (!res.ok) throw new Error('Error al obtener el historial de reportes');
|
||||
const data = await res.json();
|
||||
setReports(data);
|
||||
} catch {
|
||||
setReports([]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const stopPolling = useCallback(() => {
|
||||
if (pollingIntervalRef.current) {
|
||||
clearInterval(pollingIntervalRef.current);
|
||||
pollingIntervalRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
const startPolling = useCallback(() => {
|
||||
if (pollingIntervalRef.current) return;
|
||||
pollingIntervalRef.current = setInterval(fetchReports, 5000);
|
||||
}, [fetchReports]);
|
||||
|
||||
useEffect(() => { fetchReports(); }, [fetchReports]);
|
||||
|
||||
// Detener polling cuando todos los reportes de control_pedimento lleguen a estado terminal
|
||||
useEffect(() => {
|
||||
const hasPending = reports
|
||||
.filter(r => r.report_type === 'control_pedimento')
|
||||
.some(r => r.status !== 'ready' && r.status !== 'error');
|
||||
if (!hasPending) stopPolling();
|
||||
}, [reports, stopPolling]);
|
||||
|
||||
// Limpiar intervalo al desmontar
|
||||
useEffect(() => () => stopPolling(), [stopPolling]);
|
||||
|
||||
// Refrescar historial cuando completa una tarea de reporte de cumplimiento
|
||||
useEffect(() => {
|
||||
if (!tasks || pendingReportTasksRef.current.size === 0) return;
|
||||
let changed = false;
|
||||
tasks.forEach(t => {
|
||||
if (
|
||||
pendingReportTasksRef.current.has(t.task_id) &&
|
||||
(t.status === 'completed' || t.status === 'failed')
|
||||
) {
|
||||
pendingReportTasksRef.current.delete(t.task_id);
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if (changed) fetchReports();
|
||||
}, [tasks, fetchReports]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchSummary();
|
||||
}, []);
|
||||
@@ -1727,39 +1815,144 @@ export default function Reports() {
|
||||
<div className="p-6">
|
||||
<h2 className="text-xl font-bold mb-2 text-blue-900">Generar reporte de Cumplimiento</h2>
|
||||
<p className="mb-4 text-gray-700">Aquí puedes generar y descargar el reporte de Cumplimiento.</p>
|
||||
{/* Filtros replicados */}
|
||||
<div className="max-w-7xl mx-auto mt-6 mb-4 px-4">
|
||||
<form onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
fetchSummary();
|
||||
}} className="bg-white rounded-lg shadow-sm border border-slate-200 p-4">
|
||||
<form onSubmit={(e) => e.preventDefault()} className="bg-white rounded-lg shadow-sm border border-slate-200 p-4">
|
||||
<div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-4">
|
||||
{Object.keys(initialFiltersCumplimiento).map((key) => (
|
||||
<div key={key}>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1" htmlFor={key}>
|
||||
{key.replace(/_/g, ' ').replace('gte', 'desde').replace('lte', 'hasta')}
|
||||
</label>
|
||||
<input
|
||||
type={key.includes('fecha') ? 'date' : 'text'}
|
||||
name={key}
|
||||
id={key}
|
||||
value={filtersCumplimiento[key]}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Organización — solo lectura */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Organización</label>
|
||||
<input
|
||||
type="text"
|
||||
readOnly
|
||||
value={organizaciones?.results?.find(o => o.id === organizacionId)?.nombre || organizacionId || ''}
|
||||
className="w-full border border-slate-200 rounded px-2 py-1 text-sm bg-slate-50 text-slate-500 cursor-not-allowed"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* RFC Contribuyente — dropdown dinámico */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">RFC Contribuyente</label>
|
||||
<select
|
||||
name="contribuyente__rfc"
|
||||
value={filtersCumplimiento.contribuyente__rfc}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500 bg-white"
|
||||
>
|
||||
<option value="">Todos los RFC</option>
|
||||
<option value="SIN_RFC">Pedimentos sin RFC</option>
|
||||
{rfcsCumplimiento.map(rfc => (
|
||||
<option key={rfc} value={rfc}>{rfc}</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
{/* Pedimento App */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Pedimento</label>
|
||||
<input
|
||||
type="text"
|
||||
name="pedimento_app"
|
||||
value={filtersCumplimiento.pedimento_app}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
placeholder="Ej. 21-160-3910-0003357"
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Aduana */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Aduana</label>
|
||||
<input
|
||||
type="text"
|
||||
name="aduana"
|
||||
value={filtersCumplimiento.aduana}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Patente */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Patente</label>
|
||||
<input
|
||||
type="text"
|
||||
name="patente"
|
||||
value={filtersCumplimiento.patente}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Régimen */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Régimen</label>
|
||||
<input
|
||||
type="text"
|
||||
name="regimen"
|
||||
value={filtersCumplimiento.regimen}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Agente Aduanal */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Agente Aduanal</label>
|
||||
<input
|
||||
type="text"
|
||||
name="agente_aduanal"
|
||||
value={filtersCumplimiento.agente_aduanal}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Tipo Operación */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Tipo Operación</label>
|
||||
<input
|
||||
type="text"
|
||||
name="tipo_operacion"
|
||||
value={filtersCumplimiento.tipo_operacion}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fecha Pago Desde */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Fecha pago desde</label>
|
||||
<input
|
||||
type="date"
|
||||
name="fecha_pago_gte"
|
||||
value={filtersCumplimiento.fecha_pago_gte}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Fecha Pago Hasta */}
|
||||
<div>
|
||||
<label className="block text-xs font-medium text-slate-600 mb-1">Fecha pago hasta</label>
|
||||
<input
|
||||
type="date"
|
||||
name="fecha_pago_lte"
|
||||
value={filtersCumplimiento.fecha_pago_lte}
|
||||
onChange={handleFilterChangeCumplimiento}
|
||||
className="w-full border border-slate-300 rounded px-2 py-1 text-sm focus:ring-blue-500 focus:border-blue-500"
|
||||
/>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
<div className="flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
className="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
|
||||
onClick={handleGenerarReporteCumplimiento}
|
||||
>
|
||||
Generar Reporte
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className="bg-green-600 text-white px-4 py-2 rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-offset-2 transition-colors"
|
||||
onClick={handleGenerarReporteCumplimiento}
|
||||
>
|
||||
Generar Reporte
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
114
src/pages/SSOCallback.jsx
Normal file
114
src/pages/SSOCallback.jsx
Normal file
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* Receptor del relay token del Hub.
|
||||
* Maneja dos flujos:
|
||||
* - SSO entre productos: Hub redirige a /auth/sso?relay=<uuid>
|
||||
* - Login con Microsoft: Hub redirige al mismo endpoint tras OAuth
|
||||
*/
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
const API_URL = import.meta.env.VITE_EFC_API_URL;
|
||||
|
||||
export default function SSOCallback() {
|
||||
const [error, setError] = useState(null);
|
||||
|
||||
useEffect(() => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const relay = params.get('relay');
|
||||
|
||||
if (!relay) {
|
||||
setError('No se recibió relay token. Acceso denegado.');
|
||||
return;
|
||||
}
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/auth/sso/exchange/`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ relay_token: relay }),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => ({}));
|
||||
throw new Error(body.detail || 'Error al iniciar sesión SSO');
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
// Guardar tokens en localStorage para fetchWithAuth
|
||||
if (data.access_token) {
|
||||
localStorage.setItem('access', data.access_token);
|
||||
}
|
||||
if (data.refresh_token) {
|
||||
localStorage.setItem('refresh', data.refresh_token);
|
||||
}
|
||||
|
||||
// Sincronizar datos de usuario
|
||||
const apiUrl = import.meta.env.VITE_EFC_API_URL || '';
|
||||
try {
|
||||
const [resUser, resPerms] = await Promise.all([
|
||||
fetch(`${apiUrl}/user/users/me/`, { headers: { Authorization: `Bearer ${data.access_token}` }, credentials: 'include' }),
|
||||
fetch(`${apiUrl}/rbac/my-permissions/`, { headers: { Authorization: `Bearer ${data.access_token}` }, credentials: 'include' }),
|
||||
]);
|
||||
if (resUser.ok) {
|
||||
const user = await resUser.json();
|
||||
if (user?.username) {
|
||||
localStorage.setItem('username', user.username);
|
||||
if (user.email) localStorage.setItem('user_email', user.email);
|
||||
if (user.id) localStorage.setItem('user_id', String(user.id));
|
||||
if (user.first_name) localStorage.setItem('user_first_name', user.first_name);
|
||||
if (user.last_name) localStorage.setItem('user_last_name', user.last_name);
|
||||
if (typeof user.is_importador !== 'undefined')
|
||||
localStorage.setItem('user_is_importador', String(user.is_importador));
|
||||
}
|
||||
}
|
||||
if (resPerms.ok) {
|
||||
const permsData = await resPerms.json();
|
||||
if (permsData?.permissions)
|
||||
localStorage.setItem('user_permissions', JSON.stringify(permsData.permissions));
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
window.dispatchEvent(new CustomEvent('authStateChanged'));
|
||||
window.location.href = '/admin';
|
||||
} catch (err) {
|
||||
setError(err.message || 'Error al iniciar sesión vía workspace');
|
||||
}
|
||||
})();
|
||||
}, []);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="max-w-md w-full bg-white rounded-2xl shadow-lg p-8 text-center space-y-4">
|
||||
<div className="w-12 h-12 bg-red-100 rounded-full flex items-center justify-center mx-auto">
|
||||
<svg className="w-6 h-6 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</div>
|
||||
<h2 className="text-lg font-bold text-gray-900">Error de inicio de sesión</h2>
|
||||
<p className="text-sm text-gray-600">{error}</p>
|
||||
<a
|
||||
href={`${import.meta.env.VITE_HUB_URL || 'http://localhost:3001'}/login`}
|
||||
className="inline-block mt-2 text-sm font-medium text-blue-600 hover:underline"
|
||||
>
|
||||
Volver al login
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-50">
|
||||
<div className="text-center space-y-3">
|
||||
<svg className="w-8 h-8 text-blue-500 animate-spin mx-auto" fill="none" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
|
||||
</svg>
|
||||
<p className="text-sm text-gray-600 font-medium">Iniciando sesión…</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -304,7 +304,8 @@ const Settings = () => {
|
||||
localStorage.removeItem('access');
|
||||
localStorage.removeItem('refresh');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
const _hub = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${_hub}/login?return_to=${encodeURIComponent(window.location.origin + '/auth/sso')}`;
|
||||
}, 2000);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -90,7 +90,11 @@ export default function UserForm() {
|
||||
// Cargar importadores
|
||||
useEffect(() => {
|
||||
const access = localStorage.getItem('access');
|
||||
if (!access) { window.location.href = '/login'; return; }
|
||||
if (!access) {
|
||||
const _hub = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${_hub}/login?return_to=${encodeURIComponent(window.location.origin + '/auth/sso')}`;
|
||||
return;
|
||||
}
|
||||
fetch(`${import.meta.env.VITE_EFC_API_URL}/customs/importadores/`, {
|
||||
headers: { Authorization: `Bearer ${access}` },
|
||||
})
|
||||
|
||||
@@ -91,7 +91,8 @@ export default function Users() {
|
||||
localStorage.removeItem('user_first_name');
|
||||
localStorage.removeItem('user_last_name');
|
||||
localStorage.removeItem('user_is_importador');
|
||||
window.location.href = '/login';
|
||||
const _hub = import.meta.env.VITE_HUB_URL || 'http://localhost:3001';
|
||||
window.location.href = `${_hub}/login?return_to=${encodeURIComponent(window.location.origin + '/auth/sso')}`;
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user