Registro y elevación de componentes base (ADN, Scripts, Servicios)

This commit is contained in:
Ricardo Monla
2026-02-15 20:37:53 -03:00
parent 9e9bf62c68
commit c865a7772b
25279 changed files with 3354766 additions and 0 deletions
+452
View File
@@ -0,0 +1,452 @@
import { Routes, Route } from 'react-router-dom'
import { Toaster } from 'react-hot-toast'
import { SidebarLayout } from './components/layout/SidebarLayout'
import Login from './pages/Login'
import Dashboard from './pages/Dashboard'
import EntityPage from './pages/EntityPage'
import Reportes from './pages/Reportes'
import Calendario from './pages/Calendario'
import Estadoproyecto from './pages/Estadoproyecto'
import Sistema from './pages/Sistema'
import PrivateRoute from './components/auth/PrivateRoute'
import { ThemeProvider } from './contexts/ThemeContext'
function App() {
return (
<ThemeProvider>
<div className="App">
{/* Global Theme CSS */}
<style>{`
/* Light Theme Variables */
:root {
/* Light Theme - Clean Professional Palette */
--bg-primary: #ffffff; /* Pure white background */
--bg-secondary: #f8fafc; /* Very light gray */
--bg-tertiary: #f1f5f9; /* Light gray */
--bg-card: #ffffff; /* White card backgrounds */
--bg-hover: #f1f5f9; /* Light hover states */
--bg-active: #4f46e5; /* Indigo blue accent */
--bg-input: #ffffff; /* White form inputs */
--bg-border: #e2e8f0; /* Light borders */
/* Text Colors */
--text-primary: #1e293b; /* Dark slate text */
--text-secondary: #475569; /* Medium slate */
--text-muted: #64748b; /* Muted slate */
--text-accent: #4f46e5; /* Indigo accent */
/* Border Colors */
--border-primary: #e2e8f0; /* Light gray borders */
--border-secondary: #cbd5e1; /* Medium light borders */
--border-focus: #4f46e5; /* Indigo focus */
/* Shadow Colors */
--shadow-primary: rgba(0, 0, 0, 0.1);
--shadow-secondary: rgba(0, 0, 0, 0.05);
--shadow-accent: rgba(79, 70, 229, 0.2);
/* Status Colors */
--success: #10b981; /* Green for success */
--warning: #f59e0b; /* Amber for warning */
--error: #ef4444; /* Red for error */
--info: #4f46e5; /* Indigo for info */
/* Transitions */
--transition-fast: 0.15s cubic-bezier(0.4, 0, 0.2, 1);
--transition-normal: 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
/* Dark Theme Variables */
.dark-theme {
/* AdGuard DNS Inspired Color Palette: Clean, Professional Dark Theme */
--bg-primary: #0a0a0a; /* Deep black background */
--bg-secondary: #1a1a1a; /* Dark gray */
--bg-tertiary: #2a2a2a; /* Medium dark gray */
--bg-card: #1a1a1a; /* Card backgrounds */
--bg-hover: #2a2a2a; /* Hover states */
--bg-active: #4f46e5; /* Indigo blue accent */
--bg-input: #1a1a1a; /* Form inputs */
--bg-border: #2a2a2a; /* Borders */
/* Text Colors */
--text-primary: #ffffff; /* Pure white text */
--text-secondary: #d1d5db; /* Light gray */
--text-muted: #9ca3af; /* Muted gray */
--text-accent: #4f46e5; /* Indigo accent */
/* Border Colors */
--border-primary: #374151; /* Gray-700 */
--border-secondary: #4b5563; /* Gray-600 */
--border-focus: #4f46e5; /* Indigo focus */
/* Shadow Colors */
--shadow-primary: rgba(0, 0, 0, 0.5);
--shadow-secondary: rgba(0, 0, 0, 0.3);
--shadow-accent: rgba(79, 70, 229, 0.4);
}
/* Global Theme Application */
body {
background: var(--bg-primary) !important;
color: var(--text-primary) !important;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
transition: background-color var(--transition-normal), color var(--transition-normal);
}
/* Cards and Containers */
.card {
background: var(--bg-card) !important;
border: 1px solid var(--border-primary) !important;
color: var(--text-primary) !important;
}
.card-header {
background: var(--bg-tertiary) !important;
border-bottom: 1px solid var(--border-primary) !important;
color: var(--text-primary) !important;
}
/* Tables */
.table {
color: var(--text-primary) !important;
}
.table thead th {
background: var(--bg-tertiary) !important;
border-color: var(--border-primary) !important;
color: var(--text-secondary) !important;
}
.table tbody tr {
background: var(--bg-secondary) !important;
border-color: var(--border-primary) !important;
}
.table tbody tr:nth-child(even) {
background: var(--bg-tertiary) !important;
}
.table tbody tr:hover {
background: var(--bg-hover) !important;
}
.table tbody td {
border-color: var(--border-primary) !important;
color: var(--text-primary) !important;
}
/* Forms */
.form-control {
background: var(--bg-input) !important;
border: 1px solid var(--border-primary) !important;
color: var(--text-primary) !important;
}
.form-control:focus {
background: var(--bg-input) !important;
border-color: var(--border-focus) !important;
color: var(--text-primary) !important;
box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25) !important;
}
.form-label {
color: var(--text-secondary) !important;
}
.form-select {
background: var(--bg-input) !important;
border: 1px solid var(--border-primary) !important;
color: var(--text-primary) !important;
}
/* Buttons */
.btn-primary {
background: var(--bg-active) !important;
border-color: var(--bg-active) !important;
color: white !important;
}
.btn-primary:hover {
background: #2563eb !important;
border-color: #2563eb !important;
}
.btn-secondary {
background: var(--bg-tertiary) !important;
border-color: var(--border-primary) !important;
color: var(--text-primary) !important;
}
.btn-outline-primary {
border-color: var(--bg-active) !important;
color: var(--bg-active) !important;
}
.btn-outline-primary:hover {
background: var(--bg-active) !important;
border-color: var(--bg-active) !important;
color: white !important;
}
/* Alerts and Notifications */
.alert-success {
background: rgba(16, 185, 129, 0.1) !important;
border-color: var(--success) !important;
color: var(--success) !important;
}
.alert-warning {
background: rgba(245, 158, 11, 0.1) !important;
border-color: var(--warning) !important;
color: var(--warning) !important;
}
.alert-danger {
background: rgba(239, 68, 68, 0.1) !important;
border-color: var(--error) !important;
color: var(--error) !important;
}
.alert-info {
background: rgba(59, 130, 246, 0.1) !important;
border-color: var(--info) !important;
color: var(--info) !important;
}
/* Badges */
.badge {
font-weight: 500 !important;
}
.bg-success {
background: var(--success) !important;
}
.bg-warning {
background: var(--warning) !important;
}
.bg-danger {
background: var(--error) !important;
}
.bg-info {
background: var(--info) !important;
}
.bg-primary {
background: var(--bg-active) !important;
}
.bg-secondary {
background: var(--bg-tertiary) !important;
}
/* Pagination */
.pagination .page-link {
background: var(--bg-secondary) !important;
border-color: var(--border-primary) !important;
color: var(--text-primary) !important;
}
.pagination .page-link:hover {
background: var(--bg-hover) !important;
border-color: var(--border-secondary) !important;
color: var(--text-primary) !important;
}
.pagination .page-item.active .page-link {
background: var(--bg-active) !important;
border-color: var(--bg-active) !important;
}
/* Dropdowns */
.dropdown-menu {
background: var(--bg-card) !important;
border: 1px solid var(--border-primary) !important;
box-shadow: 0 10px 15px -3px var(--shadow-primary), 0 4px 6px -2px var(--shadow-secondary) !important;
}
.dropdown-item {
color: var(--text-primary) !important;
}
.dropdown-item:hover {
background: var(--bg-hover) !important;
color: var(--text-primary) !important;
}
/* Modals */
.modal-content {
background: var(--bg-card) !important;
border: 1px solid var(--border-primary) !important;
color: var(--text-primary) !important;
}
.modal-header {
border-bottom: 1px solid var(--border-primary) !important;
}
.modal-footer {
border-top: 1px solid var(--border-primary) !important;
}
/* Bootstrap Utilities Override */
.text-primary { color: var(--text-accent) !important; }
.text-secondary { color: var(--text-secondary) !important; }
.text-muted { color: var(--text-muted) !important; }
.text-dark { color: #1f2937 !important; }
.text-light { color: var(--text-secondary) !important; }
.bg-light { background: var(--bg-tertiary) !important; }
.bg-white { background: var(--bg-secondary) !important; }
.border { border-color: var(--border-primary) !important; }
.border-top { border-top-color: var(--border-primary) !important; }
.border-bottom { border-bottom-color: var(--border-primary) !important; }
.border-left { border-left-color: var(--border-primary) !important; }
.border-right { border-right-color: var(--border-primary) !important; }
/* Links */
a {
color: var(--text-accent) !important;
}
a:hover {
color: #93c5fd !important;
}
/* Focus states for accessibility */
.form-control:focus,
.form-select:focus,
.btn:focus {
outline: 2px solid var(--border-focus) !important;
outline-offset: 2px !important;
}
/* Scrollbar styling for dark theme */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--bg-tertiary);
}
::-webkit-scrollbar-thumb {
background: var(--bg-border);
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--border-secondary);
}
/* Loading states */
.spinner-border {
border-color: var(--bg-active);
border-right-color: transparent;
}
/* Empty states */
.empty-state {
color: var(--text-muted);
}
.empty-state i {
color: var(--text-muted);
opacity: 0.5;
}
/* Specific component overrides */
.sidebar-main-content {
background: var(--bg-primary);
}
.entity-table {
background: var(--bg-card);
}
.entity-table thead th {
background: var(--bg-tertiary) !important;
border-color: var(--border-primary) !important;
}
.entity-table tbody td {
background: var(--bg-secondary);
border-color: var(--border-primary);
}
.entity-table tbody tr:nth-child(even) td {
background: var(--bg-tertiary);
}
.entity-table tbody tr:hover td {
background: var(--bg-hover);
}
/* Stats cards */
.stats-card {
background: var(--bg-card);
border: 1px solid var(--border-primary);
}
/* Filters section */
.filters-section {
background: var(--bg-secondary) !important;
border: 1px solid var(--border-primary) !important;
}
/* Form sections */
.form-section .card {
background: var(--bg-card) !important;
border: 1px solid var(--border-primary) !important;
}
.form-section .card-header {
background: var(--bg-tertiary) !important;
border-bottom: 1px solid var(--border-primary) !important;
}
`}</style>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/*" element={
<PrivateRoute>
<SidebarLayout>
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/tecnicos" element={<EntityPage />} />
<Route path="/tareas" element={<EntityPage />} />
<Route path="/reportes" element={<Reportes />} />
<Route path="/usuarios" element={<EntityPage />} />
<Route path="/calendario" element={<Calendario />} />
<Route path="/recursos" element={<EntityPage />} />
<Route path="/sistema" element={<Sistema />} />
<Route path="/estadoproyecto" element={<Estadoproyecto />} />
{/* Dynamic entity routes */}
<Route path="/entity/:entityKey" element={<EntityPage />} />
</Routes>
</SidebarLayout>
</PrivateRoute>
} />
</Routes>
<Toaster
position="top-right"
toastOptions={{
duration: 4000,
style: {
background: '#1e293b',
color: '#f8fafc',
border: '1px solid #334155',
},
}}
/>
</div>
</ThemeProvider>
)
}
export default App
@@ -0,0 +1,264 @@
import { useState } from 'react'
import { Tecnico } from '../stores/tecnicosStore'
import toast from 'react-hot-toast'
interface ChangePasswordModalProps {
tecnico: Tecnico | null
isOpen: boolean
onClose: () => void
}
const ChangePasswordModal = ({ tecnico, isOpen, onClose }: ChangePasswordModalProps) => {
const [formData, setFormData] = useState({
newPassword: '',
confirmPassword: '',
forceChange: false
})
const [isLoading, setIsLoading] = useState(false)
const [showPassword, setShowPassword] = useState(false)
const [showConfirmPassword, setShowConfirmPassword] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!tecnico) return
// Validaciones
if (!formData.newPassword) {
toast.error('La nueva contraseña es obligatoria')
return
}
if (!formData.confirmPassword) {
toast.error('La confirmación de contraseña es obligatoria')
return
}
if (formData.newPassword !== formData.confirmPassword) {
toast.error('Las contraseñas no coinciden')
return
}
if (!validatePasswordStrength(formData.newPassword)) {
toast.error('La contraseña debe tener al menos 8 caracteres, incluir mayúsculas, minúsculas, números y caracteres especiales')
return
}
try {
setIsLoading(true)
const response = await fetch(`http://localhost:3001/api/tecnicos/${tecnico.id}?action=change_password`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
new_password: formData.newPassword,
force_change: formData.forceChange
})
})
const data = await response.json()
if (data.success) {
toast.success('Contraseña cambiada exitosamente')
handleClose()
} else {
toast.error(data.message || 'Error al cambiar contraseña')
}
} catch (error) {
console.error('Error cambiando contraseña:', error)
toast.error('Error de conexión')
} finally {
setIsLoading(false)
}
}
const handleClose = () => {
setFormData({
newPassword: '',
confirmPassword: '',
forceChange: false
})
setShowPassword(false)
setShowConfirmPassword(false)
onClose()
}
const validatePasswordStrength = (password: string): boolean => {
const minLength = password.length >= 8
const hasUpperCase = /[A-Z]/.test(password)
const hasLowerCase = /[a-z]/.test(password)
const hasNumbers = /\d/.test(password)
const hasNonalphas = /[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/.test(password)
return minLength && hasUpperCase && hasLowerCase && hasNumbers && hasNonalphas
}
const getPasswordStrength = (password: string): { level: number; text: string; color: string } => {
if (password.length === 0) return { level: 0, text: '', color: '' }
let score = 0
if (password.length >= 8) score++
if (/[A-Z]/.test(password)) score++
if (/[a-z]/.test(password)) score++
if (/\d/.test(password)) score++
if (/[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/.test(password)) score++
if (score <= 2) return { level: 1, text: 'Débil', color: 'text-danger' }
if (score <= 3) return { level: 2, text: 'Regular', color: 'text-warning' }
if (score <= 4) return { level: 3, text: 'Buena', color: 'text-info' }
return { level: 4, text: 'Fuerte', color: 'text-success' }
}
if (!isOpen || !tecnico) return null
const passwordStrength = getPasswordStrength(formData.newPassword)
return (
<div className="modal fade show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">
<i className="fas fa-key me-2"></i>
Cambiar Contraseña
</h5>
<button type="button" className="btn-close" onClick={handleClose}></button>
</div>
<div className="modal-body">
<div className="alert alert-info">
<i className="fas fa-info-circle me-2"></i>
Cambiando contraseña para: <strong>{tecnico.first_name} {tecnico.last_name}</strong>
<br />
<small className="text-muted">ID DTIC: {tecnico.dtic_id}</small>
</div>
<form onSubmit={handleSubmit}>
<div className="mb-3">
<label htmlFor="newPassword" className="form-label">
Nueva Contraseña <span className="text-danger">*</span>
</label>
<div className="input-group">
<input
type={showPassword ? 'text' : 'password'}
className="form-control"
id="newPassword"
value={formData.newPassword}
onChange={(e) => setFormData({ ...formData, newPassword: e.target.value })}
placeholder="Ingrese la nueva contraseña"
required
/>
<button
className="btn btn-outline-secondary"
type="button"
onClick={() => setShowPassword(!showPassword)}
>
<i className={`fas fa-${showPassword ? 'eye-slash' : 'eye'}`}></i>
</button>
</div>
{formData.newPassword && (
<div className="mt-2">
<small className={`form-text ${passwordStrength.color}`}>
Fortaleza: {passwordStrength.text}
</small>
<div className="progress mt-1" style={{ height: '4px' }}>
<div
className={`progress-bar ${passwordStrength.level === 1 ? 'bg-danger' :
passwordStrength.level === 2 ? 'bg-warning' :
passwordStrength.level === 3 ? 'bg-info' : 'bg-success'}`}
style={{ width: `${(passwordStrength.level / 4) * 100}%` }}
></div>
</div>
</div>
)}
<div className="form-text">
La contraseña debe tener al menos 8 caracteres, incluir mayúsculas, minúsculas, números y caracteres especiales.
</div>
</div>
<div className="mb-3">
<label htmlFor="confirmPassword" className="form-label">
Confirmar Contraseña <span className="text-danger">*</span>
</label>
<div className="input-group">
<input
type={showConfirmPassword ? 'text' : 'password'}
className="form-control"
id="confirmPassword"
value={formData.confirmPassword}
onChange={(e) => setFormData({ ...formData, confirmPassword: e.target.value })}
placeholder="Confirme la nueva contraseña"
required
/>
<button
className="btn btn-outline-secondary"
type="button"
onClick={() => setShowConfirmPassword(!showConfirmPassword)}
>
<i className={`fas fa-${showConfirmPassword ? 'eye-slash' : 'eye'}`}></i>
</button>
</div>
{formData.confirmPassword && formData.newPassword !== formData.confirmPassword && (
<div className="mt-1">
<small className="form-text text-danger">
Las contraseñas no coinciden
</small>
</div>
)}
</div>
<div className="mb-3">
<div className="form-check">
<input
className="form-check-input"
type="checkbox"
id="forceChange"
checked={formData.forceChange}
onChange={(e) => setFormData({ ...formData, forceChange: e.target.checked })}
/>
<label className="form-check-label" htmlFor="forceChange">
Forzar cambio de contraseña en el próximo inicio de sesión
</label>
</div>
<div className="form-text">
Si se marca, el técnico deberá cambiar su contraseña la próxima vez que inicie sesión.
</div>
</div>
</form>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={handleClose}
disabled={isLoading}
>
Cancelar
</button>
<button
type="button"
className="btn btn-warning"
onClick={handleSubmit}
disabled={isLoading || !formData.newPassword || !formData.confirmPassword || formData.newPassword !== formData.confirmPassword}
>
{isLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2" role="status"></span>
Cambiando...
</>
) : (
<>
<i className="fas fa-save me-2"></i>
Cambiar Contraseña
</>
)}
</button>
</div>
</div>
</div>
</div>
)
}
export default ChangePasswordModal
@@ -0,0 +1,299 @@
import { useEffect, useState } from 'react'
import { Recurso } from '../stores/recursosStore'
import { recursoUtils } from '../utils/entityUtils'
import { ResourceAssignmentControl } from './common/ResourceAssignmentControl'
import { useResourceAssignment } from '../hooks/useResourceAssignment'
interface RecursoProfileModalProps {
recurso: Recurso | null
isOpen: boolean
onClose: () => void
onEdit: (id: number) => void
}
interface RecursoStats {
total_assignments: number
active_assignments: number
assignment_history: any[]
maintenance_history: any[]
}
const RecursoProfileModal = ({ recurso, isOpen, onClose, onEdit }: RecursoProfileModalProps) => {
const [stats, setStats] = useState<RecursoStats | null>(null)
const [loading, setLoading] = useState(false)
// Initialize resource assignment hook for this recurso
const resourceAssignment = useResourceAssignment('recurso', recurso.id)
// Load assigned resources when modal opens
useEffect(() => {
if (isOpen && recurso) {
resourceAssignment.refreshAssignments()
}
}, [isOpen, recurso?.id])
useEffect(() => {
if (recurso && isOpen) {
fetchRecursoStats()
}
}, [recurso, isOpen])
const fetchRecursoStats = async () => {
if (!recurso) return
setLoading(true)
try {
const response = await fetch(`/api/recursos/${recurso.id}?include_history=true`)
const data = await response.json()
if (data.success) {
setStats({
total_assignments: data.data.resource.total_assignments || 0,
active_assignments: data.data.resource.active_assignments || 0,
assignment_history: data.data.resource.assignment_history || [],
maintenance_history: data.data.resource.maintenance_history || []
})
}
} catch (error) {
console.error('Error fetching recurso stats:', error)
} finally {
setLoading(false)
}
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('es-AR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
if (!isOpen || !recurso) return null
return (
<div className="modal fade show d-block" tabIndex={-1} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header bg-primary text-white">
<h5 className="modal-title">
<i className={`fas ${recursoUtils.getIcon(recurso.category)} me-2`}></i>Perfil de {recurso.name}
</h5>
<button
type="button"
className="btn-close btn-close-white"
onClick={onClose}
></button>
</div>
<div className="modal-body">
<div className="row">
{/* Información básica y avatar */}
<div className="col-md-4 text-center mb-4">
<div className="avatar-circle bg-primary text-white mx-auto mb-3"
style={{ width: '80px', height: '80px', fontSize: '2rem', border: '4px solid #dee2e6' }}>
<i className={`fas ${recursoUtils.getIcon(recurso.category)}`}></i>
</div>
<h5 className="mb-1">{recurso.name}</h5>
<span className={`badge fs-6 mb-2 ${recurso.status === 'available' ? 'bg-success' : recurso.status === 'assigned' ? 'bg-info' : recurso.status === 'maintenance' ? 'bg-warning' : 'bg-secondary'}`}>
{recursoUtils.getBadge(recurso.status).text}
</span>
<div>
<span className={`badge fs-6 ${recurso.category === 'hardware' ? 'bg-primary' : recurso.category === 'software' ? 'bg-info' : recurso.category === 'network' ? 'bg-success' : recurso.category === 'security' ? 'bg-danger' : 'bg-secondary'}`}>
{recursoUtils.formatCategory(recurso.category)}
</span>
</div>
</div>
{/* Información detallada */}
<div className="col-md-8">
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">ID DTIC</strong>
<span className="badge bg-light text-dark fs-6">{recurso.dtic_id}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Categoría</strong>
<span>{recursoUtils.formatCategory(recurso.category)}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Estado</strong>
<span className={`badge ${recurso.status === 'available' ? 'bg-success' : recurso.status === 'assigned' ? 'bg-info' : recurso.status === 'maintenance' ? 'bg-warning' : 'bg-secondary'}`}>
{recursoUtils.getBadge(recurso.status).text}
</span>
</div>
</div>
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Ubicación</strong>
<span>{recurso.location || 'No especificada'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Modelo</strong>
<span>{recurso.model || 'No especificado'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Número de Serie</strong>
<span>{recurso.serial_number || 'No especificado'}</span>
</div>
</div>
</div>
{recurso.description && (
<>
<hr />
<div className="mb-3">
<strong className="text-muted d-block">Descripción</strong>
<p className="mb-0">{recurso.description}</p>
</div>
</>
)}
{recurso.technical_specs && (
<>
<hr />
<div className="mb-3">
<strong className="text-muted d-block">Especificaciones Técnicas</strong>
<pre className="bg-light p-2 rounded small">{JSON.stringify(recurso.technical_specs, null, 2)}</pre>
</div>
</>
)}
<hr />
{/* Estadísticas de asignaciones */}
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-chart-bar me-2"></i>Estadísticas de Relaciones
</h6>
{loading ? (
<div className="text-center py-3">
<div className="spinner-border spinner-border-sm text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
</div>
) : stats ? (
<div className="row text-center mb-4">
<div className="col-sm-6">
<div className="p-3 bg-light rounded">
<div className="h4 text-primary mb-1">{stats.total_assignments}</div>
<small className="text-muted fw-bold">Total Relaciones</small>
</div>
</div>
<div className="col-sm-6">
<div className="p-3 bg-info rounded text-white">
<div className="h4 mb-1">{stats.active_assignments}</div>
<small className="fw-bold">Relaciones Activas</small>
</div>
</div>
</div>
) : null}
{/* Historial de asignaciones */}
{stats && stats.assignment_history && stats.assignment_history.length > 0 && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-history me-2"></i>Historial de Relaciones
</h6>
<div className="list-group mb-4">
{stats.assignment_history.slice(0, 5).map((assignment: any, index: number) => (
<div key={index} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{assignment.usuario_name || 'Usuario desconocido'}</h6>
<small className={`badge ${assignment.action === 'assigned' ? 'bg-success' : 'bg-warning'}`}>
{assignment.action === 'assigned' ? 'Relacionado' : 'Desrelacionado'}
</small>
</div>
<p className="mb-1">ID DTIC: {assignment.usuario_dtic_id}</p>
<small className="text-muted">
{assignment.action === 'assigned' ? 'Relacionado' : 'Desrelacionado'}: {formatDate(assignment.created_at)}
{assignment.tecnico_name && ` • Por: ${assignment.tecnico_name}`}
</small>
</div>
))}
</div>
</>
)}
{/* Historial de mantenimiento */}
{stats && stats.maintenance_history && stats.maintenance_history.length > 0 && (
<>
<h6 className="fw-bold text-warning mb-3">
<i className="fas fa-tools me-2"></i>Historial de Mantenimiento
</h6>
<div className="list-group">
{stats.maintenance_history.slice(0, 3).map((maintenance: any, index: number) => (
<div key={index} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{maintenance.action || 'Mantenimiento'}</h6>
<small className="badge bg-warning text-dark">
{formatDate(maintenance.created_at)}
</small>
</div>
{maintenance.details && <p className="mb-1">{maintenance.details}</p>}
<small className="text-muted">
{maintenance.tecnico_name && `Técnico: ${maintenance.tecnico_name}`}
</small>
</div>
))}
</div>
</>
)}
{stats && (!stats.assignment_history || stats.assignment_history.length === 0) &&
(!stats.maintenance_history || stats.maintenance_history.length === 0) && (
<div className="text-center py-4 text-muted">
<i className="fas fa-inbox fa-2x mb-2"></i>
<p>No hay historial disponible</p>
</div>
)}
{/* Resource Assignment Control - Reverse Assignment View */}
<hr className="my-4" />
<h6 className="fw-bold text-info mb-3">
<i className="fas fa-link me-2"></i>Entidades que Usan Este Recurso
</h6>
<div className="bg-light p-3 rounded">
<p className="text-muted mb-0">
<i className="fas fa-info-circle me-2"></i>
Este recurso actualmente está relacionado con {stats?.active_assignments || 0} entidad{stats?.active_assignments !== 1 ? 'es' : ''}.
</p>
{stats && stats.active_assignments > 0 && (
<small className="text-muted">
Las asignaciones se pueden gestionar desde los perfiles de tareas y usuarios.
</small>
)}
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
>
<i className="fas fa-times me-2"></i>Cerrar
</button>
<button
type="button"
className="btn btn-warning"
onClick={() => {
onClose()
onEdit(recurso.id)
}}
>
<i className="fas fa-edit me-2"></i>Editar Recurso
</button>
</div>
</div>
</div>
</div>
)
}
export default RecursoProfileModal
@@ -0,0 +1,174 @@
import React, { useEffect } from 'react'
import { Tarea } from '../stores/tareasStore'
import { tareaUtils } from '../utils/entityUtils'
import { ResourceAssignmentControl } from './common/ResourceAssignmentControl'
import { useResourceAssignment } from '../hooks/useResourceAssignment'
interface TareaProfileModalProps {
tarea: Tarea | null
isOpen: boolean
onClose: () => void
onEdit: (id: number) => void
onRefresh?: () => void
}
const TareaProfileModal: React.FC<TareaProfileModalProps> = ({
tarea,
isOpen,
onClose,
onEdit,
onRefresh
}) => {
if (!isOpen || !tarea) return null
// Initialize resource assignment hook for this tarea
const resourceAssignment = useResourceAssignment('tarea', tarea.id)
// Load assigned resources when modal opens
useEffect(() => {
if (isOpen && tarea) {
resourceAssignment.refreshAssignments()
}
}, [isOpen, tarea?.id])
return (
<div className="modal show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-xl">
<div className="modal-content">
<div className="modal-header bg-primary text-white">
<h5 className="modal-title">
<i className="fas fa-tasks me-2"></i>
Detalles de Tarea
</h5>
<button
type="button"
className="btn-close btn-close-white"
onClick={onClose}
></button>
</div>
<div className="modal-body">
<div className="row">
<div className="col-md-8">
<h4 className="mb-3">{tarea.title}</h4>
{tarea.description && (
<p className="text-muted mb-4">{tarea.description}</p>
)}
</div>
<div className="col-md-4 text-end">
<span className={`badge fs-6 ${tareaUtils.getBadge(tarea.status).class}`}>
{tareaUtils.getBadge(tarea.status).text}
</span>
</div>
</div>
<div className="row g-3">
<div className="col-md-4">
<div className="card h-100">
<div className="card-body">
<h6 className="card-title">
<i className="fas fa-info-circle me-2 text-primary"></i>
Información General
</h6>
<hr />
<p className="mb-2"><strong>ID DTIC:</strong> {tarea.dtic_id}</p>
<p className="mb-2">
<strong>Prioridad:</strong>
<span className={`badge ms-2 ${tareaUtils.getBadge(tarea.priority).class}`}>
{tareaUtils.formatPriority(tarea.priority)}
</span>
</p>
<p className="mb-2"><strong>Estado:</strong> {tareaUtils.getBadge(tarea.status).text}</p>
<p className="mb-2"><strong>Creada:</strong> {tareaUtils.formatDate(tarea.created_at)}</p>
<p className="mb-2"><strong>Actualizada:</strong> {tareaUtils.formatDate(tarea.updated_at)}</p>
{tarea.due_date && (
<p className="mb-2"><strong>Fecha límite:</strong> {tareaUtils.formatDate(tarea.due_date)}</p>
)}
{tarea.completed_at && (
<p className="mb-0"><strong>Completada:</strong> {tareaUtils.formatDate(tarea.completed_at)}</p>
)}
</div>
</div>
</div>
<div className="col-md-4">
<div className="card h-100">
<div className="card-body">
<h6 className="card-title">
<i className="fas fa-user me-2 text-success"></i>
Asignación
</h6>
<hr />
{tarea.technician_name ? (
<>
<p className="mb-2"><strong>Técnico relacionado:</strong></p>
<div className="d-flex align-items-center">
<div className="avatar-circle bg-primary text-white me-3" style={{ width: '40px', height: '40px' }}>
<i className="fas fa-user"></i>
</div>
<div>
<h6 className="mb-0">{tarea.technician_name}</h6>
<small className="text-muted">ID: {tarea.technician_id}</small>
</div>
</div>
</>
) : (
<div className="text-center py-3">
<i className="fas fa-user-slash fa-2x text-muted mb-2"></i>
<p className="text-muted mb-0">Sin técnico relacionado</p>
</div>
)}
</div>
</div>
</div>
<div className="col-md-4">
<div className="card h-100">
<div className="card-body">
<h6 className="card-title">
<i className="fas fa-boxes me-2 text-info"></i>
Recursos Relacionados
</h6>
<hr />
<ResourceAssignmentControl
entityId={tarea.id}
entityType="tarea"
assignedResources={resourceAssignment.assignedResources}
availableResources={resourceAssignment.availableResources}
onAssignResource={resourceAssignment.assignResource}
onUnassignResource={resourceAssignment.unassignResource}
loading={resourceAssignment.loading}
className="border-0 p-0"
showAddIcon={true}
maxHeight="300px"
/>
</div>
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
>
<i className="fas fa-times me-2"></i>Cerrar
</button>
<button
type="button"
className="btn btn-primary"
onClick={() => {
onEdit(tarea.id)
onClose()
}}
>
<i className="fas fa-edit me-2"></i>Editar Tarea
</button>
</div>
</div>
</div>
</div>
)
}
export default TareaProfileModal
@@ -0,0 +1,288 @@
import { useEffect, useState } from 'react'
import { Tecnico } from '../stores/tecnicosStore'
import { ResourceAssignmentControl } from './common/ResourceAssignmentControl'
import { useResourceAssignment } from '../hooks/useResourceAssignment'
interface TecnicoProfileModalProps {
tecnico: Tecnico | null
isOpen: boolean
onClose: () => void
onEdit: (id: number) => void
}
interface TecnicoStats {
total_tasks: number
completed_tasks: number
active_tasks: number
recent_tasks: any[]
}
const TecnicoProfileModal = ({ tecnico, isOpen, onClose, onEdit }: TecnicoProfileModalProps) => {
const [stats, setStats] = useState<TecnicoStats | null>(null)
const [loading, setLoading] = useState(false)
// Initialize resource assignment hook for this tecnico
const resourceAssignment = useResourceAssignment('tecnico', tecnico.id)
// Load assigned resources when modal opens
useEffect(() => {
if (isOpen && tecnico) {
resourceAssignment.refreshAssignments()
}
}, [isOpen, tecnico?.id])
useEffect(() => {
if (tecnico && isOpen) {
fetchTecnicoStats()
}
}, [tecnico, isOpen])
const fetchTecnicoStats = async () => {
if (!tecnico) return
setLoading(true)
try {
const response = await fetch(`http://localhost:3001/api/tecnicos/${tecnico.id}?include_tasks=true`)
const data = await response.json()
if (data.success) {
setStats({
total_tasks: data.data.technician.total_tasks || 0,
completed_tasks: data.data.technician.completed_tasks || 0,
active_tasks: data.data.technician.active_tasks || 0,
recent_tasks: data.data.technician.recent_tasks || []
})
}
} catch (error) {
console.error('Error fetching tecnico stats:', error)
} finally {
setLoading(false)
}
}
const formatRole = (role: string) => {
const roles = {
'admin': 'Administrador',
'technician': 'Técnico',
'viewer': 'Visualizador'
}
return roles[role as keyof typeof roles] || role
}
const formatDepartment = (dept: string) => {
const departments = {
'dtic': 'DTIC',
'sistemas': 'Sistemas',
'redes': 'Redes',
'seguridad': 'Seguridad'
}
return departments[dept as keyof typeof departments] || dept
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('es-AR', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
}
const formatTaskStatus = (status: string) => {
const statuses = {
'pending': 'Pendiente',
'in_progress': 'En Progreso',
'completed': 'Completada',
'cancelled': 'Cancelada'
}
return statuses[status as keyof typeof statuses] || status
}
if (!isOpen || !tecnico) return null
return (
<div className="modal fade show d-block" tabIndex={-1} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header bg-primary text-white">
<h5 className="modal-title">
<i className="fas fa-user me-2"></i>Perfil de {tecnico.first_name} {tecnico.last_name}
</h5>
<button
type="button"
className="btn-close btn-close-white"
onClick={onClose}
></button>
</div>
<div className="modal-body">
<div className="row">
{/* Información básica y avatar */}
<div className="col-md-4 text-center mb-4">
<div className="avatar-circle bg-primary text-white mx-auto mb-3"
style={{ width: '80px', height: '80px', fontSize: '2rem', border: '4px solid #dee2e6' }}>
<i className="fas fa-user"></i>
</div>
<h5 className="mb-1">{tecnico.full_name}</h5>
<span className={`badge fs-6 mb-2 ${tecnico.role === 'admin' ? 'bg-danger' : tecnico.role === 'technician' ? 'bg-info' : 'bg-secondary'}`}>
{formatRole(tecnico.role)}
</span>
<div>
<span className={`badge ${tecnico.is_active ? 'bg-success' : 'bg-warning'} fs-6`}>
{tecnico.is_active ? 'Activo' : 'Inactivo'}
</span>
</div>
</div>
{/* Información detallada */}
<div className="col-md-8">
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">ID DTIC</strong>
<span className="badge bg-light text-dark fs-6">{tecnico.dtic_id}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Email</strong>
<span>{tecnico.email}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Teléfono</strong>
<span>{tecnico.phone || 'No especificado'}</span>
</div>
</div>
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Departamento</strong>
<span>{formatDepartment(tecnico.department)}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Registro</strong>
<span>{formatDate(tecnico.created_at)}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Última actualización</strong>
<span>{formatDate(tecnico.updated_at)}</span>
</div>
</div>
</div>
<hr />
{/* Estadísticas de tareas */}
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-chart-bar me-2"></i>Estadísticas de Tareas
</h6>
{loading ? (
<div className="text-center py-3">
<div className="spinner-border spinner-border-sm text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
</div>
) : stats ? (
<div className="row text-center mb-4">
<div className="col-sm-4">
<div className="p-3 bg-light rounded">
<div className="h4 text-primary mb-1">{stats.total_tasks}</div>
<small className="text-muted fw-bold">Total Tareas</small>
</div>
</div>
<div className="col-sm-4">
<div className="p-3 bg-success rounded text-white">
<div className="h4 mb-1">{stats.completed_tasks}</div>
<small className="fw-bold">Completadas</small>
</div>
</div>
<div className="col-sm-4">
<div className="p-3 bg-warning rounded">
<div className="h4 text-dark mb-1">{stats.active_tasks}</div>
<small className="text-dark fw-bold">Activas</small>
</div>
</div>
</div>
) : null}
{/* Tareas recientes */}
{stats && stats.recent_tasks && stats.recent_tasks.length > 0 && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-clock me-2"></i>Tareas Recientes
</h6>
<div className="list-group">
{stats.recent_tasks.slice(0, 3).map((task: any, index: number) => (
<div key={index} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{task.title}</h6>
<small className={`badge ${
task.status === 'completed' ? 'bg-success' :
task.status === 'in_progress' ? 'bg-warning text-dark' :
'bg-secondary'
}`}>
{formatTaskStatus(task.status)}
</small>
</div>
<p className="mb-1">{task.description || 'Sin descripción'}</p>
<small className="text-muted">
Creada: {formatDate(task.created_at)}
{task.due_date && ` • Vence: ${formatDate(task.due_date)}`}
</small>
</div>
))}
</div>
</>
)}
{stats && (!stats.recent_tasks || stats.recent_tasks.length === 0) && (
<div className="text-center py-4 text-muted">
<i className="fas fa-inbox fa-2x mb-2"></i>
<p>No hay tareas recientes</p>
</div>
)}
{/* Resource Assignment Control */}
<hr className="my-4" />
<h6 className="fw-bold text-info mb-3">
<i className="fas fa-boxes me-2"></i>Gestión de Recursos Asignados
</h6>
<ResourceAssignmentControl
entityId={tecnico.id}
entityType="tecnico"
assignedResources={resourceAssignment.assignedResources}
availableResources={resourceAssignment.availableResources}
onAssignResource={resourceAssignment.assignResource}
onUnassignResource={resourceAssignment.unassignResource}
loading={resourceAssignment.loading}
className="border-0 p-0"
showAddIcon={true}
maxHeight="250px"
/>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
>
<i className="fas fa-times me-2"></i>Cerrar
</button>
<button
type="button"
className="btn btn-warning"
onClick={() => {
onClose()
onEdit(tecnico.id)
}}
>
<i className="fas fa-edit me-2"></i>Editar Técnico
</button>
</div>
</div>
</div>
</div>
)
}
export default TecnicoProfileModal
@@ -0,0 +1,310 @@
import { useEffect, useState } from 'react'
import { ResourceAssignmentControl } from './common/ResourceAssignmentControl'
import { useResourceAssignment } from '../hooks/useResourceAssignment'
interface UsuarioRelacionado {
id: number
dtic_id: string
first_name: string
last_name: string
full_name?: string
email?: string
phone?: string
department?: string
position?: string
created_at: string
updated_at?: string
assigned_resources_count?: number
}
interface UsuarioProfileModalProps {
usuario: UsuarioRelacionado | null
isOpen: boolean
onClose: () => void
onEdit: (id: number) => void
}
interface UsuarioStats {
total_assignments: number
active_assignments: number
assignment_history: any[]
resource_categories: { [key: string]: number }
}
const UsuarioProfileModal = ({ usuario, isOpen, onClose, onEdit }: UsuarioProfileModalProps) => {
const [stats, setStats] = useState<UsuarioStats | null>(null)
const [loading, setLoading] = useState(false)
// Initialize resource assignment hook for this usuario
const resourceAssignment = useResourceAssignment('usuario', usuario.id)
// Load assigned resources when modal opens
useEffect(() => {
if (isOpen && usuario) {
resourceAssignment.refreshAssignments()
}
}, [isOpen, usuario?.id])
useEffect(() => {
if (usuario && isOpen) {
fetchUsuarioStats()
}
}, [usuario, isOpen])
const fetchUsuarioStats = async () => {
if (!usuario) return
setLoading(true)
try {
const response = await fetch(`/api/usuarios_relacionados/${usuario.id}?include_history=true`)
const data = await response.json()
if (data.success) {
setStats({
total_assignments: data.data.usuario.total_assignments || 0,
active_assignments: data.data.usuario.active_assignments || 0,
assignment_history: data.data.usuario.assignment_history || [],
resource_categories: data.data.usuario.resource_categories || {}
})
}
} catch (error) {
console.error('Error fetching usuario stats:', error)
} finally {
setLoading(false)
}
}
const formatDepartment = (dept: string) => {
const departments = {
'dtic': 'DTIC',
'sistemas': 'Sistemas',
'redes': 'Redes',
'seguridad': 'Seguridad'
}
return departments[dept as keyof typeof departments] || dept
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('es-AR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
const formatCategory = (category: string) => {
const categories = {
'hardware': 'Hardware',
'software': 'Software',
'network': 'Redes',
'security': 'Seguridad',
'tools': 'Herramientas',
'facilities': 'Instalaciones'
}
return categories[category as keyof typeof categories] || category
}
if (!isOpen || !usuario) return null
return (
<div className="modal fade show d-block" tabIndex={-1} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header bg-primary text-white">
<h5 className="modal-title">
<i className="fas fa-user me-2"></i>Perfil de {usuario.full_name || `${usuario.first_name} ${usuario.last_name}`}
</h5>
<button
type="button"
className="btn-close btn-close-white"
onClick={onClose}
></button>
</div>
<div className="modal-body">
<div className="row">
{/* Información básica y avatar */}
<div className="col-md-4 text-center mb-4">
<div className="avatar-circle bg-primary text-white mx-auto mb-3"
style={{ width: '80px', height: '80px', fontSize: '2rem', border: '4px solid #dee2e6' }}>
<i className="fas fa-user"></i>
</div>
<h5 className="mb-1">{usuario.full_name || `${usuario.first_name} ${usuario.last_name}`}</h5>
{usuario.position && (
<span className="badge fs-6 mb-2 bg-info">
{usuario.position}
</span>
)}
<div>
<span className="badge fs-6 bg-secondary">
Usuario Relacionado
</span>
</div>
</div>
{/* Información detallada */}
<div className="col-md-8">
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">ID DTIC</strong>
<span className="badge bg-light text-dark fs-6">{usuario.dtic_id}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Email</strong>
<span>{usuario.email || 'No especificado'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Teléfono</strong>
<span>{usuario.phone || 'No especificado'}</span>
</div>
</div>
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Departamento</strong>
<span>{usuario.department ? formatDepartment(usuario.department) : 'No especificado'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Cargo</strong>
<span>{usuario.position || 'No especificado'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Registro</strong>
<span>{formatDate(usuario.created_at)}</span>
</div>
</div>
</div>
<hr />
{/* Estadísticas de recursos asignados */}
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-chart-bar me-2"></i>Estadísticas de Recursos Relacionados
</h6>
{loading ? (
<div className="text-center py-3">
<div className="spinner-border spinner-border-sm text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
</div>
) : stats ? (
<div className="row text-center mb-4">
<div className="col-sm-6">
<div className="p-3 bg-light rounded">
<div className="h4 text-primary mb-1">{stats.total_assignments}</div>
<small className="text-muted fw-bold">Total Relaciones</small>
</div>
</div>
<div className="col-sm-6">
<div className="p-3 bg-success rounded text-white">
<div className="h4 mb-1">{stats.active_assignments}</div>
<small className="fw-bold">Relaciones Activas</small>
</div>
</div>
</div>
) : null}
{/* Categorías de recursos */}
{stats && stats.resource_categories && Object.keys(stats.resource_categories).length > 0 && (
<>
<h6 className="fw-bold text-info mb-3">
<i className="fas fa-tags me-2"></i>Categorías de Recursos Relacionados
</h6>
<div className="row mb-4">
{Object.entries(stats.resource_categories).map(([category, count]) => (
<div key={category} className="col-sm-6 col-md-4 mb-2">
<div className="p-2 bg-light rounded text-center">
<div className="fw-bold text-primary">{count}</div>
<small className="text-muted">{formatCategory(category)}</small>
</div>
</div>
))}
</div>
</>
)}
{/* Historial de asignaciones */}
{stats && stats.assignment_history && stats.assignment_history.length > 0 && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-history me-2"></i>Historial de Relaciones
</h6>
<div className="list-group">
{stats.assignment_history.slice(0, 5).map((assignment: any, index: number) => (
<div key={index} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{assignment.recurso_name || 'Recurso desconocido'}</h6>
<small className={`badge ${assignment.action === 'assigned' ? 'bg-success' : 'bg-warning'}`}>
{assignment.action === 'assigned' ? 'Relacionado' : 'Desrelacionado'}
</small>
</div>
<p className="mb-1">
ID DTIC: {assignment.recurso_dtic_id} • Categoría: {formatCategory(assignment.recurso_category)}
</p>
<small className="text-muted">
{assignment.action === 'assigned' ? 'Relacionado' : 'Desrelacionado'}: {formatDate(assignment.created_at)}
{assignment.tecnico_name && ` • Por: ${assignment.tecnico_name}`}
</small>
</div>
))}
</div>
</>
)}
{stats && (!stats.assignment_history || stats.assignment_history.length === 0) && (
<div className="text-center py-4 text-muted">
<i className="fas fa-inbox fa-2x mb-2"></i>
<p>No hay historial de relaciones</p>
</div>
)}
{/* Resource Assignment Control */}
<hr className="my-4" />
<h6 className="fw-bold text-info mb-3">
<i className="fas fa-boxes me-2"></i>Gestión de Recursos Relacionados
</h6>
<ResourceAssignmentControl
entityId={usuario.id}
entityType="usuario"
assignedResources={resourceAssignment.assignedResources}
availableResources={resourceAssignment.availableResources}
onAssignResource={resourceAssignment.assignResource}
onUnassignResource={resourceAssignment.unassignResource}
loading={resourceAssignment.loading}
className="border-0 p-0"
showAddIcon={true}
maxHeight="250px"
/>
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
>
<i className="fas fa-times me-2"></i>Cerrar
</button>
<button
type="button"
className="btn btn-warning"
onClick={() => {
onClose()
onEdit(usuario.id)
}}
>
<i className="fas fa-edit me-2"></i>Editar Usuario
</button>
</div>
</div>
</div>
</div>
)
}
export default UsuarioProfileModal
@@ -0,0 +1,27 @@
import { useEffect } from 'react'
import { Navigate, useLocation } from 'react-router-dom'
import { useAuthStore } from '../../stores/authStore'
interface PrivateRouteProps {
children: React.ReactNode
}
const PrivateRoute = ({ children }: PrivateRouteProps) => {
const { isAuthenticated, checkAuth } = useAuthStore()
const location = useLocation()
useEffect(() => {
if (!isAuthenticated) {
checkAuth()
}
}, [isAuthenticated, checkAuth])
if (!isAuthenticated) {
// Redirect to login page with return url
return <Navigate to="/login" state={{ from: location }} replace />
}
return <>{children}</>
}
export default PrivateRoute
@@ -0,0 +1,297 @@
import React, { useState, useEffect } from 'react'
import { ResourceAssignmentControl } from './ResourceAssignmentControl'
import { useResourceAssignment } from '../../hooks/useResourceAssignment'
export interface FormField {
name: string
label: string
type: 'text' | 'email' | 'select' | 'textarea' | 'tel' | 'date' | 'multiselect' | 'resource_assignment'
required?: boolean
options?: Array<{ value: string, label: string }>
placeholder?: string
rows?: number
dynamicOptions?: {
endpoint: string
labelField: string
valueField: string
params?: Record<string, any>
}
resourceAssignmentConfig?: {
entityType: 'tarea' | 'usuario' | 'tecnico' | 'recurso'
entityId: number
}
}
interface EntityFormProps<T> {
onSubmit: (data: Partial<T>) => void
onCancel: () => void
initialData?: Partial<T>
fields: FormField[]
submitText?: string
title?: string
}
export const EntityForm = <T extends Record<string, any>>({
onSubmit,
onCancel,
initialData = {},
fields,
submitText = 'Guardar',
title
}: EntityFormProps<T>) => {
const [formData, setFormData] = useState<Partial<T>>(initialData)
const [dynamicOptions, setDynamicOptions] = useState<Record<string, Array<{ value: string, label: string }>>>({})
const [loadingOptions, setLoadingOptions] = useState<Record<string, boolean>>({})
// Load dynamic options for select fields with caching
useEffect(() => {
const loadDynamicOptions = async () => {
const newOptions: Record<string, Array<{ value: string, label: string }>> = {}
const newLoading: Record<string, boolean> = {}
// Process fields in parallel for better performance
const promises = fields.map(async (field) => {
if (field.dynamicOptions) {
newLoading[field.name] = true
try {
const { endpoint, labelField, valueField, params } = field.dynamicOptions
const queryParams = new URLSearchParams(params || {})
const url = `${endpoint}?${queryParams}`
const response = await fetch(url)
if (response.ok) {
const data = await response.json()
if (data.success && data.data) {
const entities = Array.isArray(data.data) ? data.data :
data.data.tecnicos || data.data.recursos || data.data.usuarios || data.data.tareas || []
const options = entities.map((entity: any) => ({
value: entity[valueField].toString(),
label: entity[labelField]
}))
newOptions[field.name] = options
}
}
} catch (error) {
console.error(`Error loading dynamic options for ${field.name}:`, error)
} finally {
newLoading[field.name] = false
}
}
})
await Promise.all(promises)
setDynamicOptions(newOptions)
setLoadingOptions(newLoading)
}
loadDynamicOptions()
}, [fields])
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
// Basic validation
const errors: string[] = []
fields.forEach(field => {
if (field.required && !formData[field.name]) {
errors.push(`${field.label} es obligatorio`)
}
})
if (errors.length > 0) {
alert(`Errores de validación:\n${errors.join('\n')}`)
return
}
onSubmit(formData)
}
const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => {
const { name, value } = e.target
setFormData(prev => ({ ...prev, [name]: value }))
}
const renderField = (field: FormField) => {
const value = formData[field.name] || ''
switch (field.type) {
case 'textarea':
return (
<textarea
className="form-control"
id={field.name}
name={field.name}
value={value}
onChange={handleChange}
placeholder={field.placeholder}
rows={field.rows || 3}
required={field.required}
/>
)
case 'select':
const selectOptions = dynamicOptions[field.name] || field.options || []
const isLoading = loadingOptions[field.name]
return (
<select
className="form-select"
id={field.name}
name={field.name}
value={value}
onChange={handleChange}
required={field.required}
disabled={isLoading}
>
<option value="">
{isLoading ? 'Cargando...' : 'Seleccionar...'}
</option>
{selectOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
)
case 'multiselect':
const multiselectOptions = dynamicOptions[field.name] || field.options || []
const isLoadingMulti = loadingOptions[field.name]
const selectedValues = Array.isArray(value) ? value : []
return (
<div className="multiselect-container">
<select
className="form-select"
multiple
id={field.name}
name={field.name}
value={selectedValues}
onChange={(e) => {
const selectedOptions = Array.from(e.target.selectedOptions, option => option.value)
setFormData(prev => ({ ...prev, [field.name]: selectedOptions }))
}}
style={{ minHeight: '120px' }}
disabled={isLoadingMulti}
>
{isLoadingMulti && <option disabled>Cargando...</option>}
{multiselectOptions.map(option => (
<option key={option.value} value={option.value}>
{option.label}
</option>
))}
</select>
{selectedValues.length > 0 && (
<small className="text-muted mt-1">
{selectedValues.length} recurso{selectedValues.length !== 1 ? 's' : ''} seleccionado{selectedValues.length !== 1 ? 's' : ''}
</small>
)}
</div>
)
case 'resource_assignment':
if (!field.resourceAssignmentConfig) {
return (
<div className="alert alert-warning">
<i className="fas fa-exclamation-triangle me-2"></i>
Configuración de asignación de recursos no encontrada
</div>
)
}
const { entityType } = field.resourceAssignmentConfig
let entityId = field.resourceAssignmentConfig.entityId
// Replace template variables in entityId
if (typeof entityId === 'string' && entityId.includes('{{id}}')) {
const actualId = initialData?.id
if (actualId) {
entityId = actualId.toString()
} else {
// For new entities without ID, don't show resource assignment
return (
<div className="alert alert-info">
<i className="fas fa-info-circle me-2"></i>
La asignación de recursos estará disponible después de guardar la entidad
</div>
)
}
}
const resourceAssignment = useResourceAssignment(entityType, parseInt(entityId.toString()))
return (
<ResourceAssignmentControl
entityId={entityId}
entityType={entityType}
assignedResources={resourceAssignment.assignedResources}
availableResources={resourceAssignment.availableResources}
onAssignResource={resourceAssignment.assignResource}
onUnassignResource={resourceAssignment.unassignResource}
loading={resourceAssignment.loading}
className="border rounded p-3"
showAddIcon={true}
maxHeight="400px"
/>
)
default:
return (
<input
type={field.type}
className="form-control"
id={field.name}
name={field.name}
value={value}
onChange={handleChange}
placeholder={field.placeholder}
required={field.required}
/>
)
}
}
return (
<form onSubmit={handleSubmit}>
{title && (
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-edit me-2"></i>
{title}
</h6>
)}
<div className="row g-3">
{fields.map(field => (
<div key={field.name} className="col-md-6">
<label className="form-label small fw-bold">
{field.label} {field.required && '*'}
</label>
{renderField(field)}
</div>
))}
</div>
<div className="d-flex justify-content-between align-items-center mt-3">
<small className="text-muted">
Los campos marcados con * son obligatorios
</small>
<div>
<button
type="button"
className="btn btn-outline-secondary btn-sm me-2"
onClick={onCancel}
>
<i className="fas fa-times me-1"></i>Cancelar
</button>
<button
type="submit"
className="btn btn-success btn-sm"
disabled={!fields.some(f => f.required) || !fields.filter(f => f.required).every(f => formData[f.name])}
>
<i className="fas fa-save me-1"></i>{submitText}
</button>
</div>
</div>
</form>
)
}
@@ -0,0 +1,66 @@
import React from 'react'
interface StatCard {
title: string
value: number
subtitle: string
color: string
}
interface EntityLayoutProps {
title: string
subtitle: string
icon: string
stats: StatCard[]
children: React.ReactNode
className?: string
}
export const EntityLayout = ({
title,
subtitle,
icon,
stats,
children,
className = ''
}: EntityLayoutProps) => {
return (
<div className={`container mt-4 scroll-smooth ${className}`}>
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center mb-3">
<i className={`fas ${icon} fa-2x text-primary me-3`}></i>
<div>
<h1 className="h3 mb-0">{title}</h1>
<p className="text-muted mb-0">{subtitle}</p>
</div>
</div>
</div>
</div>
{/* Statistics Cards */}
<div className="row mb-4">
{stats.map((stat, index) => (
<div key={index} className="col-md-3 mb-3">
<div className="card h-100">
<div className="card-header">
<i className={`fas fa-chart-line text-${stat.color} me-2`}></i>
{stat.title}
</div>
<div className="card-body text-center">
<div className={`display-4 text-${stat.color} mb-2 fw-bold`}>
{stat.value}
</div>
<small className="text-muted">{stat.subtitle}</small>
</div>
</div>
</div>
))}
</div>
{/* Main Content */}
{children}
</div>
)
}
@@ -0,0 +1,376 @@
import { useEffect, useState } from 'react'
import { EntityConfig } from '../../stores/genericEntityStore'
interface ProfileModalProps {
entity: any
entityKey: string
config: EntityConfig
isOpen: boolean
onClose: () => void
onEdit: (id: number) => void
}
interface EntityStats {
total_tasks?: number
completed_tasks?: number
active_tasks?: number
recent_tasks?: any[]
assigned_resources_count?: number
}
const ProfileModal = ({ entity, entityKey, config, isOpen, onClose, onEdit }: ProfileModalProps) => {
const [stats, setStats] = useState<EntityStats | null>(null)
const [loading, setLoading] = useState(false)
useEffect(() => {
if (entity && isOpen) {
fetchEntityStats()
}
}, [entity, isOpen])
const fetchEntityStats = async () => {
if (!entity) return
setLoading(true)
try {
const response = await fetch(`http://localhost:3001/api/${entityKey}/${entity.id}?include_tasks=true`)
const data = await response.json()
if (data.success) {
setStats({
total_tasks: data.data.technician?.total_tasks || data.data.tarea?.total_tasks || 0,
completed_tasks: data.data.technician?.completed_tasks || data.data.tarea?.completed_tasks || 0,
active_tasks: data.data.technician?.active_tasks || data.data.tarea?.active_tasks || 0,
recent_tasks: data.data.technician?.recent_tasks || data.data.tarea?.recent_tasks || [],
assigned_resources_count: data.data.usuario?.assigned_resources_count || 0
})
}
} catch (error) {
console.error('Error fetching entity stats:', error)
} finally {
setLoading(false)
}
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('es-AR', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
}
const formatTaskStatus = (status: string) => {
const statuses = {
'pending': 'Pendiente',
'in_progress': 'En Progreso',
'completed': 'Completada',
'cancelled': 'Cancelada'
}
return statuses[status as keyof typeof statuses] || status
}
const getEntityIcon = () => {
const icons: { [key: string]: string } = {
'tecnicos': 'fa-user',
'recursos': 'fa-box',
'usuarios': 'fa-user-cog',
'tareas': 'fa-tasks'
}
return icons[entityKey] || 'fa-info-circle'
}
const getEntityTitle = () => {
const titles: { [key: string]: string } = {
'tecnicos': 'Perfil de Técnico',
'recursos': 'Detalles del Recurso',
'usuarios': 'Perfil de Usuario',
'tareas': 'Detalles de Tarea'
}
return titles[entityKey] || 'Detalles'
}
if (!isOpen || !entity) return null
return (
<div className="modal fade show d-block" tabIndex={-1} style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header bg-primary text-white">
<h5 className="modal-title">
<i className={`fas ${getEntityIcon()} me-2`}></i>
{getEntityTitle()}: {entity.first_name ? `${entity.first_name} ${entity.last_name}` : entity.name || entity.title || 'Sin nombre'}
</h5>
<button
type="button"
className="btn-close btn-close-white"
onClick={onClose}
></button>
</div>
<div className="modal-body">
<div className="row">
{/* Información básica y avatar */}
<div className="col-md-4 text-center mb-4">
<div className="avatar-circle bg-primary text-white mx-auto mb-3"
style={{ width: '80px', height: '80px', fontSize: '2rem', border: '4px solid #dee2e6' }}>
<i className={`fas ${getEntityIcon()}`}></i>
</div>
<h5 className="mb-1">{entity.first_name ? `${entity.first_name} ${entity.last_name}` : entity.name || entity.title || 'Sin nombre'}</h5>
{entity.role && (
<span className={`badge fs-6 mb-2 ${entity.role === 'admin' ? 'bg-danger' : entity.role === 'technician' ? 'bg-info' : 'bg-secondary'}`}>
{entity.role === 'admin' ? 'Administrador' : entity.role === 'technician' ? 'Técnico' : entity.role === 'viewer' ? 'Visualizador' : entity.role}
</span>
)}
{entity.status && (
<div>
<span className={`badge ${entity.status === 'active' || entity.is_active ? 'bg-success' : 'bg-warning'} fs-6`}>
{entity.status === 'active' || entity.is_active ? 'Activo' : 'Inactivo'}
</span>
</div>
)}
</div>
{/* Información detallada */}
<div className="col-md-8">
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">ID DTIC</strong>
<span className="badge bg-light text-dark fs-6">{entity.dtic_id}</span>
</div>
{entity.email && (
<div className="mb-3">
<strong className="text-muted d-block">Email</strong>
<span>{entity.email}</span>
</div>
)}
{entity.phone && (
<div className="mb-3">
<strong className="text-muted d-block">Teléfono</strong>
<span>{entity.phone || 'No especificado'}</span>
</div>
)}
</div>
<div className="col-sm-6">
{entity.department && (
<div className="mb-3">
<strong className="text-muted d-block">Departamento</strong>
<span>{entity.department}</span>
</div>
)}
{entity.created_at && (
<div className="mb-3">
<strong className="text-muted d-block">Registro</strong>
<span>{formatDate(entity.created_at)}</span>
</div>
)}
{entity.updated_at && (
<div className="mb-3">
<strong className="text-muted d-block">Última actualización</strong>
<span>{formatDate(entity.updated_at)}</span>
</div>
)}
</div>
</div>
<hr />
{/* Estadísticas específicas por entidad */}
{entityKey === 'tecnicos' && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-chart-bar me-2"></i>Estadísticas de Tareas
</h6>
{loading ? (
<div className="text-center py-3">
<div className="spinner-border spinner-border-sm text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
</div>
) : stats ? (
<div className="row text-center mb-4">
<div className="col-sm-4">
<div className="p-3 bg-light rounded">
<div className="h4 text-primary mb-1">{stats.total_tasks}</div>
<small className="text-muted fw-bold">Total Tareas</small>
</div>
</div>
<div className="col-sm-4">
<div className="p-3 bg-success rounded text-white">
<div className="h4 mb-1">{stats.completed_tasks}</div>
<small className="fw-bold">Completadas</small>
</div>
</div>
<div className="col-sm-4">
<div className="p-3 bg-warning rounded">
<div className="h4 text-dark mb-1">{stats.active_tasks}</div>
<small className="text-dark fw-bold">Activas</small>
</div>
</div>
</div>
) : null}
{/* Tareas recientes */}
{stats && stats.recent_tasks && stats.recent_tasks.length > 0 && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-clock me-2"></i>Tareas Recientes
</h6>
<div className="list-group">
{stats.recent_tasks.slice(0, 3).map((task: any, index: number) => (
<div key={index} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{task.title}</h6>
<small className={`badge ${
task.status === 'completed' ? 'bg-success' :
task.status === 'in_progress' ? 'bg-warning text-dark' :
'bg-secondary'
}`}>
{formatTaskStatus(task.status)}
</small>
</div>
<p className="mb-1">{task.description || 'Sin descripción'}</p>
<small className="text-muted">
Creada: {formatDate(task.created_at)}
{task.due_date && ` • Vence: ${formatDate(task.due_date)}`}
</small>
</div>
))}
</div>
</>
)}
{stats && (!stats.recent_tasks || stats.recent_tasks.length === 0) && (
<div className="text-center py-4 text-muted">
<i className="fas fa-inbox fa-2x mb-2"></i>
<p>No hay tareas recientes</p>
</div>
)}
</>
)}
{entityKey === 'usuarios' && stats && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-chart-bar me-2"></i>Estadísticas de Recursos
</h6>
<div className="row text-center mb-4">
<div className="col-sm-6">
<div className="p-3 bg-info rounded text-white">
<div className="h4 mb-1">{stats.assigned_resources_count || 0}</div>
<small className="fw-bold">Recursos Asignados</small>
</div>
</div>
<div className="col-sm-6">
<div className="p-3 bg-success rounded text-white">
<div className="h4 mb-1">{entity.position || 'Sin cargo'}</div>
<small className="fw-bold">Cargo</small>
</div>
</div>
</div>
</>
)}
{entityKey === 'recursos' && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-info-circle me-2"></i>Detalles del Recurso
</h6>
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Categoría</strong>
<span>{entity.category}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Estado</strong>
<span className={`badge ${entity.status === 'available' ? 'bg-success' : entity.status === 'assigned' ? 'bg-info' : 'bg-warning'}`}>
{entity.status === 'available' ? 'Disponible' : entity.status === 'assigned' ? 'Asignado' : entity.status === 'maintenance' ? 'Mantenimiento' : entity.status}
</span>
</div>
</div>
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Ubicación</strong>
<span>{entity.location || 'No especificada'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Modelo</strong>
<span>{entity.model || 'No especificado'}</span>
</div>
</div>
</div>
</>
)}
{entityKey === 'tareas' && (
<>
<h6 className="fw-bold text-primary mb-3">
<i className="fas fa-tasks me-2"></i>Detalles de la Tarea
</h6>
<div className="row">
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Estado</strong>
<span className={`badge ${entity.status === 'completed' ? 'bg-success' : entity.status === 'in_progress' ? 'bg-warning text-dark' : 'bg-secondary'}`}>
{formatTaskStatus(entity.status)}
</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Prioridad</strong>
<span className={`badge ${entity.priority === 'urgent' ? 'bg-danger' : entity.priority === 'high' ? 'bg-warning text-dark' : entity.priority === 'medium' ? 'bg-info' : 'bg-light text-dark'}`}>
{entity.priority === 'urgent' ? 'Urgente' : entity.priority === 'high' ? 'Alta' : entity.priority === 'medium' ? 'Media' : 'Baja'}
</span>
</div>
</div>
<div className="col-sm-6">
<div className="mb-3">
<strong className="text-muted d-block">Fecha Límite</strong>
<span>{entity.due_date ? formatDate(entity.due_date) : 'Sin fecha límite'}</span>
</div>
<div className="mb-3">
<strong className="text-muted d-block">Técnico Asignado</strong>
<span>{entity.technician_name || 'Sin asignar'}</span>
</div>
</div>
</div>
{entity.description && (
<div className="mb-3">
<strong className="text-muted d-block">Descripción</strong>
<p className="mb-0">{entity.description}</p>
</div>
)}
</>
)}
</div>
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={onClose}
>
<i className="fas fa-times me-2"></i>Cerrar
</button>
<button
type="button"
className="btn btn-warning"
onClick={() => {
onClose()
onEdit(entity.id)
}}
>
<i className="fas fa-edit me-2"></i>Editar {config.name.slice(0, -1)}
</button>
</div>
</div>
</div>
</div>
)
}
export { ProfileModal }
@@ -0,0 +1,284 @@
import React, { useState } from 'react'
// Types for the control
export interface AssignedResource {
id: number
name: string
category?: string
status?: string
location?: string
}
export interface ResourceOption {
id: number
name: string
category?: string
status?: string
location?: string
}
export interface ResourceAssignmentControlProps {
entityId: number
entityType: 'tarea' | 'usuario' | 'tecnico' | 'recurso'
assignedResources: AssignedResource[]
availableResources: ResourceOption[]
onAssignResource: (resourceId: number) => Promise<boolean>
onUnassignResource: (resourceId: number) => Promise<boolean>
loading?: boolean
className?: string
showAddIcon?: boolean
maxHeight?: string
}
export const ResourceAssignmentControl: React.FC<ResourceAssignmentControlProps> = ({
entityId,
entityType,
assignedResources,
availableResources,
onAssignResource,
onUnassignResource,
loading = false,
className = '',
showAddIcon = true,
maxHeight = '300px'
}) => {
const [isAssigning, setIsAssigning] = useState<number | null>(null)
const [isUnassigning, setIsUnassigning] = useState<number | null>(null)
const [showAddResource, setShowAddResource] = useState(false)
const [selectedResourceId, setSelectedResourceId] = useState<string>('')
// Get icon and color for resource status
const getResourceStatusInfo = (status?: string) => {
switch (status) {
case 'available':
return { icon: 'fa-check', color: 'success', text: 'Disponible' }
case 'assigned':
return { icon: 'fa-user', color: 'info', text: 'Relacionado' }
case 'maintenance':
return { icon: 'fa-spinner', color: 'warning', text: 'Mantenimiento' }
case 'retired':
return { icon: 'fa-trash', color: 'danger', text: 'Retirado' }
default:
return { icon: 'fa-box', color: 'secondary', text: 'Desconocido' }
}
}
// Handle resource assignment
const handleAssignResource = async () => {
if (!selectedResourceId) return
setIsAssigning(parseInt(selectedResourceId))
try {
const success = await onAssignResource(parseInt(selectedResourceId))
if (success) {
setShowAddResource(false)
setSelectedResourceId('')
}
} catch (error) {
console.error('Error assigning resource:', error)
} finally {
setIsAssigning(null)
}
}
// Handle resource unassignment
const handleUnassignResource = async (resourceId: number) => {
setIsUnassigning(resourceId)
try {
await onUnassignResource(resourceId)
} catch (error) {
console.error('Error unassigning resource:', error)
} finally {
setIsUnassigning(null)
}
}
// Get category color
const getCategoryColor = (category?: string) => {
switch (category) {
case 'hardware':
return 'primary'
case 'software':
return 'info'
case 'network':
return 'success'
case 'security':
return 'danger'
case 'tools':
return 'warning'
case 'facilities':
return 'secondary'
default:
return 'secondary'
}
}
return (
<div className={`resource-assignment-control ${className}`}>
{/* Header with Add Resource Button */}
<div className="d-flex justify-content-between align-items-center mb-3">
<h6 className="mb-0">
<i className="fas fa-boxes me-2"></i>
Recursos Relacionados
</h6>
{showAddIcon && !loading && (
<button
type="button"
className="btn btn-sm btn-outline-primary"
onClick={() => setShowAddResource(!showAddResource)}
disabled={isAssigning !== null}
>
<i className="fas fa-plus me-1"></i>
Relacionar Recurso
</button>
)}
</div>
{/* Add Resource Section */}
{showAddResource && (
<div className="card mb-3 border-primary">
<div className="card-body">
<div className="row g-2 align-items-end">
<div className="col-md-8">
<label className="form-label small fw-bold">
Seleccionar Recurso:
</label>
<select
className="form-select form-select-sm"
value={selectedResourceId}
onChange={(e: React.ChangeEvent<HTMLSelectElement>) => setSelectedResourceId(e.target.value)}
disabled={isAssigning !== null}
>
<option value="">Seleccionar recurso...</option>
{availableResources
.filter((resource: ResourceOption) =>
!assignedResources.some((assigned: AssignedResource) => assigned.id === resource.id)
)
.map((resource: ResourceOption) => (
<option key={resource.id} value={resource.id}>
{resource.name} {resource.category ? `(${resource.category})` : ''}
</option>
))
}
</select>
</div>
<div className="col-md-4">
<div className="d-flex gap-1">
<button
type="button"
className="btn btn-sm btn-success"
onClick={handleAssignResource}
disabled={!selectedResourceId || isAssigning !== null}
>
{isAssigning !== null ? (
<>
<i className="fas fa-spinner fa-spin me-1"></i>
Relacionando...
</>
) : (
<>
<i className="fas fa-check me-1"></i>
Relacionar
</>
)}
</button>
<button
type="button"
className="btn btn-sm btn-outline-secondary"
onClick={() => {
setShowAddResource(false)
setSelectedResourceId('')
}}
disabled={isAssigning !== null}
>
<i className="fas fa-times"></i>
</button>
</div>
</div>
</div>
</div>
</div>
)}
{/* Currently Assigned Resources */}
<div className="resource-list" style={{ maxHeight, overflowY: 'auto' }}>
{loading ? (
<div className="text-center py-3">
<i className="fas fa-spinner fa-spin fa-2x text-muted"></i>
<p className="text-muted mt-2">Cargando recursos...</p>
</div>
) : assignedResources.length > 0 ? (
<div className="row g-2">
{assignedResources.map((resource: AssignedResource) => {
const statusInfo = getResourceStatusInfo(resource.status)
return (
<div key={resource.id} className="col-12">
<div className="card border-0 bg-light">
<div className="card-body py-2 px-3">
<div className="d-flex justify-content-between align-items-center">
<div className="d-flex align-items-center">
<div className={`badge bg-${getCategoryColor(resource.category)} me-2`}>
<i className="fas fa-box me-1"></i>
{resource.category || 'Recurso'}
</div>
<div>
<h6 className="mb-0 small">{resource.name}</h6>
{resource.location && (
<small className="text-muted">
<i className="fas fa-map-marker-alt me-1"></i>
{resource.location}
</small>
)}
</div>
</div>
<div className="d-flex align-items-center gap-2">
<span className={`badge bg-${statusInfo.color} small`}>
<i className={`fas ${statusInfo.icon} me-1`}></i>
{statusInfo.text}
</span>
<button
type="button"
className="btn btn-sm btn-outline-danger"
onClick={() => handleUnassignResource(resource.id)}
disabled={isUnassigning === resource.id}
title="Quitar relación"
>
{isUnassigning === resource.id ? (
<i className="fas fa-spinner fa-spin"></i>
) : (
<i className="fas fa-trash"></i>
)}
</button>
</div>
</div>
</div>
</div>
</div>
)
})}
</div>
) : (
<div className="text-center py-4">
<i className="fas fa-box fa-3x text-muted mb-3"></i>
<p className="text-muted mb-0">No hay recursos relacionados</p>
<small className="text-muted">
{showAddResource ? 'Selecciona un recurso para asignar' : 'Haz clic en "Asignar Recurso" para comenzar'}
</small>
</div>
)}
</div>
{/* Summary */}
{assignedResources.length > 0 && (
<div className="mt-3 pt-2 border-top">
<small className="text-muted">
<i className="fas fa-info-circle me-1"></i>
Total: {assignedResources.length} recurso{assignedResources.length !== 1 ? 's' : ''} relacionado{assignedResources.length !== 1 ? 's' : ''}
</small>
</div>
)}
</div>
)
}
export default ResourceAssignmentControl
@@ -0,0 +1,497 @@
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuthStore } from '../../stores/authStore'
import { useState, useEffect } from 'react'
const Navbar = () => {
const location = useLocation()
const navigate = useNavigate()
const { user, isAuthenticated, logout } = useAuthStore()
const [isScrolled, setIsScrolled] = useState(false)
const [isMenuOpen, setIsMenuOpen] = useState(false)
const [isHidden, setIsHidden] = useState(false)
const [isHovered, setIsHovered] = useState(false)
const [lastScrollY, setLastScrollY] = useState(0)
const handleLogout = () => {
logout()
navigate('/login')
}
const isActive = (path: string) => {
return location.pathname === path
}
// Detect scroll for navbar styling and auto-hide
useEffect(() => {
const handleScroll = () => {
const currentScrollY = window.scrollY
const scrollThreshold = 100
// Update scrolled state for visual effects
setIsScrolled(currentScrollY > 20)
// Auto-hide logic: hide when scrolling down, show when scrolling up
if (currentScrollY > lastScrollY && currentScrollY > scrollThreshold) {
setIsHidden(true)
} else if (currentScrollY < lastScrollY) {
setIsHidden(false)
}
setLastScrollY(currentScrollY)
}
window.addEventListener('scroll', handleScroll, { passive: true })
return () => window.removeEventListener('scroll', handleScroll)
}, [lastScrollY])
// Close mobile menu when route changes
useEffect(() => {
setIsMenuOpen(false)
}, [location.pathname])
if (!isAuthenticated) {
return null
}
const navItems = [
// Nuevo orden: Dashboard, Calendario, Recursos, Tareas, Técnicos, Usuarios, Reportes
{ path: '/dashboard', icon: 'fas fa-tachometer-alt', label: 'Dashboard', color: 'text-primary', group: 'vision' },
{ path: '/calendario', icon: 'fas fa-calendar', label: 'Calendario', color: 'text-secondary', group: 'vision' },
{ path: '/recursos', icon: 'fas fa-server', label: 'Recursos', color: 'text-info', group: 'gestion' },
{ path: '/tareas', icon: 'fas fa-tasks', label: 'Tareas', color: 'text-warning', group: 'operaciones' },
{ path: '/tecnicos', icon: 'fas fa-users', label: 'Técnicos', color: 'text-success', group: 'operaciones' },
...(user?.role === 'admin' ? [
{ path: '/usuarios', icon: 'fas fa-user-cog', label: 'Usuarios', color: 'text-dark', group: 'gestion' },
{ path: '/sistema', icon: 'fas fa-cogs', label: 'Sistema', color: 'text-secondary', group: 'sistema' }
] : []),
{ path: '/reportes', icon: 'fas fa-chart-bar', label: 'Reportes', color: 'text-danger', group: 'reportes' }
]
return (
<>
{/* Custom CSS for modern navbar */}
<style>{`
.modern-navbar {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
backdrop-filter: blur(10px);
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
transform: translateY(0);
}
.modern-navbar.scrolled {
background: rgba(102, 126, 234, 0.95);
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}
.modern-navbar.hidden {
transform: translateY(-100%);
}
.modern-navbar:hover {
transform: translateY(0) !important;
}
.nav-item-modern {
position: relative;
margin: 0 4px;
}
.nav-group-vision {
margin-right: 20px;
}
.nav-group-gestion {
margin-right: 20px;
}
.nav-group-operaciones {
margin-right: 20px;
}
.nav-group-sistema {
margin-right: 20px;
}
.nav-group-separators::before {
content: '';
position: absolute;
left: -12px;
top: 50%;
transform: translateY(-50%);
width: 1px;
height: 60%;
background: rgba(255, 255, 255, 0.3);
}
.nav-link-modern {
color: rgba(255, 255, 255, 0.9) !important;
font-weight: 500;
padding: 12px 20px;
border-radius: 25px;
transition: all 0.3s ease;
position: relative;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
.nav-link-modern::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
transition: left 0.5s;
}
.nav-link-modern:hover::before {
left: 100%;
}
.nav-link-modern:hover {
color: white !important;
background: rgba(255, 255, 255, 0.1);
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.nav-link-modern.active {
background: rgba(255, 255, 255, 0.15);
color: white !important;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.3);
}
.nav-link-modern i {
margin-bottom: 4px;
font-size: 1.1em;
}
.navbar-brand-modern {
font-weight: 700;
font-size: 1.5rem;
color: white !important;
text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
.navbar-brand-modern:hover {
color: rgba(255, 255, 255, 0.8) !important;
transform: scale(1.05);
transition: all 0.3s ease;
}
.version-badge {
background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.05));
border: 1px solid rgba(255, 255, 255, 0.2);
color: rgba(255, 255, 255, 0.8);
font-size: 0.75rem;
font-weight: 500;
padding: 4px 8px;
border-radius: 12px;
backdrop-filter: blur(10px);
transition: var(--transition);
}
.version-badge:hover {
background: rgba(255, 255, 255, 0.2);
color: white;
transform: scale(1.05);
}
.user-menu-modern {
background: rgba(255, 255, 255, 0.1);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 25px;
padding: 8px 16px;
color: white !important;
transition: all 0.3s ease;
}
.user-menu-modern:hover {
background: rgba(255, 255, 255, 0.2);
border-color: rgba(255, 255, 255, 0.3);
}
.dropdown-menu-modern {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 15px;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
margin-top: 10px;
}
.dropdown-item-modern {
color: rgba(255, 255, 255, 0.9) !important;
padding: 12px 20px;
border-radius: 8px;
margin: 4px 8px;
transition: all 0.3s ease;
}
.dropdown-item-modern:hover {
background: rgba(255, 255, 255, 0.2);
color: white !important;
transform: translateX(5px);
}
.mobile-menu-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(5px);
z-index: 1040;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
}
.mobile-menu-overlay.active {
opacity: 1;
visibility: visible;
}
.mobile-menu {
position: fixed;
top: 0;
right: -300px;
width: 280px;
height: 100%;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
box-shadow: -5px 0 25px rgba(0, 0, 0, 0.3);
transition: right 0.3s ease;
z-index: 1050;
padding: 80px 20px 20px;
}
.mobile-menu.active {
right: 0;
}
.mobile-nav-item {
margin-bottom: 10px;
}
.mobile-nav-link {
display: block;
color: rgba(255, 255, 255, 0.9) !important;
padding: 15px 20px;
border-radius: 12px;
text-decoration: none;
transition: all 0.3s ease;
font-weight: 500;
}
.mobile-nav-link:hover,
.mobile-nav-link.active {
background: rgba(255, 255, 255, 0.2);
color: white !important;
transform: translateX(10px);
}
.mobile-nav-link i {
margin-right: 12px;
width: 20px;
}
.hamburger-menu {
display: none;
flex-direction: column;
cursor: pointer;
padding: 10px;
border-radius: 8px;
transition: all 0.3s ease;
}
.hamburger-menu:hover {
background: rgba(255, 255, 255, 0.1);
}
.hamburger-line {
width: 25px;
height: 3px;
background: white;
margin: 3px 0;
transition: all 0.3s ease;
border-radius: 2px;
}
.hamburger-menu.active .hamburger-line:nth-child(1) {
transform: rotate(45deg) translate(5px, 5px);
}
.hamburger-menu.active .hamburger-line:nth-child(2) {
opacity: 0;
}
.hamburger-menu.active .hamburger-line:nth-child(3) {
transform: rotate(-45deg) translate(7px, -6px);
}
@media (max-width: 991px) {
.hamburger-menu {
display: flex;
}
.desktop-nav {
display: none;
}
}
@media (min-width: 992px) {
.mobile-menu-overlay,
.mobile-menu {
display: none !important;
}
}
`}</style>
{/* Mobile menu overlay */}
<div
className={`mobile-menu-overlay ${isMenuOpen ? 'active' : ''}`}
onClick={() => setIsMenuOpen(false)}
/>
{/* Mobile menu */}
<div className={`mobile-menu ${isMenuOpen ? 'active' : ''}`}>
<div className="text-center mb-4">
<h5 className="text-white mb-4">Menú de Navegación</h5>
</div>
{navItems.map((item) => (
<div key={item.path} className="mobile-nav-item">
<Link
to={item.path}
className={`mobile-nav-link ${isActive(item.path) ? 'active' : ''}`}
onClick={() => setIsMenuOpen(false)}
>
<i className={item.icon}></i>
{item.label}
</Link>
</div>
))}
<hr className="border-light my-4" />
<div className="mobile-nav-item">
<Link
to="/perfil"
className="mobile-nav-link"
onClick={() => setIsMenuOpen(false)}
>
<i className="fas fa-user-edit"></i>
Mi Perfil
</Link>
</div>
<div className="mobile-nav-item">
<button
className="mobile-nav-link w-100 text-start border-0 bg-transparent"
onClick={() => {
handleLogout()
setIsMenuOpen(false)
}}
>
<i className="fas fa-sign-out-alt"></i>
Cerrar Sesión
</button>
</div>
</div>
{/* Main Navbar */}
<nav
className={`navbar navbar-expand-lg fixed-top modern-navbar ${isScrolled ? 'scrolled' : ''} ${isHidden ? 'hidden' : ''}`}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<div className="container-fluid">
{/* Brand */}
<Link className="navbar-brand navbar-brand-modern" to="/dashboard">
<i className="fas fa-cogs me-2"></i>
DTIC Bitácoras
<span className="version-badge ms-2">v{import.meta.env.VERSION}</span>
</Link>
{/* Hamburger Menu for Mobile */}
<div
className={`hamburger-menu ${isMenuOpen ? 'active' : ''}`}
onClick={() => setIsMenuOpen(!isMenuOpen)}
>
<div className="hamburger-line"></div>
<div className="hamburger-line"></div>
<div className="hamburger-line"></div>
</div>
{/* Desktop Navigation */}
<div className="collapse navbar-collapse desktop-nav">
<ul className="navbar-nav me-auto">
{navItems.map((item, index) => {
const prevItem = index > 0 ? navItems[index - 1] : null
const showSeparator = prevItem && prevItem.group !== item.group
return (
<li
key={item.path}
className={`nav-item nav-item-modern ${showSeparator ? 'nav-group-separators' : ''}`}
>
<Link
to={item.path}
className={`nav-link nav-link-modern ${isActive(item.path) ? 'active' : ''}`}
>
<i className={item.icon}></i>
{item.label}
</Link>
</li>
)
})}
</ul>
{/* User Menu */}
<ul className="navbar-nav">
<li className="nav-item dropdown">
<a
className="nav-link dropdown-toggle user-menu-modern"
href="#"
id="navbarDropdown"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<i className="fas fa-user-circle me-2"></i>
<span className="d-none d-md-inline">{user?.first_name}</span>
<span className="d-md-none">Perfil</span>
</a>
<ul className="dropdown-menu dropdown-menu-end dropdown-menu-modern" aria-labelledby="navbarDropdown">
<li>
<Link className="dropdown-item dropdown-item-modern" to="/perfil">
<i className="fas fa-user-edit me-2"></i>
Mi Perfil
</Link>
</li>
<li><hr className="dropdown-divider border-light" /></li>
<li>
<button className="dropdown-item dropdown-item-modern" onClick={handleLogout}>
<i className="fas fa-sign-out-alt me-2"></i>
Cerrar Sesión
</button>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
</>
)
}
export default Navbar
@@ -0,0 +1,279 @@
import React, { useState, useEffect } from 'react'
import { Link, useLocation } from 'react-router-dom'
import { useAuthStore } from '../../stores/authStore'
interface SidebarProps {
onToggle?: (collapsed: boolean) => void
}
const Sidebar = ({ onToggle }: SidebarProps) => {
const location = useLocation()
const { user, logout } = useAuthStore()
const [isCollapsed, setIsCollapsed] = useState(false)
const handleLogout = () => {
logout()
// Navigate to login will be handled by the auth store
}
const isActive = (path: string) => {
return location.pathname === path
}
// Load collapsed state from localStorage on mount
useEffect(() => {
const savedState = localStorage.getItem('sidebarCollapsed')
if (savedState === 'true') {
setIsCollapsed(true)
}
}, [])
// Save collapsed state to localStorage
const toggleSidebar = () => {
const newState = !isCollapsed
setIsCollapsed(newState)
localStorage.setItem('sidebarCollapsed', newState.toString())
if (onToggle) {
onToggle(newState)
}
}
const navItems = [
{ path: '/dashboard', icon: 'fas fa-tachometer-alt', label: 'Dashboard', color: 'text-primary' },
{ path: '/calendario', icon: 'fas fa-calendar', label: 'Calendario', color: 'text-secondary' },
{ path: '/recursos', icon: 'fas fa-server', label: 'Recursos', color: 'text-info' },
{ path: '/tareas', icon: 'fas fa-tasks', label: 'Tareas', color: 'text-warning' },
{ path: '/tecnicos', icon: 'fas fa-users', label: 'Técnicos', color: 'text-success' },
...(user?.role === 'admin' ? [
{ path: '/usuarios', icon: 'fas fa-user-cog', label: 'Usuarios', color: 'text-dark' },
{ path: '/sistema', icon: 'fas fa-cogs', label: 'Sistema', color: 'text-secondary' }
] : []),
{ path: '/reportes', icon: 'fas fa-chart-bar', label: 'Reportes', color: 'text-danger' }
]
return (
<>
{/* Modern Material Design 3 Inspired Sidebar CSS */}
<style>{`
.sidebar-modern {
width: 280px;
background: var(--bg-secondary);
color: var(--text-primary);
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
position: fixed;
top: 0;
left: 0;
height: 100vh;
z-index: 1000;
box-shadow: 0 4px 6px -1px var(--shadow-primary), 0 2px 4px -1px var(--shadow-secondary);
border-right: 1px solid var(--border-primary);
overflow-y: auto;
overflow-x: hidden;
}
.sidebar-modern.collapsed {
width: 72px;
}
.sidebar-header-modern {
padding: 24px 20px 16px;
border-bottom: 1px solid var(--border-primary);
display: flex;
align-items: center;
justify-content: space-between;
min-height: 80px;
background: var(--bg-tertiary);
}
.sidebar-modern.collapsed .sidebar-header-modern {
justify-content: center;
padding: 24px 12px 16px;
}
.sidebar-brand-modern {
display: flex;
flex-direction: column;
align-items: center;
text-align: center;
font-weight: 700;
font-size: 1.1rem;
color: #1f2937;
}
.sidebar-modern.collapsed .brand-text-modern {
display: none;
}
.sidebar-toggle-modern {
background: var(--bg-tertiary);
border: 1px solid var(--border-primary);
color: var(--text-secondary);
font-size: 1.1rem;
cursor: pointer;
padding: 8px;
border-radius: 8px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
display: flex;
align-items: center;
justify-content: center;
box-shadow: 0 1px 3px 0 var(--shadow-primary), 0 1px 2px 0 var(--shadow-secondary);
}
.sidebar-toggle-modern:hover {
background: var(--bg-hover);
color: var(--text-primary);
transform: scale(1.05);
box-shadow: 0 4px 6px -1px var(--shadow-primary), 0 2px 4px -1px var(--shadow-secondary);
}
.sidebar-nav-modern {
padding: 16px 0;
}
.sidebar-link-modern {
display: flex;
flex-direction: column;
align-items: center;
padding: 16px 20px;
color: var(--text-secondary);
text-decoration: none;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 12px;
margin: 4px 12px;
text-align: center;
position: relative;
font-weight: 500;
font-size: 0.875rem;
}
.sidebar-link-modern:hover {
background: var(--bg-hover);
color: var(--text-primary);
transform: translateY(-1px);
box-shadow: 0 2px 4px -1px var(--shadow-primary), 0 1px 2px -1px var(--shadow-secondary);
}
.sidebar-link-modern.active {
background: var(--bg-active);
color: white;
box-shadow: 0 4px 6px -1px var(--shadow-accent), 0 2px 4px -1px rgba(59, 130, 246, 0.2);
}
.sidebar-link-modern.active:hover {
background: #2563eb;
}
.sidebar-link-modern i {
font-size: 1.5rem;
margin-bottom: 6px;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.sidebar-link-modern:hover i,
.sidebar-link-modern.active i {
transform: scale(1.1);
}
.sidebar-modern.collapsed .link-text-modern {
display: none;
}
/* Modern dark scrollbar */
.sidebar-modern::-webkit-scrollbar {
width: 6px;
}
.sidebar-modern::-webkit-scrollbar-track {
background: var(--bg-tertiary);
}
.sidebar-modern::-webkit-scrollbar-thumb {
background: var(--border-secondary);
border-radius: 3px;
}
.sidebar-modern::-webkit-scrollbar-thumb:hover {
background: var(--text-muted);
}
/* Mobile responsive */
@media (max-width: 768px) {
.sidebar-modern {
transform: translateX(-100%);
transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 4px 0 6px -1px rgba(0, 0, 0, 0.1), 2px 0 4px -1px rgba(0, 0, 0, 0.06);
}
.sidebar-modern.mobile-open {
transform: translateX(0);
}
.sidebar-overlay-modern {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.5);
z-index: 999;
opacity: 0;
visibility: hidden;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
backdrop-filter: blur(4px);
}
.sidebar-overlay-modern.active {
opacity: 1;
visibility: visible;
}
}
/* Focus states for accessibility */
.sidebar-link-modern:focus,
.sidebar-toggle-modern:focus {
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
`}</style>
{/* Modern Material Design Sidebar */}
<aside className={`sidebar-modern ${isCollapsed ? 'collapsed' : ''}`}>
{/* Header */}
<div className="sidebar-header-modern">
<button
className="sidebar-toggle-modern"
onClick={toggleSidebar}
title={isCollapsed ? 'Expandir menú' : 'Colapsar menú'}
aria-label={isCollapsed ? 'Expandir menú' : 'Colapsar menú'}
>
<i className={`fas ${isCollapsed ? 'fa-chevron-right' : 'fa-chevron-left'}`}></i>
</button>
<div className="sidebar-brand-modern">
<i className="fas fa-cogs text-primary" style={{ fontSize: '1.8rem', marginBottom: '4px' }}></i>
<span className="brand-text-modern fw-bold">DTIC</span>
</div>
</div>
{/* Navigation */}
<nav className="sidebar-nav-modern" role="navigation" aria-label="Navegación principal">
{navItems.map((item) => (
<Link
key={item.path}
to={item.path}
className={`sidebar-link-modern ${isActive(item.path) ? 'active' : ''}`}
title={isCollapsed ? item.label : ''}
aria-label={item.label}
>
<i className={item.icon} aria-hidden="true"></i>
<span className="link-text-modern">{item.label}</span>
</Link>
))}
</nav>
</aside>
</>
)
}
export default Sidebar
@@ -0,0 +1,582 @@
import React, { useState, useEffect } from 'react'
import Sidebar from './Sidebar'
import { useAuthStore } from '../../stores/authStore'
import { useTheme } from '../../contexts/ThemeContext'
interface SidebarLayoutProps {
children: React.ReactNode
className?: string
}
export const SidebarLayout = ({ children, className = '' }: SidebarLayoutProps) => {
const [isSidebarCollapsed, setIsSidebarCollapsed] = useState(false)
const [isUserMenuOpen, setIsUserMenuOpen] = useState(false)
const { user, logout } = useAuthStore()
const { theme, toggleTheme } = useTheme()
const handleLogout = () => {
logout()
setIsUserMenuOpen(false)
}
// Load initial collapsed state from localStorage
useEffect(() => {
const savedState = localStorage.getItem('sidebarCollapsed')
if (savedState === 'true') {
setIsSidebarCollapsed(true)
}
}, [])
const handleSidebarToggle = (collapsed: boolean) => {
setIsSidebarCollapsed(collapsed)
}
// Close user menu when clicking outside
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
const target = event.target as Element
if (!target.closest('.floating-user-menu')) {
setIsUserMenuOpen(false)
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [])
return (
<div className={`sidebar-layout ${isSidebarCollapsed ? 'has-collapsed-sidebar' : ''} ${className}`}>
{/* Custom CSS for sidebar layout */}
<style>{`
.sidebar-layout {
display: flex;
min-height: 100vh;
background: var(--bg-primary);
}
.sidebar-main-content {
flex: 1;
margin-left: 280px;
transition: margin-left 0.3s ease;
display: flex;
flex-direction: column;
}
.sidebar-layout.has-collapsed-sidebar .sidebar-main-content {
margin-left: 70px;
}
/* Floating User Menu Styles */
.floating-user-menu {
position: fixed;
top: 20px;
right: 20px;
z-index: 1050;
}
.floating-user-avatar {
width: 48px;
height: 48px;
border-radius: 50%;
background: var(--bg-active);
border: 3px solid var(--bg-secondary);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 700;
font-size: 1.2rem;
cursor: pointer;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
box-shadow: 0 4px 12px var(--shadow-primary);
}
.floating-user-avatar:hover {
transform: scale(1.1);
box-shadow: 0 6px 20px var(--shadow-accent);
border-color: var(--bg-active);
}
.floating-user-avatar.active {
border-color: var(--bg-active);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.3);
}
.floating-user-dropdown {
position: absolute;
top: 60px;
right: 0;
width: 280px;
background: var(--bg-card);
border: 1px solid var(--border-primary);
border-radius: 16px;
box-shadow: 0 20px 25px -5px var(--shadow-primary), 0 10px 10px -5px var(--shadow-secondary);
opacity: 0;
visibility: hidden;
transform: translateY(-10px) scale(0.95);
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 1060;
}
.floating-user-dropdown.open {
opacity: 1;
visibility: visible;
transform: translateY(0) scale(1);
}
.user-dropdown-header {
padding: 20px;
border-bottom: 1px solid var(--border-primary);
background: var(--bg-tertiary);
border-radius: 16px 16px 0 0;
}
.user-avatar-large {
width: 64px;
height: 64px;
border-radius: 50%;
background: var(--bg-active);
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: 700;
font-size: 1.5rem;
margin: 0 auto 12px;
border: 3px solid var(--bg-secondary);
}
.user-full-info {
text-align: center;
}
.user-full-name {
font-weight: 700;
font-size: 1.1rem;
color: var(--text-primary);
margin-bottom: 4px;
}
.user-full-role {
font-size: 0.875rem;
color: var(--text-secondary);
background: var(--bg-active);
padding: 4px 12px;
border-radius: 20px;
display: inline-block;
font-weight: 500;
}
.user-dropdown-body {
padding: 8px 0;
}
.user-menu-item {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 20px;
color: var(--text-primary);
text-decoration: none;
transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
border-radius: 8px;
margin: 4px 12px;
}
.user-menu-item:hover {
background: var(--bg-hover);
transform: translateX(4px);
}
.user-menu-item i {
font-size: 1.1rem;
width: 20px;
color: var(--text-secondary);
}
.user-menu-item.logout {
color: var(--error);
border-top: 1px solid var(--border-primary);
margin-top: 8px;
padding-top: 16px;
}
.user-menu-item.logout:hover {
background: rgba(239, 68, 68, 0.1);
}
.user-menu-item.logout i {
color: var(--error);
}
/* Content adjustment - no top margin needed since no header */
.sidebar-content-wrapper {
flex: 1;
overflow-y: auto;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.sidebar-main-content {
margin-left: 0;
}
.sidebar-layout.has-collapsed-sidebar .sidebar-main-content {
margin-left: 0;
}
.sidebar-top-header {
left: 0;
right: 0;
padding: 0 20px;
}
.sidebar-layout.has-collapsed-sidebar .sidebar-top-header {
left: 0;
}
}
.sidebar-top-header {
background: white;
padding: 15px 30px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
border-bottom: 1px solid #e9ecef;
display: flex;
justify-content: space-between;
align-items: center;
min-height: 70px;
}
.sidebar-page-title {
margin: 0;
font-size: 1.5rem;
font-weight: 600;
color: #495057;
}
.sidebar-page-subtitle {
margin: 0;
font-size: 1rem;
color: #6c757d;
font-weight: 400;
}
.sidebar-page-content {
flex: 1;
padding: 30px;
overflow-y: auto;
}
.sidebar-breadcrumb {
background: white;
padding: 10px 30px;
border-bottom: 1px solid #e9ecef;
font-size: 0.875rem;
}
.sidebar-breadcrumb a {
color: #667eea;
text-decoration: none;
}
.sidebar-breadcrumb a:hover {
text-decoration: underline;
}
.sidebar-breadcrumb .current {
color: #6c757d;
}
/* Mobile responsiveness */
@media (max-width: 768px) {
.sidebar-main-content {
margin-left: 0;
}
.sidebar-layout.has-collapsed-sidebar .sidebar-main-content {
margin-left: 0;
}
.sidebar-page-content {
padding: 20px 15px;
}
.sidebar-top-header {
padding: 15px 20px;
}
}
/* Animation for content when sidebar collapses */
.sidebar-content-wrapper {
transition: all 0.3s ease;
}
/* Ensure proper spacing for fixed sidebar */
.sidebar-layout .sidebar-main-content {
width: calc(100% - 280px);
}
.sidebar-layout.has-collapsed-sidebar .sidebar-main-content {
width: calc(100% - 70px);
}
@media (max-width: 768px) {
.sidebar-layout .sidebar-main-content {
width: 100%;
}
.sidebar-layout.has-collapsed-sidebar .sidebar-main-content {
width: 100%;
}
}
/* Application Header Styles */
.app-header {
position: fixed;
top: 80px;
left: 280px;
right: 0;
height: 70px;
background: var(--bg-card);
border-bottom: 1px solid var(--border-primary);
box-shadow: 0 2px 4px var(--shadow-primary);
z-index: 1020;
transition: left 0.3s ease;
}
.sidebar-layout.has-collapsed-sidebar .app-header {
left: 70px;
}
.app-header-content {
height: 100%;
display: flex;
align-items: center;
padding: 0 30px;
}
.app-brand {
display: flex;
align-items: center;
gap: 15px;
}
.app-logo {
font-size: 2rem;
color: var(--bg-active);
}
.app-info {
display: flex;
flex-direction: column;
}
.app-name {
font-size: 1.5rem;
font-weight: 700;
color: var(--text-primary);
margin: 0;
line-height: 1.2;
}
.app-version {
font-size: 0.875rem;
color: var(--text-secondary);
background: var(--bg-active);
color: white;
padding: 2px 8px;
border-radius: 12px;
font-weight: 500;
display: inline-block;
margin-top: 2px;
}
/* Application Footer Styles */
.app-footer {
position: fixed;
bottom: 0;
left: 280px;
right: 0;
height: 50px;
background: var(--bg-card);
border-top: 1px solid var(--border-primary);
z-index: 1020;
transition: left 0.3s ease;
}
.sidebar-layout.has-collapsed-sidebar .app-footer {
left: 70px;
}
.app-footer-content {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
padding: 0 30px;
}
.footer-info {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
font-size: 0.875rem;
color: var(--text-muted);
}
.footer-text {
display: flex;
align-items: center;
}
.footer-version {
font-weight: 500;
color: var(--text-secondary);
}
/* Adjust main content for header and footer */
.sidebar-main-content {
margin-top: 150px;
margin-bottom: 50px;
min-height: calc(100vh - 200px);
}
/* Mobile responsiveness for header and footer */
@media (max-width: 768px) {
.app-header {
top: 80px;
left: 0;
height: 60px;
}
.sidebar-layout.has-collapsed-sidebar .app-header {
left: 0;
}
.app-header-content {
padding: 0 20px;
}
.app-name {
font-size: 1.25rem;
}
.app-logo {
font-size: 1.5rem;
}
.app-footer {
left: 0;
height: 45px;
}
.sidebar-layout.has-collapsed-sidebar .app-footer {
left: 0;
}
.app-footer-content {
padding: 0 20px;
}
.footer-info {
flex-direction: column;
gap: 5px;
text-align: center;
}
.sidebar-main-content {
margin-top: 140px;
margin-bottom: 45px;
min-height: calc(100vh - 185px);
}
}
`}</style>
<Sidebar onToggle={handleSidebarToggle} />
{/* Application Header */}
<header className="app-header">
<div className="app-header-content">
<div className="app-brand">
<i className="fas fa-cogs app-logo"></i>
<div className="app-info">
<h1 className="app-name">DTIC Bitácoras</h1>
<span className="app-version">v{(import.meta as any).env.VERSION}</span>
</div>
</div>
</div>
</header>
{/* Floating User Menu */}
<div className="floating-user-menu">
<div
className={`floating-user-avatar ${isUserMenuOpen ? 'active' : ''}`}
onClick={() => setIsUserMenuOpen(!isUserMenuOpen)}
title="Menú de usuario"
>
{user?.first_name?.charAt(0)?.toUpperCase() || 'U'}
</div>
<div className={`floating-user-dropdown ${isUserMenuOpen ? 'open' : ''}`}>
<div className="user-dropdown-header">
<div className="user-avatar-large">
{user?.first_name?.charAt(0)?.toUpperCase() || 'U'}
</div>
<div className="user-full-info">
<div className="user-full-name">{user?.first_name}</div>
<div className="user-full-role">
{user?.role === 'admin' ? 'Administrador' : 'Usuario'}
</div>
</div>
</div>
<div className="user-dropdown-body">
<a href="/perfil" className="user-menu-item" onClick={() => setIsUserMenuOpen(false)}>
<i className="fas fa-user-edit"></i>
<span>Mi Perfil</span>
</a>
<button
className="user-menu-item"
onClick={() => {
toggleTheme()
setIsUserMenuOpen(false)
}}
>
<i className={`fas ${theme === 'dark' ? 'fa-sun' : 'fa-moon'}`}></i>
<span>{theme === 'dark' ? 'Tema Claro' : 'Tema Oscuro'}</span>
</button>
<button
className="user-menu-item logout"
onClick={handleLogout}
>
<i className="fas fa-sign-out-alt"></i>
<span>Cerrar Sesión</span>
</button>
</div>
</div>
</div>
<main className="sidebar-main-content">
<div className="sidebar-content-wrapper">
{children}
</div>
</main>
{/* Application Footer */}
<footer className="app-footer">
<div className="app-footer-content">
<div className="footer-info">
<span className="footer-text">
<i className="fas fa-university me-2"></i>
DTIC - Universidad Tecnológica Nacional
</span>
<span className="footer-version">
Versión {(import.meta as any).env.VERSION}
</span>
</div>
</div>
</footer>
</div>
)
}
@@ -0,0 +1,596 @@
entities:
tecnicos:
name: "Técnicos"
title: "Gestión de Técnicos"
subtitle: "Administra los técnicos relacionados a recursos del sistema DTIC Bitácoras"
icon: "fa-users"
api:
endpoint: "/api/tecnicos"
methods:
fetch: "GET"
create: "POST"
update: "PUT"
delete: "DELETE"
toggleStatus: "PATCH"
fields:
- name: "first_name"
label: "Nombre"
type: "text"
required: true
- name: "last_name"
label: "Apellido"
type: "text"
required: true
- name: "email"
label: "Email"
type: "email"
required: true
- name: "role"
label: "Rol"
type: "select"
required: true
options:
- value: "admin"
label: "Administrador"
- value: "technician"
label: "Técnico"
- value: "viewer"
label: "Visualizador"
- name: "department"
label: "Departamento"
type: "select"
required: true
options:
- value: "dtic"
label: "DTIC"
- value: "sistemas"
label: "Sistemas"
- value: "redes"
label: "Redes"
- value: "seguridad"
label: "Seguridad"
- name: "phone"
label: "Teléfono"
type: "tel"
- name: "assigned_resources"
label: "Recursos Relacionados"
type: "resource_assignment"
resourceAssignmentConfig:
entityType: "tecnico"
entityId: "{{id}}"
required: false
description: "Gestión de recursos relacionados a este técnico con funcionalidad de agregar/quitar"
table:
columns:
- key: "role"
label: "Rol"
formatter: "formatRole"
- key: "full_name"
label: "Nombre"
- key: "email"
label: "Email"
- key: "department"
label: "Departamento"
formatter: "formatDepartment"
- key: "updated_at"
label: "Último Acceso"
formatter: "formatDate"
- key: "is_active"
label: "Estado"
formatter: "formatStatus"
filters:
- key: "role"
label: "Rol"
type: "select"
options:
- value: ""
label: "Todos"
- value: "admin"
label: "Admin"
- value: "technician"
label: "Técnico"
- value: "viewer"
label: "Viewer"
- key: "status"
label: "Estado"
type: "select"
options:
- value: ""
label: "Todos"
- value: "active"
label: "Activo"
- value: "inactive"
label: "Inactivo"
- value: "all"
label: "Todos (incluyendo inactivos)"
- key: "department"
label: "Depto"
type: "select"
options:
- value: ""
label: "Todos"
- value: "dtic"
label: "DTIC"
- value: "sistemas"
label: "Sistemas"
- value: "redes"
label: "Redes"
- value: "seguridad"
label: "Seguridad"
actions:
- key: "view"
label: "Ver Perfil"
icon: "fa-eye"
color: "primary"
modal: "profile"
- key: "edit"
label: "Editar"
icon: "fa-edit"
color: "warning"
- key: "changePassword"
label: "Cambiar contraseña"
icon: "fa-key"
color: "info"
modal: "changePassword"
- key: "delete"
label: "Eliminar técnico"
icon: "fa-trash"
color: "danger"
- key: "toggleStatus"
label: "Desactivar/Reactivar"
icon: "fa-ban/fa-check"
color: "danger/success"
condition: "is_active"
stats:
- title: "Total Técnicos"
value: "entities.length"
subtitle: "Registrados en el sistema"
color: "primary"
- title: "Activos"
value: "entities.filter(t => t.is_active).length"
subtitle: "Con acceso al sistema"
color: "success"
- title: "Inactivos"
value: "entities.filter(t => !t.is_active).length"
subtitle: "Acceso suspendido"
color: "warning"
- title: "Administradores"
value: "entities.filter(t => t.role === 'admin').length"
subtitle: "Acceso completo"
color: "danger"
modals:
- key: "profile"
component: "TecnicoProfileModal"
- key: "changePassword"
component: "ChangePasswordModal"
recursos:
name: "Recursos"
title: "Gestión de Recursos"
subtitle: "Administra el inventario de recursos del sistema DTIC Bitácoras"
icon: "fa-boxes"
api:
endpoint: "/api/recursos"
methods:
fetch: "GET"
create: "POST"
update: "PUT"
delete: "DELETE"
assign: "POST"
unassign: "DELETE"
fields:
- name: "name"
label: "Nombre"
type: "text"
required: true
- name: "description"
label: "Descripción"
type: "textarea"
rows: 3
- name: "category"
label: "Categoría"
type: "select"
required: true
options:
- value: "hardware"
label: "Hardware"
- value: "software"
label: "Software"
- value: "network"
label: "Redes"
- value: "security"
label: "Seguridad"
- value: "tools"
label: "Herramientas"
- value: "facilities"
label: "Instalaciones"
- name: "status"
label: "Estado"
type: "select"
required: true
options:
- value: "available"
label: "Disponible"
- value: "assigned"
label: "Relacionado"
- value: "maintenance"
label: "Mantenimiento"
- value: "retired"
label: "Retirado"
- name: "location"
label: "Ubicación"
type: "text"
- name: "model"
label: "Modelo"
type: "text"
- name: "serial_number"
label: "Número de Serie"
type: "text"
table:
columns:
- key: "status_category"
label: "Estado/Categoría"
formatter: "statusCategory"
- key: "recurso_modelo_serie"
label: "Recurso"
- key: "assigned_users"
label: "Usuarios"
formatter: "formatRelatedUsers"
- key: "related_tasks"
label: "Tareas"
formatter: "formatRelatedTasks"
filters:
- key: "category"
label: "Categoría"
type: "select"
options:
- value: ""
label: "Todas"
- value: "hardware"
label: "Hardware"
- value: "software"
label: "Software"
- value: "network"
label: "Redes"
- value: "security"
label: "Seguridad"
- value: "tools"
label: "Herramientas"
- value: "facilities"
label: "Instalaciones"
- key: "status"
label: "Estado"
type: "select"
options:
- value: ""
label: "Todos"
- value: "available"
label: "Disponible"
- value: "assigned"
label: "Relacionado"
- value: "maintenance"
label: "Mantenimiento"
- value: "retired"
label: "Retirado"
- key: "location"
label: "Ubicación"
type: "text"
placeholder: "Ubicación..."
actions:
- key: "view"
label: "Ver Detalles"
icon: "fa-eye"
color: "primary"
modal: "profile"
- key: "edit"
label: "Editar"
icon: "fa-edit"
color: "warning"
- key: "assign"
label: "Relacionar Usuario"
icon: "fa-user-plus"
color: "success"
modal: "assign"
- key: "delete"
label: "Eliminar recurso"
icon: "fa-trash"
color: "danger"
stats:
- title: "Total Recursos"
value: "entities.length"
subtitle: "En inventario"
color: "primary"
- title: "Disponibles"
value: "entities.filter((r) => r.status === 'available').length"
subtitle: "Listos para asignar"
color: "success"
- title: "Relacionados"
value: "entities.filter((r) => r.status === 'assigned').length"
subtitle: "En uso actualmente"
color: "info"
- title: "En Mantenimiento"
value: "entities.filter((r) => r.status === 'maintenance').length"
subtitle: "Fuera de servicio"
color: "warning"
modals:
- key: "profile"
component: "RecursoProfileModal"
- key: "assign"
component: "AssignUserModal"
usuarios:
name: "Usuarios Relacionados"
title: "Gestión de Usuarios Relacionados"
subtitle: "Administra usuarios que pueden tener recursos relacionados del sistema DTIC Bitácoras"
icon: "fa-user-cog"
api:
endpoint: "/api/usuarios_relacionados"
methods:
fetch: "GET"
create: "POST"
update: "PUT"
delete: "DELETE"
fields:
- name: "first_name"
label: "Nombre"
type: "text"
required: true
- name: "last_name"
label: "Apellido"
type: "text"
required: true
- name: "dtic_id"
label: "ID DTIC"
type: "text"
required: true
- name: "email"
label: "Email"
type: "email"
- name: "phone"
label: "Teléfono"
type: "tel"
- name: "department"
label: "Departamento"
type: "select"
options:
- value: "dtic"
label: "DTIC"
- value: "sistemas"
label: "Sistemas"
- value: "redes"
label: "Redes"
- value: "seguridad"
label: "Seguridad"
- name: "position"
label: "Cargo"
type: "text"
- name: "assigned_resources"
label: "Recursos Relacionados"
type: "resource_assignment"
resourceAssignmentConfig:
entityType: "usuario"
entityId: "{{id}}"
required: false
description: "Gestión de recursos relacionados a este usuario con funcionalidad de agregar/quitar"
table:
columns:
- key: "department"
label: "Departamento"
- key: "full_name"
label: "Nombre"
- key: "email"
label: "Email"
- key: "position"
label: "Cargo"
- key: "assigned_resources_count"
label: "Recursos Relacionados"
- key: "status"
label: "Estado"
formatter: "formatStatus"
filters:
- key: "department"
label: "Departamento"
type: "select"
options:
- value: ""
label: "Todos"
- value: "dtic"
label: "DTIC"
- value: "sistemas"
label: "Sistemas"
- value: "redes"
label: "Redes"
- value: "seguridad"
label: "Seguridad"
actions:
- key: "view"
label: "Ver Perfil"
icon: "fa-eye"
color: "primary"
modal: "profile"
- key: "edit"
label: "Editar"
icon: "fa-edit"
color: "warning"
- key: "delete"
label: "Eliminar usuario"
icon: "fa-trash"
color: "danger"
stats:
- title: "Total Usuarios"
value: "entities.length"
subtitle: "Registrados en el sistema"
color: "primary"
- title: "Con Recursos"
value: "entities.filter((u) => (u.assigned_resources_count || 0) > 0).length"
subtitle: "Tienen recursos relacionados"
color: "success"
- title: "Sin Recursos"
value: "entities.filter((u) => (u.assigned_resources_count || 0) === 0).length"
subtitle: "Sin asignaciones activas"
color: "warning"
- title: "Recursos Totales"
value: "entities.reduce((total, u) => total + (u.assigned_resources_count || 0), 0)"
subtitle: "Relacionados actualmente"
color: "info"
modals:
- key: "profile"
component: "UsuarioProfileModal"
tareas:
name: "Tareas"
title: "Gestión de Tareas"
subtitle: "Administra las tareas relacionadas a los técnicos del sistema DTIC Bitácoras"
icon: "fa-tasks"
api:
endpoint: "/api/tareas"
methods:
fetch: "GET"
create: "POST"
update: "PUT"
delete: "DELETE"
fields:
- name: "title"
label: "Título"
type: "text"
required: true
- name: "description"
label: "Descripción"
type: "textarea"
rows: 3
- name: "technician_id"
label: "Técnico Relacionado"
type: "select"
dynamicOptions:
endpoint: "/api/tecnicos"
labelField: "full_name"
valueField: "id"
params:
status: "active"
options:
- value: ""
label: "Sin relacionar"
- name: "priority"
label: "Prioridad"
type: "select"
required: true
options:
- value: "low"
label: "Baja"
- value: "medium"
label: "Media"
- value: "high"
label: "Alta"
- value: "urgent"
label: "Urgente"
- name: "status"
label: "Estado"
type: "select"
required: true
options:
- value: "pending"
label: "Pendiente"
- value: "in_progress"
label: "En Progreso"
- value: "completed"
label: "Completada"
- value: "cancelled"
label: "Cancelada"
- name: "due_date"
label: "Fecha Límite"
type: "date"
- name: "assigned_resources"
label: "Recursos Relacionados"
type: "resource_assignment"
resourceAssignmentConfig:
entityType: "tarea"
entityId: "{{id}}"
required: false
description: "Gestión de recursos relacionados a esta tarea con funcionalidad de agregar/quitar"
table:
columns:
- key: "status_priority"
label: "Estado/Prioridad"
formatter: "formatStatusPriority"
- key: "title"
label: "Tarea"
- key: "assigned_resources"
label: "Recurso/s"
formatter: "formatAssignedResources"
- key: "technician_name"
label: "Técnico"
filters:
- key: "technician_id"
label: "Técnico"
type: "select"
dynamicOptions:
endpoint: "/api/tecnicos"
labelField: "full_name"
valueField: "id"
params:
status: "active"
options:
- value: ""
label: "Todos"
- key: "status"
label: "Estado"
type: "select"
options:
- value: ""
label: "Todos"
- value: "pending"
label: "Pendiente"
- value: "in_progress"
label: "En Progreso"
- value: "completed"
label: "Completada"
- value: "cancelled"
label: "Cancelada"
- key: "priority"
label: "Prioridad"
type: "select"
options:
- value: ""
label: "Todas"
- value: "low"
label: "Baja"
- value: "medium"
label: "Media"
- value: "high"
label: "Alta"
- value: "urgent"
label: "Urgente"
actions:
- key: "view"
label: "Ver Detalles"
icon: "fa-eye"
color: "primary"
modal: "profile"
- key: "edit"
label: "Editar"
icon: "fa-edit"
color: "warning"
- key: "delete"
label: "Eliminar tarea"
icon: "fa-trash"
color: "danger"
stats:
- title: "Total Tareas"
value: "entities.length"
subtitle: "Registradas en el sistema"
color: "primary"
- title: "Pendientes"
value: "entities.filter((t) => t.status === 'pending').length"
subtitle: "Esperando relación"
color: "warning"
- title: "En Progreso"
value: "entities.filter((t) => t.status === 'in_progress').length"
subtitle: "Siendo trabajadas"
color: "info"
- title: "Completadas"
value: "entities.filter((t) => t.status === 'completed').length"
subtitle: "Finalizadas exitosamente"
color: "success"
modals:
- key: "profile"
component: "TareaProfileModal"
@@ -0,0 +1,71 @@
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react'
type Theme = 'light' | 'dark'
interface ThemeContextType {
theme: Theme
toggleTheme: () => void
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined)
interface ThemeProviderProps {
children: ReactNode
}
export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
const [theme, setTheme] = useState<Theme>('dark')
// Load theme from localStorage on mount
useEffect(() => {
const savedTheme = localStorage.getItem('theme') as Theme
if (savedTheme && (savedTheme === 'light' || savedTheme === 'dark')) {
setTheme(savedTheme)
}
}, [])
// Apply theme to document and update CSS variables
useEffect(() => {
const root = document.documentElement
// Remove existing theme classes
root.classList.remove('dark-theme')
// Add current theme class if dark
if (theme === 'dark') {
root.classList.add('dark-theme')
}
// Save to localStorage
localStorage.setItem('theme', theme)
// Update meta theme-color for mobile browsers
const metaThemeColor = document.querySelector('meta[name="theme-color"]')
if (metaThemeColor) {
metaThemeColor.setAttribute('content', theme === 'dark' ? '#0a0a0a' : '#ffffff')
}
}, [theme])
const toggleTheme = () => {
setTheme(prevTheme => prevTheme === 'light' ? 'dark' : 'light')
}
const value: ThemeContextType = {
theme,
toggleTheme
}
return (
<ThemeContext.Provider value={value}>
{children}
</ThemeContext.Provider>
)
}
export const useTheme = (): ThemeContextType => {
const context = useContext(ThemeContext)
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider')
}
return context
}
@@ -0,0 +1,199 @@
import { useState } from 'react'
import toast from 'react-hot-toast'
export interface EntityManagementState<T> {
showEditForm: boolean
setShowEditForm: (show: boolean) => void
editingEntity: T | null
setEditingEntity: (entity: T | null) => void
showCreateForm: boolean
setShowCreateForm: (show: boolean) => void
}
export interface EntityManagementActions<T> {
handleCreate: (data: Partial<T>) => Promise<void>
handleEdit: (id: number) => Promise<void>
handleUpdate: (data: Partial<T>) => Promise<void>
handleDelete: (id: number) => Promise<void>
handleViewProfile: (id: number) => void
}
export interface EntityStore<T> {
entities?: T[]
loading: boolean
error: string | null
pagination?: {
page: number
limit: number
total: number
pages: number
}
filters: Record<string, any>
fetchEntities: (page?: number) => Promise<void>
createEntity: (data: Partial<T>) => Promise<void>
updateEntity: (id: number, data: Partial<T>) => Promise<void>
deleteEntity: (id: number) => Promise<void>
setFilters: (filters: Record<string, any>) => void
clearFilters: () => void
}
export const useEntityManagement = <T extends { id: number; name?: string; full_name?: string }>(
store: EntityStore<T> & { [key: string]: any },
entityName: string,
entityNamePlural: string = entityName + 's',
entitiesKey: string = 'entities'
): EntityManagementState<T> & EntityManagementActions<T> => {
const [showEditForm, setShowEditForm] = useState(false)
const [editingEntity, setEditingEntity] = useState<T | null>(null)
const [showCreateForm, setShowCreateForm] = useState(false)
const handleCreate = async (data: Partial<T>) => {
try {
await store.createEntity(data)
toast.success(`${entityName} creado exitosamente`)
setShowCreateForm(false)
} catch (error) {
// Error handled by store
}
}
const handleEdit = async (id: number) => {
console.log('[DEBUG] handleEdit called with id:', id)
console.log('[DEBUG] entitiesKey:', entitiesKey)
console.log('[DEBUG] store[entitiesKey]:', store[entitiesKey])
console.log('[DEBUG] store[entitiesKey] type:', typeof store[entitiesKey])
console.log('[DEBUG] store[entitiesKey] length:', store[entitiesKey]?.length)
console.log('[DEBUG] entityName:', entityName)
const entities = store[entitiesKey]
if (!entities || !Array.isArray(entities)) {
console.error('[DEBUG] store[entitiesKey] is not an array or is undefined')
return
}
const entity = entities.find(e => e.id === id)
console.log('[DEBUG] Found entity:', entity)
console.log('[DEBUG] Entity id type:', typeof entity?.id, 'Entity id value:', entity?.id)
if (entity) {
console.log('[DEBUG] Setting editingEntity and showEditForm')
setEditingEntity(entity)
setShowEditForm(true)
// Scroll suave al formulario de edición con animación mejorada
setTimeout(() => {
const editForm = document.getElementById('editFormSection')
console.log('[DEBUG] Looking for editFormSection element:', editForm)
if (editForm) {
console.log('[DEBUG] Scrolling to edit form')
editForm.scrollIntoView({
behavior: 'smooth',
block: 'start'
})
// Agregar clase para animación adicional
editForm.classList.add('highlight-form')
setTimeout(() => {
editForm.classList.remove('highlight-form')
}, 2000)
} else {
console.warn('[DEBUG] editFormSection element not found')
}
}, 150)
} else {
console.warn(`Entity with id ${id} not found in store. Available entities:`, entities.map(e => e.id))
}
}
const handleUpdate = async (data: Partial<T>) => {
console.log('[DEBUG] handleUpdate called with data:', data)
console.log('[DEBUG] editingEntity:', editingEntity)
console.log('[DEBUG] store.updateEntity available:', typeof store.updateEntity)
if (!editingEntity) {
console.warn('[DEBUG] No editingEntity found, returning early')
return
}
try {
// Filtrar solo los campos que realmente cambiaron y son válidos para actualizar
const updateData: Partial<T> = {}
// Para tareas, solo enviar campos específicos que pueden actualizarse
if (entityName === 'tareas') {
const allowedFields = ['title', 'description', 'technician_id', 'status', 'priority', 'due_date']
allowedFields.forEach(key => {
const currentValue = editingEntity[key as keyof T]
const newValue = data[key as keyof T]
// Comparar valores y solo incluir si son diferentes
if (newValue !== undefined && newValue !== currentValue) {
updateData[key as keyof T] = newValue
}
})
} else {
// Para otras entidades, copiar todos los datos
Object.assign(updateData, data)
}
console.log('[DEBUG] Filtered update data:', updateData)
if (Object.keys(updateData).length === 0) {
console.log('[DEBUG] No changes detected, closing form')
setShowEditForm(false)
setEditingEntity(null)
return
}
console.log('[DEBUG] Calling store.updateEntity with id:', editingEntity.id)
console.log('[DEBUG] Data to send:', updateData)
await store.updateEntity(editingEntity.id, updateData)
console.log('[DEBUG] Update successful, showing success toast')
toast.success(`${entityName} actualizado exitosamente`)
console.log('[DEBUG] Setting showEditForm to false and editingEntity to null')
setShowEditForm(false)
setEditingEntity(null)
console.log('[DEBUG] Form should be closed now')
} catch (error) {
console.error('[DEBUG] Error in handleUpdate:', error)
console.error('[DEBUG] Error details:', error instanceof Error ? error.message : error)
toast.error(`Error al actualizar ${entityName.toLowerCase()}: ${error instanceof Error ? error.message : 'Error desconocido'}`)
}
}
const handleDelete = async (id: number) => {
if (window.confirm(`¿Está seguro de eliminar este ${entityName.toLowerCase()}?`)) {
try {
await store.deleteEntity(id)
toast.success(`${entityName} eliminado exitosamente`)
} catch (error) {
// Error handled by store
}
}
}
const handleViewProfile = (id: number) => {
const entities = store[entitiesKey]
const entity = entities?.find(e => e.id === id)
if (entity) {
toast.info(`Ver detalles del ${entityName.toLowerCase()}: ${entity.full_name || entity.name || 'Sin nombre'}`)
}
}
return {
// State
showEditForm,
setShowEditForm,
editingEntity,
setEditingEntity,
showCreateForm,
setShowCreateForm,
// Actions
handleCreate,
handleEdit,
handleUpdate,
handleDelete,
handleViewProfile
}
}
@@ -0,0 +1,352 @@
import { useState, useCallback, useEffect } from 'react'
import toast from 'react-hot-toast'
export interface AssignedResource {
id: number
name: string
category?: string
status?: string
location?: string
}
export interface ResourceOption {
id: number
name: string
category?: string
status?: string
location?: string
}
export interface ResourceAssignmentData {
entity_type: 'tarea' | 'usuario' | 'tecnico' | 'recurso'
entity_id: number
resource_id: number
}
export interface UseResourceAssignmentState {
assignedResources: AssignedResource[]
availableResources: ResourceOption[]
loading: boolean
error: string | null
}
export interface UseResourceAssignmentActions {
assignResource: (resourceId: number) => Promise<boolean>
unassignResource: (resourceId: number) => Promise<boolean>
loadAssignedResources: () => Promise<void>
loadAvailableResources: () => Promise<void>
refreshAssignments: () => Promise<void>
}
export type UseResourceAssignment = UseResourceAssignmentState & UseResourceAssignmentActions
export const useResourceAssignment = (
entityType: 'tarea' | 'usuario' | 'tecnico' | 'recurso',
entityId: number
): UseResourceAssignment => {
// Use relative paths for Vite proxy
const API_BASE = '/api'
const [state, setState] = useState<UseResourceAssignmentState>({
assignedResources: [],
availableResources: [],
loading: false,
error: null
})
const setLoading = useCallback((loading: boolean) => {
setState(prev => ({ ...prev, loading }))
}, [])
const setError = useCallback((error: string | null) => {
setState(prev => ({ ...prev, error }))
}, [])
// Load currently assigned resources
const loadAssignedResources = useCallback(async () => {
setLoading(true)
setError(null)
try {
let endpoint = ''
let queryParams = ''
// Build endpoint based on entity type
switch (entityType) {
case 'tarea':
endpoint = `${API_BASE}/tarea-recursos/tareas/${entityId}/recursos`
break
case 'usuario':
endpoint = `${API_BASE}/usuarios_relacionados/usuarios/${entityId}/recursos`
break
case 'tecnico':
endpoint = `${API_BASE}/tecnico-recursos/tecnicos/${entityId}/recursos`
break
case 'recurso':
endpoint = `${API_BASE}/recursos-asignados/recursos/${entityId}/asignaciones`
break
default:
endpoint = `${API_BASE}/tarea-recursos/tareas/${entityId}/recursos`
}
const response = await fetch(endpoint)
if (!response.ok) {
throw new Error(`Error al cargar recursos asignados: ${response.status}`)
}
const data = await response.json()
if (data.success && data.data) {
// Handle different response structures
let resources = []
if (data.data.assignments) {
// Backend returns { assignments: [...] }
resources = data.data.assignments
} else if (Array.isArray(data.data)) {
// Direct array response
resources = data.data
} else {
resources = []
}
// Map resources to expected format
const mappedResources = resources.map((resource: any) => {
// Handle different naming patterns from backend
const name = resource.recurso_name || resource.name || resource.resource_name || 'Recurso desconocido'
const category = resource.recurso_category || resource.category
const status = resource.recurso_status || resource.status
const location = resource.recurso_location || resource.location
const id = resource.recurso_id || resource.id || resource.resource_id
return {
id: id || 0,
name: name,
category: category,
status: status,
location: location
}
}).filter(resource => resource.id) // Filter out invalid resources
setState(prev => ({
...prev,
assignedResources: mappedResources
}))
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Error desconocido'
setError(errorMessage)
console.error('Error loading assigned resources:', error)
// Don't show toast error for missing assignments, it's normal for new entities
} finally {
setLoading(false)
}
}, [entityType, entityId, setLoading, setError])
// Load available resources for assignment
const loadAvailableResources = useCallback(async () => {
try {
const response = await fetch(`${API_BASE}/recursos?status=available`)
if (!response.ok) {
throw new Error(`Error al cargar recursos disponibles: ${response.status}`)
}
const data = await response.json()
if (data.success && data.data) {
const resources = Array.isArray(data.data) ? data.data : data.data.recursos || []
setState(prev => ({
...prev,
availableResources: resources.map((resource: any) => ({
id: resource.id,
name: resource.name,
category: resource.category,
status: resource.status,
location: resource.location
}))
}))
}
} catch (error) {
console.error('Error loading available resources:', error)
// Don't show error toast for available resources as it's not critical
}
}, [])
// Assign a resource to the entity
const assignResource = useCallback(async (resourceId: number): Promise<boolean> => {
setLoading(true)
setError(null)
try {
// Build endpoint based on entity type
let endpoint = ''
let requestBody = {}
switch (entityType) {
case 'tarea':
endpoint = `${API_BASE}/tarea-recursos/tareas/${entityId}/recursos`
requestBody = { recurso_id: resourceId }
break
case 'usuario':
endpoint = `${API_BASE}/usuarios_relacionados/usuarios/${entityId}/recursos`
requestBody = { resource_id: resourceId }
break
case 'tecnico':
endpoint = `${API_BASE}/tecnico-recursos/tecnicos/${entityId}/recursos`
requestBody = { resource_id: resourceId }
break
case 'recurso':
endpoint = `${API_BASE}/recursos-asignados/recursos/${entityId}/asignaciones`
requestBody = { entity_type: 'tarea', entity_id: entityId, resource_id: resourceId }
break
default:
throw new Error('Tipo de entidad no soportado')
}
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
if (response.status === 409) {
const errorData = await response.json().catch(() => ({}))
const message = errorData.message || 'Error de conflicto al asignar recurso'
throw new Error(message)
} else {
throw new Error(`Error al asignar recurso: ${response.status}`)
}
}
const data = await response.json()
if (data.success) {
toast.success('Recurso relacionado exitosamente')
await refreshAssignments()
return true
} else {
throw new Error(data.message || 'Error al asignar recurso')
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Error desconocido'
setError(errorMessage)
console.error('Error assigning resource:', error)
// Don't show toast for now due to missing backend endpoints
return false
} finally {
setLoading(false)
}
}, [entityType, entityId, setLoading, setError])
// Unassign a resource from the entity
const unassignResource = useCallback(async (resourceId: number): Promise<boolean> => {
setLoading(true)
setError(null)
try {
// Build endpoint based on entity type
let endpoint = ''
let requestBody = {}
switch (entityType) {
case 'tarea':
endpoint = `${API_BASE}/tarea-recursos/tareas/${entityId}/recursos/${resourceId}`
requestBody = {}
break
case 'usuario':
endpoint = `${API_BASE}/usuarios_relacionados/usuarios/${entityId}/recursos/${resourceId}`
requestBody = {}
break
case 'tecnico':
endpoint = `${API_BASE}/tecnico-recursos/tecnicos/${entityId}/recursos/${resourceId}`
requestBody = {}
break
case 'recurso':
endpoint = `${API_BASE}/recursos-asignados/recursos/${resourceId}/asignaciones`
requestBody = { entity_type: entityType, entity_id: entityId }
break
default:
throw new Error('Tipo de entidad no soportado')
}
const response = await fetch(endpoint, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
})
if (!response.ok) {
throw new Error(`Error al desasignar recurso: ${response.status}`)
}
const data = await response.json()
if (data.success) {
// Don't show toast for now due to missing backend endpoints
await refreshAssignments()
return true
} else {
throw new Error(data.message || 'Error al desasignar recurso')
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Error desconocido'
setError(errorMessage)
console.error('Error unassigning resource:', error)
return false
} finally {
setLoading(false)
}
}, [entityType, entityId, setLoading, setError])
// Refresh both assigned and available resources
const refreshAssignments = useCallback(async () => {
await Promise.all([
loadAssignedResources(),
loadAvailableResources()
])
}, [loadAssignedResources, loadAvailableResources])
// Helper function to get the correct endpoint for assignments
const getAssignmentEndpoint = (type: string): string => {
switch (type) {
case 'tarea':
return '/api/tarea-recursos'
case 'usuario':
return '/api/usuarios_relacionados'
case 'tecnico':
return '/api/tecnico-recursos'
case 'recurso':
return '/api/recursos-asignados'
default:
return '/api/tarea-recursos'
}
}
// Auto-load data when hook is initialized
useEffect(() => {
refreshAssignments()
}, [refreshAssignments])
return {
// State
assignedResources: state.assignedResources,
availableResources: state.availableResources,
loading: state.loading,
error: state.error,
// Actions
assignResource,
unassignResource,
loadAssignedResources,
loadAvailableResources,
refreshAssignments
}
}
export default useResourceAssignment
+318
View File
@@ -0,0 +1,318 @@
/* DTIC Bitácoras - Estilos personalizados para React */
:root {
--primary-color: #667eea;
--secondary-color: #764ba2;
--success-color: #28a745;
--warning-color: #ffc107;
--danger-color: #dc3545;
--info-color: #17a2b8;
--dark-color: #343a40;
--light-color: #f8f9fa;
--shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
--border-radius: 8px;
--transition: all 0.3s ease;
/* Light theme colors */
--bg-primary: #ffffff;
--bg-secondary: #f8f9fa;
--bg-tertiary: #e9ecef;
--bg-hover: #dee2e6;
--bg-active: #667eea;
--text-primary: #212529;
--text-secondary: #6c757d;
--text-muted: #adb5bd;
--border-primary: #dee2e6;
--border-secondary: #ced4da;
--shadow-primary: rgba(0, 0, 0, 0.1);
--shadow-secondary: rgba(0, 0, 0, 0.05);
--shadow-accent: rgba(102, 126, 234, 0.3);
}
/* Dark theme overrides */
.dark-theme {
--bg-primary: #1a1a1a;
--bg-secondary: #2d2d2d;
--bg-tertiary: #404040;
--bg-hover: #4a4a4a;
--bg-active: #4f46e5;
--text-primary: #ffffff;
--text-secondary: #cccccc;
--text-muted: #888888;
--border-primary: #555555;
--border-secondary: #666666;
--shadow-primary: rgba(0, 0, 0, 0.3);
--shadow-secondary: rgba(0, 0, 0, 0.2);
--shadow-accent: rgba(79, 70, 229, 0.5);
}
* {
box-sizing: border-box;
}
body {
margin: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #f0f4f8 0%, #e1e8ed 100%);
min-height: 100vh;
color: #333;
}
.App {
min-height: 100vh;
}
.main-content {
padding-top: 76px; /* Altura del navbar */
min-height: calc(100vh - 76px);
}
/* Cards */
.card {
border: none;
border-radius: var(--border-radius);
box-shadow: var(--shadow);
transition: var(--transition);
background: white;
overflow: hidden;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}
.card-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-bottom: none;
padding: 1rem 1.25rem;
}
/* Botones */
.btn {
border-radius: var(--border-radius);
font-weight: 500;
transition: var(--transition);
border: none;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.btn-success {
background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
color: white;
}
.btn-warning {
background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
color: white;
}
.btn-danger {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
color: white;
}
/* Formularios */
.form-control {
border-radius: var(--border-radius);
border: 2px solid #e9ecef;
transition: var(--transition);
}
.form-control:focus {
border-color: var(--primary-color);
box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}
.form-label {
font-weight: 600;
color: var(--dark-color);
margin-bottom: 0.5rem;
}
/* Estados de carga */
.loading {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: #fff;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* Responsive */
@media (max-width: 768px) {
.main-content {
padding-top: 60px;
}
}
/* Utilidades */
.text-gradient {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.shadow-custom {
box-shadow: var(--shadow) !important;
}
.border-radius-custom {
border-radius: var(--border-radius) !important;
}
/* Animaciones */
.fade-in {
animation: fadeIn 0.5s ease-out;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Dark theme overrides for components */
.dark-theme body {
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a1a 100%);
color: var(--text-primary);
}
.dark-theme .card {
background: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.dark-theme .card-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border-bottom-color: var(--border-primary);
}
.dark-theme .table {
color: var(--text-primary);
background-color: var(--bg-secondary);
}
.dark-theme .table th,
.dark-theme .table td {
color: var(--text-primary);
background-color: var(--bg-secondary);
border-color: var(--border-primary);
}
.dark-theme .table-hover tbody tr:hover {
background-color: var(--bg-hover);
color: var(--text-primary);
}
.dark-theme .table-hover tbody tr:hover td {
background-color: var(--bg-hover);
color: var(--text-primary);
}
.dark-theme .text-muted {
color: var(--text-muted) !important;
}
.dark-theme .badge.bg-light {
background-color: var(--bg-tertiary) !important;
color: var(--text-primary) !important;
}
.dark-theme .bg-light {
background-color: var(--bg-tertiary) !important;
color: var(--text-primary) !important;
}
.dark-theme .bg-warning {
background-color: #f59e0b !important;
color: #000000 !important;
}
.dark-theme .bg-warning.text-dark {
color: #000000 !important;
}
.dark-theme .modal-content {
background-color: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.dark-theme .modal-header {
background-color: var(--bg-tertiary);
color: var(--text-primary);
border-bottom-color: var(--border-primary);
}
.dark-theme .modal-body {
background-color: var(--bg-secondary);
color: var(--text-primary);
}
.dark-theme .modal-footer {
background-color: var(--bg-tertiary);
color: var(--text-primary);
border-top-color: var(--border-primary);
}
.dark-theme .form-control {
background-color: var(--bg-primary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.dark-theme .form-control:focus {
background-color: var(--bg-primary);
color: var(--text-primary);
border-color: var(--primary-color);
}
.dark-theme .form-label {
color: var(--text-primary);
}
.dark-theme .btn-secondary {
background-color: var(--bg-tertiary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.dark-theme .btn-secondary:hover {
background-color: var(--bg-hover);
color: var(--text-primary);
}
.dark-theme .list-group-item {
background-color: var(--bg-secondary);
color: var(--text-primary);
border-color: var(--border-primary);
}
.dark-theme .list-group-item:hover {
background-color: var(--bg-hover);
color: var(--text-primary);
}
+13
View File
@@ -0,0 +1,13 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App.tsx'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
)
@@ -0,0 +1,692 @@
import { useEffect, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
interface CalendarEvent {
id: string
title: string
start: string
end: string
backgroundColor: string
borderColor: string
textColor: string
extendedProps: {
type: string
technician: string
technicianName: string
resource: string
resourceName: string
description: string
subtasks: Array<{
title: string
time: string
technician: string
}>
reminders: string[]
}
}
interface CalendarStats {
events: number
tasks: number
activeTechnicians: number
busyResources: number
}
const Calendario = () => {
const { user } = useAuthStore()
const [calendar, setCalendar] = useState<any>(null)
const [currentEvents, setCurrentEvents] = useState<CalendarEvent[]>([])
const [upcomingEvents, setUpcomingEvents] = useState<CalendarEvent[]>([])
const [stats, setStats] = useState<CalendarStats>({
events: 0,
tasks: 0,
activeTechnicians: 0,
busyResources: 0
})
const [showEventModal, setShowEventModal] = useState(false)
const [showDetailsModal, setShowDetailsModal] = useState(false)
const [selectedEvent, setSelectedEvent] = useState<CalendarEvent | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
initializeCalendar()
return () => {
if (calendar) {
calendar.destroy()
}
}
}, [])
useEffect(() => {
if (calendar) {
loadCalendarData()
}
}, [calendar])
const initializeCalendar = () => {
// Load FullCalendar dynamically
const script = document.createElement('script')
script.src = 'https://cdn.jsdelivr.net/npm/fullcalendar@6.1.8/index.global.min.js'
script.onload = () => {
setTimeout(() => {
const calendarEl = document.getElementById('calendar')
if (calendarEl && (window as any).FullCalendar) {
const cal = new (window as any).FullCalendar.Calendar(calendarEl, {
initialView: 'dayGridMonth',
locale: 'es',
headerToolbar: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
buttonText: {
today: 'Hoy',
month: 'Mes',
week: 'Semana',
day: 'Día',
list: 'Lista'
},
height: 'auto',
editable: true,
selectable: true,
selectMirror: true,
dayMaxEvents: true,
eventDisplay: 'block',
eventTimeFormat: {
hour: '2-digit',
minute: '2-digit',
meridiem: false
},
slotLabelFormat: {
hour: '2-digit',
minute: '2-digit',
meridiem: false
},
nowIndicator: true,
businessHours: {
daysOfWeek: [1, 2, 3, 4, 5],
startTime: '08:00',
endTime: '18:00'
},
eventClick: function(info: any) {
showEventDetails(info.event)
},
select: function(info: any) {
openNewEventModal(info.start, info.end)
},
eventDrop: function(info: any) {
updateEventTime(info.event)
},
eventResize: function(info: any) {
updateEventTime(info.event)
},
datesSet: function(dateInfo: any) {
updateMonthStatistics()
}
})
cal.render()
setCalendar(cal)
setLoading(false)
} else {
console.error('FullCalendar not loaded or calendar element not found')
setLoading(false)
}
}, 1000) // Wait for script to fully load
}
script.onerror = () => {
console.error('Failed to load FullCalendar script')
setLoading(false)
}
document.head.appendChild(script)
}
const loadCalendarData = () => {
// Mock data - in production this would come from API
const mockEvents: CalendarEvent[] = [
{
id: '1',
title: 'Preparar los equipos en el Auditorio con música y proyector',
start: '2025-11-15T14:00:00',
end: '2025-11-15T16:00:00',
backgroundColor: '#17a2b8',
borderColor: '#17a2b8',
textColor: '#ffffff',
extendedProps: {
type: 'event',
technician: 'jgarcia',
technicianName: 'Juan García',
resource: 'auditorio',
resourceName: 'Auditorio',
description: 'Evento especial de capacitación técnica',
subtasks: [
{
title: 'Hacer pruebas de sonido y video 1 hora antes',
time: '2025-11-15T13:00:00',
technician: 'jgarcia'
},
{
title: 'Verificar conectividad de proyectores 30 minutos antes',
time: '2025-11-15T13:30:00',
technician: 'mrodriguez'
}
],
reminders: ['1h', '30m']
}
},
{
id: '2',
title: 'Mantenimiento preventivo de servidores',
start: '2025-11-16T09:00:00',
end: '2025-11-16T12:00:00',
backgroundColor: '#28a745',
borderColor: '#28a745',
textColor: '#ffffff',
extendedProps: {
type: 'maintenance',
technician: 'clopez',
technicianName: 'Carlos López',
resource: 'computadoras',
resourceName: 'Sala de Servidores',
description: 'Mantenimiento rutinario de equipos',
subtasks: [],
reminders: ['1h']
}
},
{
id: '3',
title: 'Capacitación en ciberseguridad',
start: '2025-11-18T10:00:00',
end: '2025-11-18T12:00:00',
backgroundColor: '#ffc107',
borderColor: '#ffc107',
textColor: '#000000',
extendedProps: {
type: 'training',
technician: 'amartinez',
technicianName: 'Ana Martínez',
resource: 'auditorio',
resourceName: 'Auditorio',
description: 'Sesión de capacitación para todo el equipo',
subtasks: [],
reminders: ['1h', '15m']
}
},
{
id: '4',
title: 'Reunión de coordinación semanal',
start: '2025-11-17T08:30:00',
end: '2025-11-17T09:30:00',
backgroundColor: '#6c757d',
borderColor: '#6c757d',
textColor: '#ffffff',
extendedProps: {
type: 'meeting',
technician: 'rmartinez',
technicianName: 'Roberto Martínez',
resource: 'auditorio',
resourceName: 'Sala de Reuniones',
description: 'Reunión semanal de coordinación del equipo DTIC',
subtasks: [],
reminders: ['15m']
}
}
]
setCurrentEvents(mockEvents)
// Add events to calendar if it's initialized
if (calendar) {
calendar.addEventSource(mockEvents)
}
updateUpcomingEvents(mockEvents)
updateMonthStatistics()
}
const updateUpcomingEvents = (events: CalendarEvent[] = currentEvents) => {
const now = new Date()
const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)
const upcoming = events
.filter(event => {
const eventStart = new Date(event.start)
return eventStart >= now && eventStart <= nextWeek
})
.sort((a, b) => new Date(a.start).getTime() - new Date(b.start).getTime())
.slice(0, 6)
setUpcomingEvents(upcoming)
}
const updateMonthStatistics = () => {
if (!calendar) return
const view = calendar.view
const start = view.activeStart
const end = view.activeEnd
const monthEvents = currentEvents.filter(event => {
const eventStart = new Date(event.start)
return eventStart >= start && eventStart < end
})
const technicians = new Set()
const resources = new Set()
monthEvents.forEach(event => {
technicians.add(event.extendedProps.technician)
if (event.extendedProps.resource) {
resources.add(event.extendedProps.resource)
}
})
const totalTasks = monthEvents.reduce((sum, event) => {
return sum + (event.extendedProps.subtasks ? event.extendedProps.subtasks.length : 0)
}, 0)
setStats({
events: monthEvents.length,
tasks: totalTasks,
activeTechnicians: technicians.size,
busyResources: resources.size
})
}
const showEventDetails = (event: any) => {
const calendarEvent = currentEvents.find(e => e.id === event.id)
if (calendarEvent) {
setSelectedEvent(calendarEvent)
setShowDetailsModal(true)
}
}
const openNewEventModal = (start: Date, end: Date) => {
// Pre-fill start and end times
const startInput = document.getElementById('eventStart') as HTMLInputElement
const endInput = document.getElementById('eventEnd') as HTMLInputElement
if (startInput && endInput) {
startInput.value = formatDateTime(start)
endInput.value = formatDateTime(end)
}
setShowEventModal(true)
}
const updateEventTime = (event: any) => {
console.log('Event time updated:', event.id, event.start, event.end)
// In production, this would update the backend
}
const formatDateTime = (date: Date) => {
return date.toISOString().slice(0, 16)
}
const getEventTypeIcon = (type: string) => {
const icons: { [key: string]: string } = {
'maintenance': 'fas fa-wrench',
'event': 'fas fa-calendar-star',
'training': 'fas fa-graduation-cap',
'meeting': 'fas fa-users'
}
return icons[type] || 'fas fa-calendar'
}
const handleViewChange = (view: string) => {
if (calendar) {
calendar.changeView(view)
}
}
const handleTechnicianFilter = (technician: string) => {
if (!calendar) return
calendar.getEvents().forEach((event: any) => {
const show = !technician || event.extendedProps.technician === technician
event.setProp('display', show ? 'auto' : 'none')
})
}
const handleResourceFilter = (resource: string) => {
if (!calendar) return
calendar.getEvents().forEach((event: any) => {
const show = !resource || event.extendedProps.resource === resource
event.setProp('display', show ? 'auto' : 'none')
})
}
const clearFilters = () => {
if (!calendar) return
const technicianSelect = document.getElementById('technicianFilter') as HTMLSelectElement
const resourceSelect = document.getElementById('resourceFilter') as HTMLSelectElement
if (technicianSelect) technicianSelect.value = ''
if (resourceSelect) resourceSelect.value = ''
calendar.getEvents().forEach((event: any) => {
event.setProp('display', 'auto')
})
}
const goToToday = () => {
if (calendar) {
calendar.today()
}
}
if (loading) {
return (
<div className="container mt-4">
<div className="text-center py-5">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
<p className="mt-3">Cargando calendario...</p>
</div>
</div>
)
}
return (
<div className="container mt-4">
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center mb-3">
<i className="fas fa-calendar-alt fa-2x text-primary me-3"></i>
<div>
<h1 className="h3 mb-0">Calendario Interactivo</h1>
<p className="text-muted mb-0">Gestión de eventos y programaciones del sistema</p>
</div>
</div>
</div>
</div>
{/* Calendar Filters and Controls */}
<div className="row mb-4">
<div className="col-12">
<div className="card">
<div className="card-body">
<div className="row g-3">
<div className="col-md-3">
<select className="form-select" id="calendarView" onChange={(e) => handleViewChange(e.target.value)}>
<option value="dayGridMonth">Vista Mensual</option>
<option value="timeGridWeek">Vista Semanal</option>
<option value="timeGridDay">Vista Diaria</option>
<option value="listWeek">Lista Semanal</option>
</select>
</div>
<div className="col-md-3">
<select className="form-select" id="technicianFilter" onChange={(e) => handleTechnicianFilter(e.target.value)}>
<option value="">Todos los técnicos</option>
<option value="jgarcia">Juan García</option>
<option value="mrodriguez">María Rodríguez</option>
<option value="clopez">Carlos López</option>
<option value="amartinez">Ana Martínez</option>
<option value="rmartinez">Roberto Martínez</option>
</select>
</div>
<div className="col-md-3">
<select className="form-select" id="resourceFilter" onChange={(e) => handleResourceFilter(e.target.value)}>
<option value="">Todos los recursos</option>
<option value="auditorio">Auditorio</option>
<option value="proyector">Proyectores</option>
<option value="computadoras">Computadoras</option>
<option value="redes">Equipos de Red</option>
</select>
</div>
<div className="col-md-3">
<div className="d-flex gap-2">
<button className="btn btn-outline-primary flex-fill" onClick={goToToday}>Hoy</button>
<button className="btn btn-outline-secondary flex-fill" onClick={clearFilters}>Limpiar</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Calendar Container */}
<div className="row">
<div className="col-12">
<div className="card">
<div className="card-body">
<div id="calendar"></div>
</div>
</div>
</div>
</div>
{/* Upcoming Events Sidebar */}
<div className="row mt-4">
<div className="col-md-8">
<div className="card">
<div className="card-header">
<h5 className="mb-0">Próximos Eventos</h5>
</div>
<div className="card-body">
<div className="list-group list-group-flush">
{upcomingEvents.length > 0 ? (
upcomingEvents.map(event => (
<div key={event.id} className="list-group-item">
<div className="d-flex w-100 justify-content-between">
<h6 className="mb-1">{event.title}</h6>
<small className="text-muted">
{new Date(event.start).toLocaleString('es-AR', {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</small>
</div>
<p className="mb-1">{event.extendedProps.technicianName}</p>
<small className="text-muted">{event.extendedProps.resourceName}</small>
</div>
))
) : (
<div className="text-center text-muted py-4">
<i className="fas fa-calendar-check fa-3x mb-3"></i>
<p>No hay eventos próximos programados</p>
</div>
)}
</div>
</div>
</div>
</div>
<div className="col-md-4">
<div className="card">
<div className="card-header">
<h5 className="mb-0">Estadísticas del Mes</h5>
</div>
<div className="card-body">
<div className="row text-center">
<div className="col-6">
<div className="h4 text-primary mb-1" id="monthEvents">{stats.events}</div>
<small className="text-muted">Eventos</small>
</div>
<div className="col-6">
<div className="h4 text-success mb-1" id="monthTasks">{stats.tasks}</div>
<small className="text-muted">Tareas</small>
</div>
</div>
<hr />
<div className="row text-center">
<div className="col-6">
<div className="h4 text-info mb-1" id="activeTechnicians">{stats.activeTechnicians}</div>
<small className="text-muted">Técnicos Activos</small>
</div>
<div className="col-6">
<div className="h4 text-warning mb-1" id="busyResources">{stats.busyResources}</div>
<small className="text-muted">Recursos Ocupados</small>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Add Event Modal */}
{showEventModal && (
<div className="modal fade show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">
<i className="fas fa-plus me-2"></i>Nuevo Evento
</h5>
<button type="button" className="btn-close" onClick={() => setShowEventModal(false)}></button>
</div>
<div className="modal-body">
<form id="addEventForm">
<div className="row">
<div className="col-md-8">
<div className="mb-3">
<label className="form-label">Título del Evento *</label>
<input type="text" className="form-control" id="eventTitle" required />
</div>
</div>
<div className="col-md-4">
<div className="mb-3">
<label className="form-label">Tipo *</label>
<select className="form-select" id="eventType" required>
<option value="">Seleccionar...</option>
<option value="maintenance">Mantenimiento</option>
<option value="event">Evento Especial</option>
<option value="training">Capacitación</option>
<option value="meeting">Reunión</option>
<option value="other">Otro</option>
</select>
</div>
</div>
</div>
<div className="mb-3">
<label className="form-label">Descripción</label>
<textarea className="form-control" id="eventDescription" rows={3}></textarea>
</div>
<div className="row">
<div className="col-md-6">
<div className="mb-3">
<label className="form-label">Fecha y Hora de Inicio *</label>
<input type="datetime-local" className="form-control" id="eventStart" required />
</div>
</div>
<div className="col-md-6">
<div className="mb-3">
<label className="form-label">Fecha y Hora de Fin *</label>
<input type="datetime-local" className="form-control" id="eventEnd" required />
</div>
</div>
</div>
<div className="row">
<div className="col-md-6">
<div className="mb-3">
<label className="form-label">Técnico Asignado *</label>
<select className="form-select" id="eventTechnician" required>
<option value="">Seleccionar técnico...</option>
<option value="jgarcia">Juan García - Desarrollador</option>
<option value="mrodriguez">María Rodríguez - Analista</option>
<option value="clopez">Carlos López - Diseñador</option>
<option value="amartinez">Ana Martínez - Tester</option>
<option value="rmartinez">Roberto Martínez - Administrador</option>
</select>
</div>
</div>
<div className="col-md-6">
<div className="mb-3">
<label className="form-label">Recurso Principal</label>
<select className="form-select" id="eventResource">
<option value="">Seleccionar recurso...</option>
<option value="auditorio">Auditorio</option>
<option value="proyector">Proyector Principal</option>
<option value="computadoras">Sala de Computadoras</option>
<option value="redes">Equipos de Red</option>
</select>
</div>
</div>
</div>
</form>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={() => setShowEventModal(false)}>Cancelar</button>
<button type="button" className="btn btn-info" onClick={() => console.log('Save event')}>
<i className="fas fa-save me-2"></i>Guardar Evento
</button>
</div>
</div>
</div>
</div>
)}
{/* Event Details Modal */}
{showDetailsModal && selectedEvent && (
<div className="modal fade show d-block" style={{ backgroundColor: 'rgba(0,0,0,0.5)' }}>
<div className="modal-dialog modal-lg">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">
<i className="fas fa-info-circle me-2"></i>Detalles del Evento
</h5>
<button type="button" className="btn-close" onClick={() => setShowDetailsModal(false)}></button>
</div>
<div className="modal-body">
<div className="row">
<div className="col-md-8">
<h4>{selectedEvent.title}</h4>
<p className="text-muted">
{selectedEvent.extendedProps.type === 'maintenance' ? 'Mantenimiento' :
selectedEvent.extendedProps.type === 'event' ? 'Evento Especial' :
selectedEvent.extendedProps.type === 'training' ? 'Capacitación' :
selectedEvent.extendedProps.type === 'meeting' ? 'Reunión' : 'Evento'}
</p>
<hr />
<p><strong>Fecha y Hora:</strong> {new Date(selectedEvent.start).toLocaleString('es-AR', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})} - {new Date(selectedEvent.end).toLocaleString('es-AR', {
hour: '2-digit',
minute: '2-digit'
})}</p>
<p><strong>Técnico Asignado:</strong> {selectedEvent.extendedProps.technicianName}</p>
<p><strong>Recurso:</strong> {selectedEvent.extendedProps.resourceName}</p>
{selectedEvent.extendedProps.description && (
<p><strong>Descripción:</strong> {selectedEvent.extendedProps.description}</p>
)}
</div>
<div className="col-md-4">
<div className="card">
<div className="card-body text-center">
<i className="fas fa-clock fa-3x text-info mb-3"></i>
<h6>Próximo Recordatorio</h6>
<p className="mb-0">15 minutos antes</p>
</div>
</div>
</div>
</div>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={() => setShowDetailsModal(false)}>Cerrar</button>
<button type="button" className="btn btn-warning">
<i className="fas fa-edit me-2"></i>Editar
</button>
<button type="button" className="btn btn-danger">
<i className="fas fa-trash me-2"></i>Eliminar
</button>
</div>
</div>
</div>
</div>
)}
</div>
)
}
export default Calendario
@@ -0,0 +1,634 @@
import { useEffect, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
interface DashboardStats {
tecnicos: {
total: number
activos: number
inactivos: number
administradores: number
}
tareas: {
total: number
pendientes: number
enProgreso: number
completadas: number
canceladas: number
}
recursos: {
total: number
disponibles: number
asignados: number
mantenimiento: number
}
usuarios: {
total: number
conRecursos: number
sinRecursos: number
}
}
interface UpcomingEvent {
id: string
title: string
start: string
end: string
type: string
technician: string
technicianName: string
resource: string
resourceName: string
description: string
}
interface RecentActivity {
id: string
timestamp: string
title: string
description: string
type: string
}
const Dashboard = () => {
const { user } = useAuthStore()
const [stats, setStats] = useState<DashboardStats>({
tecnicos: { total: 0, activos: 0, inactivos: 0, administradores: 0 },
tareas: { total: 0, pendientes: 0, enProgreso: 0, completadas: 0, canceladas: 0 },
recursos: { total: 0, disponibles: 0, asignados: 0, mantenimiento: 0 },
usuarios: { total: 0, conRecursos: 0, sinRecursos: 0 }
})
const [upcomingEvents, setUpcomingEvents] = useState<UpcomingEvent[]>([])
const [recentActivity, setRecentActivity] = useState<RecentActivity[]>([])
const [currentDate, setCurrentDate] = useState('')
const [currentTime, setCurrentTime] = useState('')
const [loading, setLoading] = useState(true)
useEffect(() => {
loadDashboardData()
updateDateTime()
const timeInterval = setInterval(updateDateTime, 1000)
return () => clearInterval(timeInterval)
}, [])
const loadDashboardData = async () => {
try {
setLoading(true)
// Load data from all entities
const [tecnicosRes, tareasRes, recursosRes, usuariosRes] = await Promise.all([
fetch('/api/tecnicos'),
fetch('/api/tareas'),
fetch('/api/recursos'),
fetch('/api/usuarios_relacionados')
])
const tecnicos = tecnicosRes.ok ? await tecnicosRes.json() : []
const tareas = tareasRes.ok ? await tareasRes.json() : []
const recursos = recursosRes.ok ? await recursosRes.json() : []
const usuarios = usuariosRes.ok ? await usuariosRes.json() : []
// Calculate statistics
const tecnicosArray = Array.isArray(tecnicos) ? tecnicos : []
const tareasArray = Array.isArray(tareas) ? tareas : []
const recursosArray = Array.isArray(recursos) ? recursos : []
const usuariosArray = Array.isArray(usuarios) ? usuarios : []
const tecnicosStats = {
total: tecnicosArray.length,
activos: tecnicosArray.filter((t: any) => t.is_active).length,
inactivos: tecnicosArray.filter((t: any) => !t.is_active).length,
administradores: tecnicosArray.filter((t: any) => t.role === 'admin').length
}
const tareasStats = {
total: tareasArray.length,
pendientes: tareasArray.filter((t: any) => t.status === 'pending').length,
enProgreso: tareasArray.filter((t: any) => t.status === 'in_progress').length,
completadas: tareasArray.filter((t: any) => t.status === 'completed').length,
canceladas: tareasArray.filter((t: any) => t.status === 'cancelled').length
}
const recursosStats = {
total: recursosArray.length,
disponibles: recursosArray.filter((r: any) => r.status === 'available').length,
asignados: recursosArray.filter((r: any) => r.status === 'assigned').length,
mantenimiento: recursosArray.filter((r: any) => r.status === 'maintenance').length
}
const usuariosStats = {
total: usuariosArray.length,
conRecursos: usuariosArray.filter((u: any) => (u.assigned_resources_count || 0) > 0).length,
sinRecursos: usuariosArray.filter((u: any) => (u.assigned_resources_count || 0) === 0).length
}
setStats({
tecnicos: tecnicosStats,
tareas: tareasStats,
recursos: recursosStats,
usuarios: usuariosStats
})
// Generate mock upcoming events (in production, this would come from a dedicated events API)
const mockEvents: UpcomingEvent[] = [
{
id: '1',
title: 'Preparar los equipos en el Auditorio con música y proyector',
start: '2025-11-15T14:00:00',
end: '2025-11-15T16:00:00',
type: 'event',
technician: 'jgarcia',
technicianName: 'Juan García',
resource: 'auditorio',
resourceName: 'Auditorio',
description: 'Evento especial de capacitación técnica'
},
{
id: '2',
title: 'Mantenimiento preventivo de servidores',
start: '2025-11-16T09:00:00',
end: '2025-11-16T12:00:00',
type: 'maintenance',
technician: 'clopez',
technicianName: 'Carlos López',
resource: 'servidores',
resourceName: 'Sala de Servidores',
description: 'Mantenimiento rutinario de equipos'
},
{
id: '3',
title: 'Capacitación en ciberseguridad',
start: '2025-11-18T10:00:00',
end: '2025-11-18T12:00:00',
type: 'training',
technician: 'amartinez',
technicianName: 'Ana Martínez',
resource: 'auditorio',
resourceName: 'Auditorio',
description: 'Sesión de capacitación para todo el equipo'
}
]
setUpcomingEvents(mockEvents)
// Generate mock recent activity
const mockActivity: RecentActivity[] = [
{
id: '1',
timestamp: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
title: 'Nueva tarea completada',
description: 'Implementar API de autenticación finalizada por María Rodríguez',
type: 'task'
},
{
id: '2',
timestamp: new Date(Date.now() - 4 * 60 * 60 * 1000).toISOString(),
title: 'Recurso relacionado',
description: 'Laptop Dell Latitude 5420 relacionada con Juan García',
type: 'resource'
},
{
id: '3',
timestamp: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
title: 'Usuario registrado',
description: 'Ana Martínez se unió al sistema como Visualizador',
type: 'user'
}
]
setRecentActivity(mockActivity)
} catch (error) {
console.error('Error loading dashboard data:', error)
} finally {
setLoading(false)
}
}
const updateDateTime = () => {
const now = new Date()
// Formatear fecha en español de Argentina
const dateOptions: Intl.DateTimeFormatOptions = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
}
setCurrentDate(now.toLocaleDateString('es-AR', dateOptions))
// Formatear hora
const timeOptions: Intl.DateTimeFormatOptions = {
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
hour12: false
}
setCurrentTime(now.toLocaleTimeString('es-AR', timeOptions))
}
const getEventTypeIcon = (type: string) => {
const icons: { [key: string]: string } = {
'maintenance': 'fas fa-wrench',
'event': 'fas fa-calendar-star',
'training': 'fas fa-graduation-cap',
'meeting': 'fas fa-users'
}
return icons[type] || 'fas fa-calendar'
}
const getActivityTypeIcon = (type: string) => {
const icons: { [key: string]: string } = {
'maintenance': 'fas fa-wrench',
'task': 'fas fa-tasks',
'user': 'fas fa-user-plus',
'training': 'fas fa-graduation-cap',
'system': 'fas fa-server',
'meeting': 'fas fa-users',
'resource': 'fas fa-box'
}
return icons[type] || 'fas fa-info-circle'
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('es-AR', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
if (loading) {
return (
<div className="container mt-4">
<div className="text-center py-5">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
<p className="mt-3">Cargando dashboard...</p>
</div>
</div>
)
}
return (
<div className="container mt-4">
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center mb-3">
<i className="fas fa-chart-line fa-2x text-primary me-3"></i>
<div>
<h1 className="h3 mb-0">Dashboard</h1>
<p className="text-muted mb-0">Panel de control principal del sistema</p>
</div>
</div>
</div>
</div>
{/* Statistics Cards */}
{user && (
<div className="row mb-4">
<div className="col-md-3 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-clock text-warning me-2"></i>
Tareas Pendientes
</div>
<div className="card-body text-center">
<div className="card-text task-pending" id="pending-tasks">{stats.tareas.pendientes}</div>
<small className="text-muted">Esperando asignación</small>
</div>
</div>
</div>
<div className="col-md-3 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-play-circle text-info me-2"></i>
En Progreso
</div>
<div className="card-body text-center">
<div className="card-text task-in-progress" id="in-progress-tasks">{stats.tareas.enProgreso}</div>
<small className="text-muted">Actualmente trabajando</small>
</div>
</div>
</div>
<div className="col-md-3 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-check-circle text-success me-2"></i>
Completadas
</div>
<div className="card-body text-center">
<div className="card-text task-completed" id="completed-tasks">{stats.tareas.completadas}</div>
<small className="text-muted">Esta semana</small>
</div>
</div>
</div>
<div className="col-md-3 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-times-circle text-danger me-2"></i>
Canceladas
</div>
<div className="card-body text-center">
<div className="card-text task-cancelled" id="cancelled-tasks">{stats.tareas.canceladas}</div>
<small className="text-muted">Esta semana</small>
</div>
</div>
</div>
</div>
)}
{!user && (
<div className="row mb-4">
<div className="col-md-4 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-users text-primary me-2"></i>
Gestión de Técnicos
</div>
<div className="card-body text-center">
<div className="card-text">
<i className="fas fa-user-cog fa-2x text-primary mb-3"></i>
<p>Administra el personal técnico del DTIC</p>
</div>
</div>
</div>
</div>
<div className="col-md-4 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-tasks text-success me-2"></i>
Control de Tareas
</div>
<div className="card-body text-center">
<div className="card-text">
<i className="fas fa-clipboard-list fa-2x text-success mb-3"></i>
<p>Gestiona tareas y proyectos del departamento</p>
</div>
</div>
</div>
</div>
<div className="col-md-4 mb-3">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-boxes text-info me-2"></i>
Inventario de Recursos
</div>
<div className="card-body text-center">
<div className="card-text">
<i className="fas fa-server fa-2x text-info mb-3"></i>
<p>Controla equipos y recursos tecnológicos</p>
</div>
</div>
</div>
</div>
</div>
)}
{/* Recent Activity & Upcoming Events */}
<div className="row">
{/* Recent Tasks */}
<div className="col-md-6 mb-4">
<div className="card">
<div className="card-header">
<i className="fas fa-history me-2"></i>
Actividad Reciente
</div>
<div className="card-body">
{recentActivity.length > 0 ? (
<div className="activity-list">
{recentActivity.map(activity => (
<div key={activity.id} className="activity-item mb-3 p-2 border-start border-primary border-3">
<div className="d-flex align-items-start">
<i className={`${getActivityTypeIcon(activity.type)} me-2 mt-1`}></i>
<div className="flex-grow-1">
<small className="text-muted">{formatDate(activity.timestamp)}</small>
<div className="fw-bold">{activity.title}</div>
<small>{activity.description}</small>
</div>
</div>
</div>
))}
</div>
) : (
<div id="recent-activity" className="text-center text-muted py-4">
<i className="fas fa-inbox fa-3x mb-3"></i>
<p>No hay actividad reciente para mostrar.</p>
<small>Las actividades aparecerán aquí una vez que se implemente el backend.</small>
</div>
)}
</div>
</div>
</div>
{/* Upcoming Events */}
<div className="col-md-6 mb-4">
<div className="card">
<div className="card-header d-flex justify-content-between align-items-center">
<div>
<i className="fas fa-calendar-check me-2"></i>
Próximos Eventos
</div>
<a href="/calendario" className="btn btn-sm btn-outline-primary">
<i className="fas fa-external-link-alt"></i>
</a>
</div>
<div className="card-body">
<div id="dashboard-upcoming-events">
{upcomingEvents.length > 0 ? (
upcomingEvents.slice(0, 4).map(event => (
<div key={event.id} className="dashboard-upcoming-event mb-3 p-2 border rounded">
<div className="event-title">
<i className={`${getEventTypeIcon(event.type)} me-2`}></i>{event.title}
</div>
<div className="event-time">
{new Date(event.start).toLocaleString('es-AR', {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}
</div>
<div className="event-details">
<small><strong>{event.technicianName}</strong> • {event.resourceName}</small>
</div>
</div>
))
) : (
<div className="text-center text-muted py-3">
<i className="fas fa-calendar-alt fa-3x mb-2"></i>
<p className="mb-1">No hay eventos próximos</p>
<small>Los próximos eventos aparecerán aquí</small>
</div>
)}
</div>
</div>
</div>
</div>
</div>
{/* Quick Actions */}
{user && (
<div className="row">
<div className="col-12 mb-4">
<div className="card">
<div className="card-header">
<i className="fas fa-bolt me-2"></i>
Acciones Rápidas
</div>
<div className="card-body">
<div className="row">
<div className="col-md-3">
<div className="d-grid gap-2">
<button className="btn btn-primary" id="btn-new-task" disabled>
<i className="fas fa-plus me-2"></i>Nueva Tarea
</button>
</div>
</div>
<div className="col-md-3">
<div className="d-grid gap-2">
<button className="btn btn-success" id="btn-new-resource" disabled>
<i className="fas fa-box me-2"></i>Nuevo Recurso
</button>
</div>
</div>
<div className="col-md-3">
<div className="d-grid gap-2">
<a href="/calendario" className="btn btn-info">
<i className="fas fa-calendar-plus me-2"></i>Nuevo Evento
</a>
</div>
</div>
<div className="col-md-3">
<div className="d-grid gap-2">
<a href="/reportes" className="btn btn-warning">
<i className="fas fa-chart-bar me-2"></i>Ver Reportes
</a>
</div>
</div>
</div>
<hr />
<div className="text-center">
<small className="text-muted">
<i className="fas fa-info-circle me-1"></i>
Las acciones estarán disponibles en etapas posteriores
</small>
</div>
</div>
</div>
</div>
</div>
)}
{/* Access System */}
{!user && (
<div className="row">
<div className="col-12 mb-4">
<div className="card">
<div className="card-header">
<i className="fas fa-sign-in-alt me-2"></i>
Acceso al Sistema
</div>
<div className="card-body text-center">
<div className="row">
<div className="col-md-6">
<div className="d-grid gap-2">
<a href="/login" className="btn btn-primary btn-lg">
<i className="fas fa-sign-in-alt me-2"></i>Iniciar Sesión
</a>
<small className="text-muted">Accede a todas las funcionalidades del sistema</small>
</div>
</div>
<div className="col-md-6">
<div className="d-grid gap-2">
<a href="/test" className="btn btn-outline-secondary btn-lg">
<i className="fas fa-flask me-2"></i>Verificar Sistema
</a>
<small className="text-muted">Página de diagnóstico y pruebas</small>
</div>
</div>
</div>
<hr />
<div className="text-center">
<small className="text-muted">
<i className="fas fa-info-circle me-1"></i>
Para acceder a funciones avanzadas, inicia sesión con tus credenciales
</small>
</div>
</div>
</div>
</div>
</div>
)}
{/* System Information */}
<div className="row">
<div className="col-12">
<div className="card">
<div className="card-header">
<i className="fas fa-server me-2"></i>
Información del Sistema
</div>
<div className="card-body">
<div className="row">
<div className="col-md-3">
<div className="text-center">
<i className="fas fa-code fa-2x text-primary mb-2"></i>
<div className="h6">React + TypeScript</div>
<small className="text-muted">Framework Frontend</small>
</div>
</div>
<div className="col-md-3">
<div className="text-center">
<i className="fas fa-database fa-2x text-success mb-2"></i>
<div className="h6">Node.js + Express</div>
<small className="text-muted">Backend API</small>
</div>
</div>
<div className="col-md-3">
<div className="text-center">
<i className="fas fa-calendar-alt fa-2x text-warning mb-2"></i>
<div className="h6">Calendario</div>
<small className="text-muted">Gestión de eventos</small>
</div>
</div>
<div className="col-md-3">
<div className="text-center">
<a href="/estado-proyecto" className="text-decoration-none">
<i className="fas fa-info-circle fa-2x text-info mb-2"></i>
<div className="h6 text-info">Estado del Proyecto</div>
<small className="text-muted">Ver progreso</small>
</a>
</div>
</div>
</div>
<hr />
<div className="row">
<div className="col-12">
<div className="text-center">
<div className="mb-2">
<span className="badge bg-primary fs-6 px-3 py-2">
<i className="fas fa-tag me-1"></i>
Versión 1.2.0
</span>
</div>
<small className="text-muted">
<i className="fas fa-copyright me-1"></i>
Aplicación creada y desarrollada por Lic. Ricardo MONLA,
del Departamento de Servidores de la Dirección de TIC de la
Universidad Tecnológica Nacional – Facultad Regional La Rioja
</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Dashboard
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,31 @@
const Estadoproyecto = () => {
return (
<div className="container mt-4">
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center mb-3">
<i className="fas fa-project-diagram fa-2x text-primary me-3"></i>
<div>
<h1 className="h3 mb-0">Estado del Proyecto</h1>
<p className="text-muted mb-0">Monitorea el estado general de los proyectos</p>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div className="card">
<div className="card-body text-center py-5">
<h3>Módulo de Estado del Proyecto</h3>
<p className="text-muted">Funcionalidad en desarrollo</p>
</div>
</div>
</div>
</div>
</div>
)
}
export default Estadoproyecto
@@ -0,0 +1,139 @@
import { useState, useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import { useForm } from 'react-hook-form'
import { yupResolver } from '@hookform/resolvers/yup'
import * as yup from 'yup'
import toast from 'react-hot-toast'
import { useAuthStore } from '../stores/authStore'
const schema = yup.object({
email: yup.string().email('Email inválido').required('Email es requerido'),
password: yup.string().required('Contraseña es requerida'),
})
type LoginForm = {
email: string
password: string
}
const Login = () => {
const navigate = useNavigate()
const location = useLocation()
const { login, isAuthenticated, isLoading } = useAuthStore()
const [showPassword, setShowPassword] = useState(false)
const {
register,
handleSubmit,
formState: { errors },
} = useForm<LoginForm>({
resolver: yupResolver(schema),
})
useEffect(() => {
if (isAuthenticated) {
const from = location.state?.from?.pathname || '/dashboard'
navigate(from, { replace: true })
}
}, [isAuthenticated, navigate, location])
const onSubmit = async (data: LoginForm) => {
try {
await login(data.email, data.password)
toast.success('Inicio de sesión exitoso')
} catch (error) {
toast.error(error instanceof Error ? error.message : 'Error en el inicio de sesión')
}
}
return (
<div className="min-vh-100 d-flex align-items-center justify-content-center bg-gradient">
<div className="container">
<div className="row justify-content-center">
<div className="col-md-6 col-lg-4">
<div className="card shadow-lg border-0 rounded-lg">
<div className="card-header bg-primary text-white text-center py-4">
<h3 className="mb-0">
<i className="fas fa-cogs me-2"></i>
DTIC Bitácoras
</h3>
<p className="mb-0 mt-2">Sistema de gestión de técnicos</p>
</div>
<div className="card-body p-4">
<form onSubmit={handleSubmit(onSubmit)}>
<div className="mb-3">
<label htmlFor="email" className="form-label">
<i className="fas fa-envelope me-2"></i>
Email
</label>
<input
type="email"
className={`form-control ${errors.email ? 'is-invalid' : ''}`}
id="email"
{...register('email')}
placeholder="tu.email@dtic.gob.ar"
/>
{errors.email && (
<div className="invalid-feedback">{errors.email.message}</div>
)}
</div>
<div className="mb-4">
<label htmlFor="password" className="form-label">
<i className="fas fa-lock me-2"></i>
Contraseña
</label>
<div className="input-group">
<input
type={showPassword ? 'text' : 'password'}
className={`form-control ${errors.password ? 'is-invalid' : ''}`}
id="password"
{...register('password')}
placeholder="Ingresa tu contraseña"
/>
<button
className="btn btn-outline-secondary"
type="button"
onClick={() => setShowPassword(!showPassword)}
>
<i className={`fas ${showPassword ? 'fa-eye-slash' : 'fa-eye'}`}></i>
</button>
{errors.password && (
<div className="invalid-feedback">{errors.password.message}</div>
)}
</div>
</div>
<button
type="submit"
className="btn btn-primary w-100 py-2"
disabled={isLoading}
>
{isLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2" role="status"></span>
Iniciando sesión...
</>
) : (
<>
<i className="fas fa-sign-in-alt me-2"></i>
Iniciar Sesión
</>
)}
</button>
</form>
</div>
<div className="card-footer text-center py-3">
<small className="text-muted">
Sistema de gestión de recursos y tareas - DTIC
</small>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Login
@@ -0,0 +1,658 @@
import { useEffect, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
interface ReportData {
tasks: {
total: number
completed: number
pending: number
inProgress: number
cancelled: number
completionRate: number
averageTime: number
}
resources: {
total: number
available: number
assigned: number
maintenance: number
retired: number
utilizationRate: number
}
users: {
total: number
withResources: number
withoutResources: number
totalAssignedResources: number
}
technicians: {
total: number
active: number
inactive: number
admins: number
}
}
interface ChartData {
labels: string[]
datasets: Array<{
label: string
data: number[]
backgroundColor: string[]
borderColor?: string
borderWidth?: number
}>
}
const Reportes = () => {
const { user } = useAuthStore()
const [reportData, setReportData] = useState<ReportData>({
tasks: { total: 0, completed: 0, pending: 0, inProgress: 0, cancelled: 0, completionRate: 0, averageTime: 0 },
resources: { total: 0, available: 0, assigned: 0, maintenance: 0, retired: 0, utilizationRate: 0 },
users: { total: 0, withResources: 0, withoutResources: 0, totalAssignedResources: 0 },
technicians: { total: 0, active: 0, inactive: 0, admins: 0 }
})
const [tasksChart, setTasksChart] = useState<ChartData | null>(null)
const [productivityChart, setProductivityChart] = useState<ChartData | null>(null)
const [resourcesChart, setResourcesChart] = useState<ChartData | null>(null)
const [reportType, setReportType] = useState('tasks')
const [reportPeriod, setReportPeriod] = useState('month')
const [dateFrom, setDateFrom] = useState('')
const [dateTo, setDateTo] = useState('')
const [loading, setLoading] = useState(true)
const [generating, setGenerating] = useState(false)
useEffect(() => {
loadReportData()
setDefaultDates()
}, [])
useEffect(() => {
if (!loading) {
initializeCharts()
}
}, [loading, reportData])
const loadReportData = async () => {
try {
setLoading(true)
// Load data from all entities
const [tecnicosRes, tareasRes, recursosRes, usuariosRes] = await Promise.all([
fetch('/api/tecnicos'),
fetch('/api/tareas'),
fetch('/api/recursos'),
fetch('/api/usuarios_relacionados')
])
const tecnicos = tecnicosRes.ok ? await tecnicosRes.json() : []
const tareas = tareasRes.ok ? await tareasRes.json() : []
const recursos = recursosRes.ok ? await recursosRes.json() : []
const usuarios = usuariosRes.ok ? await usuariosRes.json() : []
// Calculate report data
const tareasArray = Array.isArray(tareas) ? tareas : []
const recursosArray = Array.isArray(recursos) ? recursos : []
const usuariosArray = Array.isArray(usuarios) ? usuarios : []
const tecnicosArray = Array.isArray(tecnicos) ? tecnicos : []
const tasksData = {
total: tareasArray.length,
completed: tareasArray.filter((t: any) => t.status === 'completed').length,
pending: tareasArray.filter((t: any) => t.status === 'pending').length,
inProgress: tareasArray.filter((t: any) => t.status === 'in_progress').length,
cancelled: tareasArray.filter((t: any) => t.status === 'cancelled').length,
completionRate: tareasArray.length > 0 ? Math.round((tareasArray.filter((t: any) => t.status === 'completed').length / tareasArray.length) * 100) : 0,
averageTime: 3.2 // Mock data
}
const resourcesData = {
total: recursosArray.length,
available: recursosArray.filter((r: any) => r.status === 'available').length,
assigned: recursosArray.filter((r: any) => r.status === 'assigned').length,
maintenance: recursosArray.filter((r: any) => r.status === 'maintenance').length,
retired: recursosArray.filter((r: any) => r.status === 'retired').length,
utilizationRate: recursosArray.length > 0 ? Math.round((recursosArray.filter((r: any) => r.status === 'assigned').length / recursosArray.length) * 100) : 0
}
const usersData = {
total: usuariosArray.length,
withResources: usuariosArray.filter((u: any) => (u.assigned_resources_count || 0) > 0).length,
withoutResources: usuariosArray.filter((u: any) => (u.assigned_resources_count || 0) === 0).length,
totalAssignedResources: usuariosArray.reduce((total: number, u: any) => total + (u.assigned_resources_count || 0), 0)
}
const techniciansData = {
total: tecnicosArray.length,
active: tecnicosArray.filter((t: any) => t.is_active).length,
inactive: tecnicosArray.filter((t: any) => !t.is_active).length,
admins: tecnicosArray.filter((t: any) => t.role === 'admin').length
}
setReportData({
tasks: tasksData,
resources: resourcesData,
users: usersData,
technicians: techniciansData
})
} catch (error) {
console.error('Error loading report data:', error)
} finally {
setLoading(false)
}
}
const initializeCharts = () => {
// Load Chart.js dynamically
const script = document.createElement('script')
script.src = 'https://cdn.jsdelivr.net/npm/chart.js'
script.onload = () => {
setTimeout(() => {
// Destroy existing charts to prevent "Canvas is already in use" error
const tasksCtx = document.getElementById('tasksChart') as HTMLCanvasElement
const resourcesCtx = document.getElementById('resourcesChart') as HTMLCanvasElement
// Destroy existing chart instances if they exist
if ((window as any).tasksChartInstance) {
(window as any).tasksChartInstance.destroy()
}
if ((window as any).resourcesChartInstance) {
(window as any).resourcesChartInstance.destroy()
}
// Tasks Status Chart
if (tasksCtx) {
(window as any).tasksChartInstance = new (window as any).Chart(tasksCtx, {
type: 'doughnut',
data: {
labels: ['Pendientes', 'En Progreso', 'Completadas', 'Canceladas'],
datasets: [{
data: [reportData.tasks.pending, reportData.tasks.inProgress, reportData.tasks.completed, reportData.tasks.cancelled],
backgroundColor: [
'#ffc107', // warning
'#17a2b8', // info
'#28a745', // success
'#dc3545' // danger
],
borderWidth: 2
}]
},
options: {
responsive: true,
plugins: {
legend: {
position: 'bottom'
}
}
}
})
}
// Resources Chart
if (resourcesCtx) {
(window as any).resourcesChartInstance = new (window as any).Chart(resourcesCtx, {
type: 'bar',
data: {
labels: ['Hardware', 'Software', 'Redes', 'Herramientas'],
datasets: [{
label: 'Total',
data: [15, 12, 8, 13],
backgroundColor: '#28a745',
borderWidth: 1
}, {
label: 'Relacionados',
data: [8, 5, 4, 3],
backgroundColor: '#17a2b8',
borderWidth: 1
}]
},
options: {
responsive: true,
scales: {
y: {
beginAtZero: true
}
}
}
})
}
}, 1000) // Wait for script to load
}
script.onerror = () => {
console.error('Failed to load Chart.js script')
}
document.head.appendChild(script)
}
const setDefaultDates = () => {
const today = new Date()
const monthAgo = new Date()
monthAgo.setMonth(today.getMonth() - 1)
setDateTo(today.toISOString().split('T')[0])
setDateFrom(monthAgo.toISOString().split('T')[0])
}
const generateReport = async () => {
setGenerating(true)
// Simulate report generation
setTimeout(() => {
setGenerating(false)
showNotification('✅ Reporte generado exitosamente', 'success')
}, 2000)
}
const resetFilters = () => {
setReportType('tasks')
setReportPeriod('month')
setDefaultDates()
showNotification('🔄 Filtros restablecidos', 'info')
}
const exportReport = (format: string) => {
showNotification(`📄 Función de exportación ${format.toUpperCase()} disponible en Etapa 3`, 'warning')
}
const printReport = () => {
showNotification('🖨️ Función de impresión disponible en Etapa 3', 'warning')
}
const showNotification = (message: string, type: string = 'info') => {
// Create notification element
const notification = document.createElement('div')
notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`
notification.style.cssText = `
top: 20px;
right: 20px;
z-index: 9999;
min-width: 300px;
box-shadow: 0 4px 15px rgba(0,0,0,0.2);
`
notification.innerHTML = `
${message}
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
`
document.body.appendChild(notification)
setTimeout(() => {
if (notification.parentNode) {
notification.remove()
}
}, 5000)
}
useEffect(() => {
if (!loading) {
initializeCharts()
}
}, [loading, reportData])
if (loading) {
return (
<div className="container mt-4">
<div className="text-center py-5">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
<p className="mt-3">Cargando reportes...</p>
</div>
</div>
)
}
return (
<div className="container mt-4">
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center mb-3">
<i className="fas fa-chart-bar fa-2x text-primary me-3"></i>
<div>
<h1 className="h3 mb-0">Reportes y Estadísticas</h1>
<p className="text-muted mb-0">Análisis y métricas del sistema</p>
</div>
</div>
</div>
</div>
{/* Report Filters */}
<div className="row mb-4">
<div className="col-12">
<div className="card">
<div className="card-body">
<div className="row g-3">
<div className="col-md-3">
<label className="form-label">Tipo de Reporte</label>
<select
className="form-select"
value={reportType}
onChange={(e) => setReportType(e.target.value)}
>
<option value="tasks">Tareas</option>
<option value="resources">Recursos</option>
<option value="users">Usuarios</option>
<option value="system">Sistema</option>
</select>
</div>
<div className="col-md-3">
<label className="form-label">Período</label>
<select
className="form-select"
value={reportPeriod}
onChange={(e) => setReportPeriod(e.target.value)}
>
<option value="today">Hoy</option>
<option value="week">Esta semana</option>
<option value="month">Este mes</option>
<option value="quarter">Este trimestre</option>
<option value="year">Este año</option>
</select>
</div>
<div className="col-md-3">
<label className="form-label">Fecha Desde</label>
<input
type="date"
className="form-control"
value={dateFrom}
onChange={(e) => setDateFrom(e.target.value)}
/>
</div>
<div className="col-md-3">
<label className="form-label">Fecha Hasta</label>
<input
type="date"
className="form-control"
value={dateTo}
onChange={(e) => setDateTo(e.target.value)}
/>
</div>
</div>
<div className="row mt-3">
<div className="col-12">
<button
className="btn btn-primary me-2"
onClick={generateReport}
disabled={generating}
>
<i className="fas fa-chart-line me-2"></i>
{generating ? 'Generando...' : 'Generar Reporte'}
</button>
<button className="btn btn-outline-secondary" onClick={resetFilters}>
<i className="fas fa-times me-1"></i>Limpiar Filtros
</button>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Charts Section */}
<div className="row mb-4">
<div className="col-md-6 mb-4">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-chart-pie me-2"></i>
Estado de Tareas
</div>
<div className="card-body">
<div className="chart-container">
<canvas id="tasksChart" width="400" height="300"></canvas>
</div>
<div className="row text-center mt-3">
<div className="col-3">
<div className="text-warning">
<div className="h5 mb-0" id="chartPending">{reportData.tasks.pending}</div>
<small>Pendientes</small>
</div>
</div>
<div className="col-3">
<div className="text-info">
<div className="h5 mb-0" id="chartInProgress">{reportData.tasks.inProgress}</div>
<small>En Progreso</small>
</div>
</div>
<div className="col-3">
<div className="text-success">
<div className="h5 mb-0" id="chartCompleted">{reportData.tasks.completed}</div>
<small>Completadas</small>
</div>
</div>
<div className="col-3">
<div className="text-danger">
<div className="h5 mb-0" id="chartCancelled">{reportData.tasks.cancelled}</div>
<small>Canceladas</small>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="col-md-6 mb-4">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-chart-bar me-2"></i>
Recursos por Categoría
</div>
<div className="card-body">
<div className="chart-container">
<canvas id="resourcesChart" width="400" height="300"></canvas>
</div>
<div className="text-center mt-3">
<small className="text-muted">Distribución de recursos por categoría</small>
</div>
</div>
</div>
</div>
</div>
{/* Detailed Reports */}
<div className="row">
{/* Tasks Report */}
<div className="col-md-6 mb-4">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-tasks me-2"></i>
Reporte de Tareas
</div>
<div className="card-body">
<div className="table-responsive">
<table className="table table-sm">
<thead>
<tr>
<th>Métrica</th>
<th>Valor</th>
<th>Cambio</th>
</tr>
</thead>
<tbody>
<tr>
<td>Total de Tareas</td>
<td><strong>{reportData.tasks.total}</strong></td>
<td><span className="badge bg-success">+12%</span></td>
</tr>
<tr>
<td>Tareas Completadas</td>
<td><strong>{reportData.tasks.completed}</strong></td>
<td><span className="badge bg-success">+8%</span></td>
</tr>
<tr>
<td>Tiempo Promedio</td>
<td><strong>{reportData.tasks.averageTime} días</strong></td>
<td><span className="badge bg-warning">-5%</span></td>
</tr>
<tr>
<td>Tasa de Éxito</td>
<td><strong>{reportData.tasks.completionRate}%</strong></td>
<td><span className="badge bg-success">+3%</span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
{/* Resources Report */}
<div className="col-md-6 mb-4">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-boxes me-2"></i>
Reporte de Recursos
</div>
<div className="card-body">
<div className="table-responsive">
<table className="table table-sm">
<thead>
<tr>
<th>Categoría</th>
<th>Total</th>
<th>Relacionados</th>
<th>Disponibles</th>
</tr>
</thead>
<tbody>
<tr>
<td>Hardware</td>
<td><strong>15</strong></td>
<td><strong>8</strong></td>
<td><strong>7</strong></td>
</tr>
<tr>
<td>Software</td>
<td><strong>12</strong></td>
<td><strong>5</strong></td>
<td><strong>7</strong></td>
</tr>
<tr>
<td>Redes</td>
<td><strong>8</strong></td>
<td><strong>4</strong></td>
<td><strong>4</strong></td>
</tr>
<tr>
<td>Herramientas</td>
<td><strong>13</strong></td>
<td><strong>3</strong></td>
<td><strong>10</strong></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
{/* Recent Activity Report */}
<div className="row mb-4">
<div className="col-12">
<div className="card">
<div className="card-header">
<i className="fas fa-history me-2"></i>
Actividad Reciente del Sistema
</div>
<div className="card-body">
<div className="timeline">
<div className="timeline-item">
<div className="timeline-marker bg-success"></div>
<div className="timeline-content">
<h6 className="text-success mb-1">Nueva tarea completada</h6>
<p className="mb-1">"Implementar API de autenticación" finalizada por María Rodríguez</p>
<small className="text-muted">Hace 2 horas</small>
</div>
</div>
<div className="timeline-item">
<div className="timeline-marker bg-info"></div>
<div className="timeline-content">
<h6 className="text-info mb-1">Recurso relacionado</h6>
<p className="mb-1">Laptop Dell Latitude 5420 relacionada con Juan García</p>
<small className="text-muted">Hace 4 horas</small>
</div>
</div>
<div className="timeline-item">
<div className="timeline-marker bg-warning"></div>
<div className="timeline-content">
<h6 className="text-warning mb-1">Nuevo usuario registrado</h6>
<p className="mb-1">Ana Martínez se unió al sistema como Visualizador</p>
<small className="text-muted">Hace 1 día</small>
</div>
</div>
<div className="timeline-item">
<div className="timeline-marker bg-danger"></div>
<div className="timeline-content">
<h6 className="text-danger mb-1">Tarea cancelada</h6>
<p className="mb-1">"Migrar base de datos legacy" fue cancelada por falta de requerimientos</p>
<small className="text-muted">Hace 2 días</small>
</div>
</div>
<div className="timeline-item">
<div className="timeline-marker bg-primary"></div>
<div className="timeline-content">
<h6 className="text-primary mb-1">Mantenimiento completado</h6>
<p className="mb-1">Router Cisco RV340 reparado y devuelto a servicio</p>
<small className="text-muted">Hace 3 días</small>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{/* Export Options */}
<div className="row">
<div className="col-12">
<div className="card">
<div className="card-header">
<i className="fas fa-file-export me-2"></i>
Opciones de Exportación
</div>
<div className="card-body">
<div className="row">
<div className="col-md-3 mb-3">
<button className="btn btn-success w-100" onClick={() => exportReport('pdf')}>
<i className="fas fa-file-pdf fa-2x mb-2"></i>
<br />
Exportar PDF
</button>
</div>
<div className="col-md-3 mb-3">
<button className="btn btn-info w-100" onClick={() => exportReport('excel')}>
<i className="fas fa-file-excel fa-2x mb-2"></i>
<br />
Exportar Excel
</button>
</div>
<div className="col-md-3 mb-3">
<button className="btn btn-warning w-100" onClick={() => exportReport('csv')}>
<i className="fas fa-file-csv fa-2x mb-2"></i>
<br />
Exportar CSV
</button>
</div>
<div className="col-md-3 mb-3">
<button className="btn btn-secondary w-100" onClick={() => exportReport('json')}>
<i className="fas fa-file-code fa-2x mb-2"></i>
<br />
Exportar JSON
</button>
</div>
</div>
<div className="alert alert-info">
<i className="fas fa-info-circle me-2"></i>
<strong>Nota:</strong> Las funciones de exportación estarán disponibles cuando se implemente el backend en la Etapa 3.
</div>
</div>
</div>
</div>
</div>
</div>
)
}
export default Reportes
@@ -0,0 +1,722 @@
import { useEffect, useState } from 'react'
import { useAuthStore } from '../stores/authStore'
import toast from 'react-hot-toast'
// CSS para estética mejorada de tablas (consistente con EntityPage.tsx)
const styles = `
/* Estética mejorada para tablas */
.entity-table {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 10px rgba(0,0,0,0.08);
}
.entity-table thead th {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
font-weight: 600;
text-transform: uppercase;
font-size: 0.85rem;
letter-spacing: 0.5px;
border: none;
padding: 1rem 0.75rem;
position: sticky;
top: 0;
z-index: 10;
}
.entity-table tbody tr {
transition: all 0.2s ease;
border-bottom: 1px solid #f1f3f4;
}
.entity-table tbody tr:hover {
background-color: #f8f9ff;
transform: translateY(-1px);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
.entity-table tbody tr:nth-child(even) {
background-color: #fafbfc;
}
.entity-table tbody tr:nth-child(even):hover {
background-color: #f0f2ff;
}
.entity-table tbody td {
padding: 0.875rem 0.75rem;
vertical-align: middle;
border: none;
}
/* Estilos para badges en celdas */
.entity-table .badge {
font-size: 0.75rem;
padding: 0.375rem 0.5rem;
border-radius: 20px;
font-weight: 500;
}
/* Responsive improvements */
@media (max-width: 768px) {
.entity-table {
font-size: 0.875rem;
}
.entity-table thead th,
.entity-table tbody td {
padding: 0.5rem 0.375rem;
}
}
/* Dark theme overrides for entity tables */
.dark-theme .entity-table {
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
}
.dark-theme .entity-table thead th {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.dark-theme .entity-table tbody tr {
border-bottom-color: #555555;
}
.dark-theme .entity-table tbody tr:hover {
background-color: #4a4a4a;
}
.dark-theme .entity-table tbody tr:nth-child(even) {
background-color: #2d2d2d;
}
.dark-theme .entity-table tbody tr:nth-child(even):hover {
background-color: #404040;
}
.dark-theme .entity-table tbody td {
color: #ffffff;
}
`
// Inyectar estilos
if (typeof document !== 'undefined') {
const styleSheet = document.createElement('style')
styleSheet.textContent = styles
document.head.appendChild(styleSheet)
}
interface BackupFile {
filename: string
size: number
created_at: string
modified_at: string
}
const Sistema = () => {
const { user, token } = useAuthStore()
const [backups, setBackups] = useState<BackupFile[]>([])
const [loading, setLoading] = useState(true)
const [backupLoading, setBackupLoading] = useState(false)
const [restoreLoading, setRestoreLoading] = useState(false)
const [deleteLoading, setDeleteLoading] = useState<string | null>(null)
const [downloadLoading, setDownloadLoading] = useState<string | null>(null)
const [selectedBackup, setSelectedBackup] = useState<string>('')
const [showRestoreConfirm, setShowRestoreConfirm] = useState(false)
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)
const [backupToDelete, setBackupToDelete] = useState<string>('')
// Check if user is admin
if (!user || user.role !== 'admin') {
return (
<div className="container mt-4">
<div className="row justify-content-center">
<div className="col-md-6">
<div className="card border-danger">
<div className="card-body text-center">
<i className="fas fa-shield-alt fa-3x text-danger mb-3"></i>
<h4 className="card-title text-danger">Acceso Denegado</h4>
<p className="card-text">
Solo los administradores pueden acceder a esta sección del sistema.
</p>
<p className="text-muted">
Si crees que deberías tener acceso, contacta al administrador del sistema.
</p>
</div>
</div>
</div>
</div>
</div>
)
}
useEffect(() => {
loadBackups()
}, [])
const loadBackups = async () => {
try {
setLoading(true)
console.log('Sistema loadBackups: user:', user, 'token:', !!token)
const response = await fetch('/api/system/backups', {
headers: {
'Authorization': `Bearer ${token}`,
},
})
console.log('Backups response status:', response.status)
console.log('Backups response ok:', response.ok)
if (!response.ok) {
const errorText = await response.text()
console.error('Backups response error text:', errorText)
throw new Error(`HTTP ${response.status}: ${errorText}`)
}
const data = await response.json()
console.log('Backups response data:', data)
if (data.success) {
setBackups(data.data.backups)
} else {
throw new Error(data.message || 'Error al cargar los backups')
}
} catch (error) {
console.error('Error loading backups:', error)
toast.error('Error al cargar la lista de backups')
} finally {
setLoading(false)
}
}
const handleCreateBackup = async () => {
try {
setBackupLoading(true)
console.log('handleCreateBackup: Starting backup creation')
// Create AbortController for timeout
const controller = new AbortController()
const timeoutId = setTimeout(() => controller.abort(), 60000) // 60 second timeout for backup operations
const response = await fetch('/api/system/backup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
signal: controller.signal,
})
clearTimeout(timeoutId)
console.log('handleCreateBackup: Response status:', response.status)
console.log('handleCreateBackup: Response ok:', response.ok)
if (!response.ok) {
const errorText = await response.text()
console.error('handleCreateBackup: Response error text:', errorText)
throw new Error(`HTTP ${response.status}: ${errorText}`)
}
const data = await response.json()
console.log('handleCreateBackup: Response data:', data)
if (data.success) {
toast.success('Backup creado exitosamente')
// Reload backups list
await loadBackups()
} else {
throw new Error(data.message || 'Error al crear el backup')
}
} catch (error) {
console.error('Error creating backup:', error)
if (error instanceof Error && error.name === 'AbortError') {
toast.error('Timeout: La creación del backup tomó demasiado tiempo')
} else {
toast.error('Error al crear el backup')
}
} finally {
setBackupLoading(false)
}
}
const handleRestoreBackup = async () => {
if (!selectedBackup) {
toast.error('Selecciona un backup para restaurar')
return
}
try {
setRestoreLoading(true)
const response = await fetch('/api/system/restore', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({ backup_file: selectedBackup }),
})
const data = await response.json()
if (data.success) {
toast.success('Base de datos restaurada exitosamente')
setShowRestoreConfirm(false)
setSelectedBackup('')
} else {
throw new Error(data.message || 'Error al restaurar el backup')
}
} catch (error) {
console.error('Error restoring backup:', error)
toast.error('Error al restaurar el backup')
} finally {
setRestoreLoading(false)
}
}
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
const k = 1024
const sizes = ['Bytes', 'KB', 'MB', 'GB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleString('es-AR', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
const confirmRestore = () => {
if (!selectedBackup) {
toast.error('Selecciona un backup para restaurar')
return
}
setShowRestoreConfirm(true)
}
const handleDownloadBackup = async (filename: string) => {
try {
setDownloadLoading(filename)
console.log('handleDownloadBackup: Starting download for', filename)
const response = await fetch(`/api/system/backups/${filename}/download`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`,
},
})
if (!response.ok) {
const errorText = await response.text()
console.error('handleDownloadBackup: Response error text:', errorText)
throw new Error(`HTTP ${response.status}: ${errorText}`)
}
// Create a blob from the response
const blob = await response.blob()
// Create a download link and trigger the download
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
toast.success(`Backup ${filename} descargado exitosamente`)
} catch (error) {
console.error('Error downloading backup:', error)
toast.error('Error al descargar el backup')
} finally {
setDownloadLoading(null)
}
}
const handleDeleteBackup = async () => {
if (!backupToDelete) {
toast.error('No se seleccionó ningún backup para eliminar')
return
}
try {
setDeleteLoading(backupToDelete)
console.log('handleDeleteBackup: Starting deletion for', backupToDelete)
const response = await fetch(`/api/system/backups/${backupToDelete}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
},
})
if (!response.ok) {
const errorText = await response.text()
console.error('handleDeleteBackup: Response error text:', errorText)
throw new Error(`HTTP ${response.status}: ${errorText}`)
}
const data = await response.json()
console.log('handleDeleteBackup: Response data:', data)
if (data.success) {
toast.success('Backup eliminado exitosamente')
setShowDeleteConfirm(false)
setBackupToDelete('')
// Reload backups list
await loadBackups()
} else {
throw new Error(data.message || 'Error al eliminar el backup')
}
} catch (error) {
console.error('Error deleting backup:', error)
toast.error('Error al eliminar el backup')
} finally {
setDeleteLoading(null)
}
}
const confirmDelete = (filename: string) => {
setBackupToDelete(filename)
setShowDeleteConfirm(true)
}
if (loading) {
return (
<div className="container mt-4">
<div className="text-center py-5">
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Cargando...</span>
</div>
<p className="mt-3">Cargando sistema...</p>
</div>
</div>
)
}
return (
<div className="container mt-4">
{/* Header */}
<div className="row mb-4">
<div className="col-12">
<div className="d-flex align-items-center justify-content-between mb-3">
<div className="d-flex align-items-center">
<i className="fas fa-server fa-2x text-primary me-3"></i>
<div>
<h1 className="h3 mb-0">Sistema - Backup y Restauración</h1>
<p className="text-muted mb-0">Gestión de backups de la base de datos</p>
</div>
</div>
<div className="text-end">
<span className="badge bg-primary fs-6">v2.1.2</span>
<p className="text-muted small mb-0 mt-1">Versión del Sistema</p>
</div>
</div>
</div>
</div>
{/* Backup Section */}
<div className="row mb-4">
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-save text-success me-2"></i>
Crear Backup
</div>
<div className="card-body text-center">
<i className="fas fa-database fa-3x text-success mb-3"></i>
<p className="card-text mb-4">
Crea un backup completo de la base de datos del sistema.
Los backups se almacenan automáticamente en el servidor.
</p>
<button
className="btn btn-success btn-lg"
onClick={handleCreateBackup}
disabled={backupLoading}
>
{backupLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2" role="status"></span>
Creando Backup... (puede tomar hasta 1 minuto)
</>
) : (
<>
<i className="fas fa-save me-2"></i>
Crear Backup
</>
)}
</button>
</div>
</div>
</div>
{/* Restore Section */}
<div className="col-md-6">
<div className="card h-100">
<div className="card-header">
<i className="fas fa-undo text-warning me-2"></i>
Restaurar Backup
</div>
<div className="card-body text-center">
<i className="fas fa-history fa-3x text-warning mb-3"></i>
<p className="card-text mb-4">
Restaura la base de datos desde un backup anterior.
Esta acción sobrescribirá todos los datos actuales.
</p>
<div className="mb-3">
<select
className="form-select"
value={selectedBackup}
onChange={(e) => setSelectedBackup(e.target.value)}
>
<option value="">Seleccionar backup...</option>
{backups.map((backup) => (
<option key={backup.filename} value={backup.filename}>
{backup.filename} - {formatDate(backup.created_at)}
</option>
))}
</select>
</div>
<button
className="btn btn-warning btn-lg"
onClick={confirmRestore}
disabled={!selectedBackup || restoreLoading}
>
{restoreLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2" role="status"></span>
Restaurando...
</>
) : (
<>
<i className="fas fa-undo me-2"></i>
Restaurar Backup
</>
)}
</button>
</div>
</div>
</div>
</div>
{/* Backup History */}
<div className="row">
<div className="col-12">
<div className="card">
<div className="card-header d-flex justify-content-between align-items-center">
<div>
<i className="fas fa-list text-info me-2"></i>
Historial de Backups
</div>
<button
className="btn btn-sm btn-outline-primary"
onClick={loadBackups}
disabled={loading}
>
<i className="fas fa-sync me-1"></i>
Actualizar
</button>
</div>
<div className="card-body">
{backups.length > 0 ? (
<div className="table-responsive">
<table className="table entity-table">
<thead>
<tr>
<th>Archivo</th>
<th>Tamaño</th>
<th>Fecha de Creación</th>
<th>Última Modificación</th>
<th>Acciones</th>
</tr>
</thead>
<tbody>
{backups.map((backup) => (
<tr key={backup.filename}>
<td>
<i className="fas fa-file-archive text-secondary me-2"></i>
{backup.filename}
</td>
<td>{formatFileSize(backup.size)}</td>
<td>{formatDate(backup.created_at)}</td>
<td>{formatDate(backup.modified_at)}</td>
<td>
<div className="btn-group btn-group-sm" role="group">
<button
className="btn btn-outline-primary btn-sm"
onClick={() => handleDownloadBackup(backup.filename)}
disabled={downloadLoading === backup.filename}
title="Descargar backup"
>
{downloadLoading === backup.filename ? (
<span className="spinner-border spinner-border-sm" role="status"></span>
) : (
<i className="fas fa-download"></i>
)}
</button>
<button
className="btn btn-outline-danger btn-sm"
onClick={() => confirmDelete(backup.filename)}
disabled={deleteLoading === backup.filename}
title="Eliminar backup"
>
{deleteLoading === backup.filename ? (
<span className="spinner-border spinner-border-sm" role="status"></span>
) : (
<i className="fas fa-trash"></i>
)}
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="text-center py-4">
<i className="fas fa-inbox fa-3x text-muted mb-3"></i>
<p className="text-muted">No hay backups disponibles</p>
<small className="text-muted">
Los backups aparecerán aquí una vez que se creen
</small>
</div>
)}
</div>
</div>
</div>
</div>
{/* Restore Confirmation Modal */}
{showRestoreConfirm && (
<div className="modal show d-block" tabIndex={-1}>
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">
<i className="fas fa-exclamation-triangle text-warning me-2"></i>
Confirmar Restauración
</h5>
<button
type="button"
className="btn-close"
onClick={() => setShowRestoreConfirm(false)}
></button>
</div>
<div className="modal-body">
<div className="alert alert-warning">
<i className="fas fa-exclamation-triangle me-2"></i>
<strong>Advertencia:</strong> Esta acción restaurará la base de datos
desde el backup seleccionado. Todos los datos actuales serán sobrescritos
y se perderán los cambios realizados después de la fecha del backup.
</div>
<p>¿Estás seguro de que deseas continuar?</p>
<div className="text-muted small">
<strong>Backup seleccionado:</strong> {selectedBackup}
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={() => setShowRestoreConfirm(false)}
>
Cancelar
</button>
<button
type="button"
className="btn btn-warning"
onClick={handleRestoreBackup}
disabled={restoreLoading}
>
{restoreLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2"></span>
Restaurando...
</>
) : (
'Confirmar Restauración'
)}
</button>
</div>
</div>
</div>
</div>
)}
{/* Delete Confirmation Modal */}
{showDeleteConfirm && (
<div className="modal show d-block" tabIndex={-1}>
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">
<i className="fas fa-exclamation-triangle text-danger me-2"></i>
Confirmar Eliminación
</h5>
<button
type="button"
className="btn-close"
onClick={() => setShowDeleteConfirm(false)}
></button>
</div>
<div className="modal-body">
<div className="alert alert-danger">
<i className="fas fa-exclamation-triangle me-2"></i>
<strong>Advertencia:</strong> Esta acción eliminará permanentemente el archivo de backup.
Una vez eliminado, no podrá ser recuperado.
</div>
<p>¿Estás seguro de que deseas eliminar este backup?</p>
<div className="text-muted small">
<strong>Archivo a eliminar:</strong> {backupToDelete}
</div>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-secondary"
onClick={() => setShowDeleteConfirm(false)}
>
Cancelar
</button>
<button
type="button"
className="btn btn-danger"
onClick={handleDeleteBackup}
disabled={deleteLoading !== null}
>
{deleteLoading ? (
<>
<span className="spinner-border spinner-border-sm me-2"></span>
Eliminando...
</>
) : (
'Confirmar Eliminación'
)}
</button>
</div>
</div>
</div>
</div>
)}
{/* Modal Backdrop */}
{(showRestoreConfirm || showDeleteConfirm) && (
<div className="modal-backdrop show"></div>
)}
</div>
)
}
export default Sistema
@@ -0,0 +1,135 @@
import { create } from 'zustand'
import { persist } from 'zustand/middleware'
interface User {
id: number
dtic_id: string
first_name: string
last_name: string
email: string
role: 'admin' | 'technician' | 'viewer'
department: string
}
interface AuthState {
user: User | null
token: string | null
isAuthenticated: boolean
isLoading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => void
checkAuth: () => Promise<void>
refreshToken: () => Promise<void>
}
export const useAuthStore = create<AuthState>()(
persist(
(set, get) => ({
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
login: async (email: string, password: string) => {
set({ isLoading: true })
try {
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
})
const data = await response.json()
if (!data.success) {
throw new Error(data.message || 'Error en el inicio de sesión')
}
console.log('AuthStore login: setting user and token', { user: data.data.user, token: !!data.data.token })
set({
user: data.data.user,
token: data.data.token,
isAuthenticated: true,
isLoading: false,
})
} catch (error) {
set({ isLoading: false })
throw error
}
},
logout: () => {
set({
user: null,
token: null,
isAuthenticated: false,
})
},
checkAuth: async () => {
const { token } = get()
console.log('AuthStore checkAuth: token present?', !!token)
if (!token) return
try {
const response = await fetch('/api/auth/me', {
headers: {
'Authorization': `Bearer ${token}`,
},
})
if (response.ok) {
const data = await response.json()
console.log('AuthStore checkAuth: user set from /me', { user: data.data.user })
set({
user: data.data.user,
isAuthenticated: true,
})
} else {
console.log('AuthStore checkAuth: token invalid, logging out')
// Token inválido, hacer logout
get().logout()
}
} catch (error) {
console.error('Error checking auth:', error)
get().logout()
}
},
refreshToken: async () => {
const { token } = get()
if (!token) return
try {
const response = await fetch('/api/auth/refresh', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ token }),
})
if (response.ok) {
const data = await response.json()
set({ token: data.data.token })
} else {
get().logout()
}
} catch (error) {
console.error('Error refreshing token:', error)
get().logout()
}
},
}),
{
name: 'auth-storage',
partialize: (state) => ({
user: state.user,
token: state.token,
isAuthenticated: state.isAuthenticated,
}),
}
)
)
@@ -0,0 +1,268 @@
import { create } from 'zustand'
import { devtools } from 'zustand/middleware'
export interface EntityConfig {
name: string
api: {
endpoint: string
methods: Record<string, string>
}
fields: any[]
table: {
columns: any[]
}
filters: any[]
actions: any[]
stats: any[]
modals: any[]
}
export interface GenericEntityState {
entities: any[]
loading: boolean
error: string | null
pagination: {
page: number
pages: number
total: number
per_page: number
} | null
filters: Record<string, any>
config: EntityConfig | null
}
export interface GenericEntityActions {
setConfig: (config: EntityConfig) => void
fetchEntities: (page?: number) => Promise<void>
createEntity: (data: any) => Promise<void>
updateEntity: (id: number, data: any) => Promise<void>
deleteEntity: (id: number) => Promise<void>
toggleEntityStatus: (id: number, isActive: boolean) => Promise<void>
setFilters: (filters: Record<string, any>) => void
clearFilters: () => void
setEntities: (entities: any[]) => void
setLoading: (loading: boolean) => void
setError: (error: string | null) => void
reset: () => void
}
export type GenericEntityStore = GenericEntityState & GenericEntityActions
const initialState: GenericEntityState = {
entities: [],
loading: false,
error: null,
pagination: null,
filters: {},
config: null
}
export const useGenericEntityStore = create<GenericEntityStore>()(
devtools(
(set, get) => ({
...initialState,
setConfig: (config: EntityConfig) => {
set({ config })
},
fetchEntities: async (page = 1) => {
const { config, filters } = get()
if (!config) return
set({ loading: true, error: null })
try {
const queryParams = new URLSearchParams({
page: page.toString(),
limit: '20', // Optimized default limit
...filters
})
const response = await fetch(`${config.api.endpoint}?${queryParams}`)
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
const data = await response.json()
// Handle different API response formats
let entities = []
let pagination = null
if (data.success && data.data) {
// API response format: { success: true, data: { tecnicos: [...], pagination: {...} } }
if (Array.isArray(data.data)) {
entities = data.data
} else if (data.data.tecnicos) {
entities = data.data.tecnicos
pagination = data.data.pagination
} else if (data.data.recursos) {
entities = data.data.recursos
pagination = data.data.pagination
} else if (data.data.usuarios) {
entities = data.data.usuarios
pagination = data.data.pagination
} else if (data.data.tasks) {
entities = data.data.tasks
pagination = data.data.pagination
} else if (data.data.tareas) {
entities = data.data.tareas
pagination = data.data.pagination
} else {
entities = data.data
}
} else {
// Fallback to direct data
entities = data.data || data
}
set({
entities,
pagination,
loading: false
})
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Error fetching entities',
loading: false
})
}
},
createEntity: async (data: any) => {
const { config } = get()
if (!config) return
try {
const response = await fetch(config.api.endpoint, {
method: config.api.methods.create,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
// Refresh entities after creation
get().fetchEntities()
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Error creating entity'
})
throw error
}
},
updateEntity: async (id: number, data: any) => {
const { config } = get()
if (!config) return
try {
const response = await fetch(`${config.api.endpoint}/${id}`, {
method: config.api.methods.update,
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`)
}
// Refresh entities after update
get().fetchEntities()
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Error updating entity'
})
throw error
}
},
deleteEntity: async (id: number) => {
const { config } = get()
if (!config) return
try {
const response = await fetch(`${config.api.endpoint}/${id}`, {
method: config.api.methods.delete
})
if (!response.ok) {
// Handle specific error cases with user-friendly messages
if (response.status === 409) {
const errorData = await response.json().catch(() => ({}))
const message = errorData.message || 'No se puede eliminar la entidad'
// Show specific messages based on the error
if (message.includes('tareas activas')) {
throw new Error('No se puede eliminar porque tiene tareas activas asignadas')
} else if (message.includes('desactivar')) {
throw new Error('El técnico será desactivado (no eliminado permanentemente) porque tiene tareas activas')
} else {
throw new Error(message)
}
} else {
throw new Error(`HTTP error! status: ${response.status}`)
}
}
// Refresh entities after successful deletion/deactivation
await get().fetchEntities()
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Error deleting entity'
})
// Still refresh the list even on error to show current state
await get().fetchEntities()
throw error
}
},
setFilters: (filters: Record<string, any>) => {
set({ filters })
},
clearFilters: () => {
set({ filters: {} })
},
setEntities: (entities: any[]) => {
set({ entities })
},
setLoading: (loading: boolean) => {
set({ loading })
},
setError: (error: string | null) => {
set({ error })
},
toggleEntityStatus: async (id: number, isActive: boolean) => {
const { config } = get()
if (!config) return
try {
await get().updateEntity(id, { is_active: isActive })
} catch (error) {
set({
error: error instanceof Error ? error.message : 'Error toggling entity status'
})
throw error
}
},
reset: () => {
set(initialState)
}
}),
{
name: 'generic-entity-store'
}
)
)
@@ -0,0 +1,112 @@
import { useGenericEntityStore } from '../stores/genericEntityStore'
import toast from 'react-hot-toast'
export interface ActionHandler {
(entity: any, ...args: any[]): Promise<void> | void
}
export interface ActionHandlers {
[key: string]: ActionHandler
}
export const createActionHandlers = (entityKey: string): ActionHandlers => {
const store = useGenericEntityStore()
return {
view: (entity: any) => {
// This will be handled by the modal system in EntityPage
console.log('View entity:', entity)
// The actual modal opening is handled in EntityPage.tsx
},
edit: (entity: any) => {
store.setEditingEntity?.(entity.id)
store.setShowEditForm?.(true)
},
delete: async (entity: any) => {
// This is now handled by the EntityPage component with custom confirmation
// The actual deletion logic is in EntityPage.tsx
},
changePassword: (entity: any) => {
// This will be handled by the modal system
console.log('Change password for:', entity)
},
toggleStatus: async (entity: any, isActive?: boolean) => {
const action = entity.is_active ? 'desactivar' : 'reactivar'
if (window.confirm(`¿Está seguro de ${action} este ${entityKey.slice(0, -1)}?`)) {
try {
await store.toggleEntityStatus?.(entity.id, !entity.is_active)
toast.success(`${entityKey.slice(0, -1)} ${action}do exitosamente`)
} catch (error) {
// Error handled by store
}
}
},
assign: (entity: any) => {
// This will be handled by the modal system
console.log('Assign entity:', entity)
},
unassign: async (entity: any, userId: number) => {
if (window.confirm('¿Está seguro de desasignar este recurso del usuario?')) {
try {
await store.unassignEntity?.(entity.id, userId)
} catch (error) {
// Error handled by store
}
}
}
}
}
export const getActionIcon = (actionKey: string, condition?: boolean): string => {
const icons: Record<string, string> = {
view: 'fa-eye',
edit: 'fa-edit',
delete: 'fa-trash',
changePassword: 'fa-key',
assign: 'fa-user-plus',
unassign: 'fa-user-minus'
}
if (actionKey === 'toggleStatus') {
return condition ? 'fa-ban' : 'fa-check'
}
return icons[actionKey] || 'fa-cog'
}
export const getActionColor = (actionKey: string, condition?: boolean): string => {
const colors: Record<string, string> = {
view: 'primary',
edit: 'warning',
delete: 'danger',
changePassword: 'info',
assign: 'success',
unassign: 'secondary'
}
if (actionKey === 'toggleStatus') {
return condition ? 'danger' : 'success'
}
return colors[actionKey] || 'secondary'
}
export const getActionLabel = (actionKey: string, entityName: string): string => {
const labels: Record<string, string> = {
view: `Ver ${entityName}`,
edit: 'Editar',
delete: `Eliminar ${entityName}`,
changePassword: 'Cambiar contraseña',
assign: 'Asignar Usuario',
unassign: 'Desasignar',
toggleStatus: 'Desactivar/Reactivar'
}
return labels[actionKey] || actionKey
}
@@ -0,0 +1,275 @@
// Utilidades compartidas para formateo y configuración de entidades
import React from 'react'
export interface BadgeConfig {
text: string
class: string
}
export interface EntityConfig {
formatters: Record<string, (value: any) => string>
icons: Record<string, string>
badges: Record<string, BadgeConfig>
categories?: Record<string, string>
roles?: Record<string, string>
departments?: Record<string, string>
}
export interface PartialEntityConfig extends Partial<EntityConfig> {
formatters: Record<string, (value: any) => string>
icons: Record<string, string>
badges: Record<string, BadgeConfig>
}
// Configuración específica para técnicos
export const tecnicoConfig: EntityConfig = {
formatters: {
role: (role: string) => ({
'admin': 'Administrador',
'technician': 'Técnico',
'viewer': 'Visualizador'
}[role] || role),
department: (dept: string) => ({
'dtic': 'DTIC',
'sistemas': 'Sistemas',
'redes': 'Redes',
'seguridad': 'Seguridad'
}[dept] || dept),
status: (status: boolean) => status ? 'Activo' : 'Inactivo',
date: (date: string) => new Date(date).toLocaleDateString('es-AR')
},
icons: {
'admin': 'fa-user-shield',
'technician': 'fa-user-cog',
'viewer': 'fa-user'
},
badges: {
'admin': { text: 'Administrador', class: 'bg-danger' },
'technician': { text: 'Técnico', class: 'bg-info' },
'viewer': { text: 'Visualizador', class: 'bg-secondary' },
'active': { text: 'Activo', class: 'bg-success' },
'inactive': { text: 'Inactivo', class: 'bg-warning' }
},
roles: {
'admin': 'Administrador',
'technician': 'Técnico',
'viewer': 'Visualizador'
},
departments: {
'dtic': 'DTIC',
'sistemas': 'Sistemas',
'redes': 'Redes',
'seguridad': 'Seguridad'
}
}
// Configuración específica para recursos
export const recursoConfig: EntityConfig = {
formatters: {
category: (category: string) => ({
'hardware': 'Hardware',
'software': 'Software',
'network': 'Redes',
'security': 'Seguridad',
'tools': 'Herramientas',
'facilities': 'Instalaciones'
}[category] || category),
status: (status: string) => ({
'available': 'Disponible',
'assigned': 'Asignado',
'maintenance': 'Mantenimiento',
'retired': 'Retirado'
}[status] || status),
statusCategory: (entity: any) => {
const statusText = ({
'available': 'Disponible',
'assigned': 'Asignado',
'maintenance': 'Mantenimiento',
'retired': 'Retirado'
} as Record<string, string>)[entity.status] || entity.status;
const categoryText = ({
'hardware': 'Hardware',
'software': 'Software',
'network': 'Redes',
'security': 'Seguridad',
'tools': 'Herramientas',
'facilities': 'Instalaciones'
} as Record<string, string>)[entity.category] || entity.category;
return `${statusText} - ${categoryText}`;
},
modeloSerie: (entity: any) => {
const model = entity.model || '';
const serie = entity.serial_number || '';
if (model && serie) return `${model} - ${serie}`;
if (model) return model;
if (serie) return serie;
return '-';
},
recursoModeloSerie: (entity: any) => {
const name = entity.name || '';
const model = entity.model || '';
const serie = entity.serial_number || '';
let modelSerie = '';
if (model && serie) modelSerie = `${model} - ${serie}`;
else if (model) modelSerie = model;
else if (serie) modelSerie = serie;
else modelSerie = '-';
return `${name}\n${modelSerie}`;
},
formatRelatedTasks: (entity: any) => {
const relatedTasks = entity.related_tasks || []
if (!Array.isArray(relatedTasks) || relatedTasks.length === 0) {
return 'Sin tareas relacionadas'
}
const firstTask = relatedTasks[0]
const remainingCount = relatedTasks.length - 1
let result = firstTask.title || 'Sin título'
if (remainingCount > 0) {
result += ` y ${remainingCount} tarea${remainingCount !== 1 ? 's' : ''} más`
}
return result
},
date: (date: string) => new Date(date).toLocaleDateString('es-AR')
},
icons: {
'hardware': 'fa-laptop',
'software': 'fa-key',
'network': 'fa-router',
'security': 'fa-shield-alt',
'tools': 'fa-tools',
'facilities': 'fa-building'
},
badges: {
'available': { text: 'Disponible', class: 'bg-success' },
'assigned': { text: 'Asignado', class: 'bg-info' },
'maintenance': { text: 'Mantenimiento', class: 'bg-warning' },
'retired': { text: 'Retirado', class: 'bg-secondary' }
},
categories: {
'hardware': 'Hardware',
'software': 'Software',
'network': 'Redes',
'security': 'Seguridad',
'tools': 'Herramientas',
'facilities': 'Instalaciones'
}
}
// Clase utilitaria para trabajar con configuraciones de entidades
export class EntityUtils {
constructor(private config: EntityConfig) {}
formatValue(key: string, value: any): string {
const formatter = this.config.formatters[key]
return formatter ? formatter(value) : String(value)
}
getIcon(key: string): string {
return this.config.icons[key] || 'fa-question'
}
getBadge(status: string): BadgeConfig {
return this.config.badges[status] || { text: status, class: 'bg-secondary' }
}
getCategoryIcon(category: string): string {
return this.config.icons[category] || 'fa-box'
}
formatRole(role: string): string {
return this.config.roles?.[role] || role
}
formatDepartment(dept: string): string {
return this.config.departments?.[dept] || dept
}
formatCategory(category: string): string {
return this.config.categories?.[category] || category
}
formatPriority(priority: string): string {
return this.config.formatters.priority(priority)
}
formatStatus(status: string): string {
return this.config.formatters.status(status)
}
formatDate(dateString: string): string {
return this.config.formatters.date(dateString)
}
}
// Configuración específica para tareas
export const tareaConfig: EntityConfig = {
formatters: {
priority: (priority: string) => ({
'low': 'Baja',
'medium': 'Media',
'high': 'Alta',
'urgent': 'Urgente'
}[priority] || priority),
status: (status: string) => ({
'pending': 'Pendiente',
'in_progress': 'En Progreso',
'completed': 'Completada',
'cancelled': 'Cancelada'
}[status] || status),
date: (date: string) => new Date(date).toLocaleDateString('es-AR')
},
icons: {
'low': 'fa-arrow-down',
'medium': 'fa-minus',
'high': 'fa-arrow-up',
'urgent': 'fa-exclamation-triangle',
'pending': 'fa-clock',
'in_progress': 'fa-play',
'completed': 'fa-check',
'cancelled': 'fa-times'
},
badges: {
'pending': { text: 'Pendiente', class: 'badge-status-pending' },
'in_progress': { text: 'En Progreso', class: 'badge-status-in_progress' },
'completed': { text: 'Completada', class: 'badge-status-completed' },
'cancelled': { text: 'Cancelada', class: 'badge-status-cancelled' },
'low': { text: 'Baja', class: 'badge-priority-low' },
'medium': { text: 'Media', class: 'badge-priority-medium' },
'high': { text: 'Alta', class: 'badge-priority-high' },
'urgent': { text: 'Urgente', class: 'badge-priority-urgent' }
}
}
// Instancias pre-configuradas
export const tecnicoUtils = new EntityUtils(tecnicoConfig)
export const recursoUtils = new EntityUtils(recursoConfig)
export const tareaUtils = new EntityUtils(tareaConfig)
// Función helper para crear utilidades personalizadas
export const createEntityUtils = (config: PartialEntityConfig) => new EntityUtils(config as EntityConfig)