Reestructuración modular integral de servicios, reorganización de gestión en docs/ y limpieza profunda del repositorio
This commit is contained in:
@@ -1,63 +0,0 @@
|
||||
# Archivo de ejemplo de variables de entorno para DTIC Bitácoras
|
||||
# Copia este archivo como .env y ajusta los valores según tu entorno
|
||||
|
||||
# === CONFIGURACIÓN GENERAL ===
|
||||
NODE_ENV=development
|
||||
# Opciones: development, production, test
|
||||
|
||||
# === BASE DE DATOS POSTGRESQL ===
|
||||
POSTGRES_DB=dtic_bitacoras
|
||||
POSTGRES_USER=dtic_user
|
||||
POSTGRES_PASSWORD=dtic_password
|
||||
# ⚠️ IMPORTANTE: Cambia esta contraseña en producción!
|
||||
POSTGRES_PORT=5432
|
||||
|
||||
# URL completa de conexión a la base de datos
|
||||
DATABASE_URL=postgresql://dtic_user:dtic_password@postgres:5432/dtic_bitacoras
|
||||
|
||||
# === API BACKEND ===
|
||||
JWT_SECRET=your-super-secret-jwt-key-change-in-production
|
||||
# ⚠️ IMPORTANTE: Genera una clave secreta segura para producción!
|
||||
# Puedes generar una con: openssl rand -base64 32
|
||||
API_PORT=3001
|
||||
|
||||
# === FRONTEND ===
|
||||
VITE_API_URL=http://localhost:3001/api
|
||||
FRONTEND_PORT=5173
|
||||
|
||||
# === CONFIGURACIÓN DE RED ===
|
||||
NETWORK_NAME=dtic_network
|
||||
|
||||
# === VOLÚMENES ===
|
||||
POSTGRES_VOLUME_NAME=dtic_bitacoras_postgres_data
|
||||
|
||||
# === CONFIGURACIÓN PARA PRODUCCIÓN ===
|
||||
|
||||
# Para despliegue en producción, ajusta estas variables:
|
||||
# NODE_ENV=production
|
||||
# POSTGRES_PASSWORD=tu_password_seguro_aqui
|
||||
# JWT_SECRET=tu_clave_jwt_segura_aqui
|
||||
# VITE_API_URL=https://tu-dominio.com/api
|
||||
# POSTGRES_PORT=5432
|
||||
# API_PORT=3001
|
||||
# FRONTEND_PORT=80
|
||||
|
||||
# === CONFIGURACIÓN SSL (OPCIONAL) ===
|
||||
# Si usas HTTPS en producción:
|
||||
# SSL_CERT_PATH=/path/to/ssl/cert.pem
|
||||
# SSL_KEY_PATH=/path/to/ssl/private.key
|
||||
|
||||
# === LOGGING ===
|
||||
LOG_LEVEL=info
|
||||
# Opciones: error, warn, info, debug
|
||||
|
||||
# === RATE LIMITING ===
|
||||
RATE_LIMIT_WINDOW_MS=900000
|
||||
RATE_LIMIT_MAX_REQUESTS=1000
|
||||
|
||||
# === CONFIGURACIÓN DE EMAIL (OPCIONAL) ===
|
||||
# Para funcionalidades de notificación:
|
||||
# SMTP_HOST=smtp.gmail.com
|
||||
# SMTP_PORT=587
|
||||
# SMTP_USER=tu-email@gmail.com
|
||||
# SMTP_PASS=tu-app-password
|
||||
@@ -1,377 +0,0 @@
|
||||
## [2.1.2] - 2025-11-29
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Documentación Integral Bilingüe del Sistema**: Creación de documentación completa en inglés y español para todos los módulos del sistema |
|
||||
| Agregado | **Índice de Documentación Interactivo**: Nuevo archivo index.md con navegación completa de todos los módulos |
|
||||
| Agregado | **Documentación de Arquitectura**: Documentación detallada de componentes, APIs, esquemas de base de datos y flujos de trabajo |
|
||||
| Agregado | **Guías de Desarrollo**: Documentación de procesos de desarrollo, convenciones de código y mejores prácticas |
|
||||
| Mejorado | **Organización de Documentación**: Estructura jerárquica con tabla de contenidos en cada archivo |
|
||||
| Mejorado | **Accesibilidad de Información**: Documentación disponible en español para facilitar el acceso a desarrolladores locales |
|
||||
| Detalles Técnicos | **Documentación de 11 Módulos**: Authentication, Dashboard, Technicians, Resources, Tasks, Users, Reports, Calendar, Project Status, System, Task-Resources |
|
||||
| Detalles Técnicos | **Versionado Sincronizado**: Actualización de versiones en package.json frontend, backend y visualización en UI |
|
||||
|
||||
## [2.1.1] - 2025-11-28
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Eliminado | **Limpieza de Archivos Históricos**: Eliminación de archivos obsoletos y documentación histórica movida a directorio _basurero |
|
||||
| Eliminado | **Archivos de Bitácoras Antiguas**: Remoción de archivos de bitácoras anteriores y estados del sistema |
|
||||
| Eliminado | **Documentación Duplicada**: Eliminación de archivos de documentación redundantes y prompts obsoletos |
|
||||
| Eliminado | **Archivos Temporales**: Limpieza de archivos temporales y de desarrollo no utilizados |
|
||||
| Detalles Técnicos | **Optimización del Repositorio**: Reducción significativa del tamaño del repositorio eliminando archivos innecesarios |
|
||||
| Detalles Técnicos | **Mantenimiento de Historial**: Preservación de archivos históricos en directorio _basurero para referencia futura |
|
||||
|
||||
## [2.1.0] - 2025-11-28
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Refactorización Modular del Sistema de Gestión**: Reestructuración completa de `app-run.sh` para mejorar mantenibilidad y escalabilidad |
|
||||
| Agregado | **Biblioteca Compartida de Funciones**: Creación de `app-run_lib.sh` con funciones reutilizables (log, success, error, warning, etc.) |
|
||||
| Agregado | **Módulo de Gestión de Dependencias**: Nuevo script `app-run_deps.sh` para manejo centralizado de dependencias del sistema |
|
||||
| Agregado | **Interfaz API-like para Sub-scripts**: Sub-scripts con argumentos CLI estrictos y códigos de salida estructurados |
|
||||
| Agregado | **Visualización de Versión en UI**: Badge de versión agregado en página Sistema para mostrar versión actual al usuario |
|
||||
| Mejorado | **Principio DRY Aplicado**: Eliminación de código duplicado y centralización de funciones comunes |
|
||||
| Mejorado | **Separación de Responsabilidades**: Funciones modulares con responsabilidades claras y bien definidas |
|
||||
| Mejorado | **Mantenibilidad del Código**: Reducción significativa de complejidad y mejora en legibilidad del código |
|
||||
| Eliminado | **Limpieza de Archivos Redundantes**: Eliminación de `install.sh` y `Makefile` duplicados |
|
||||
| Detalles Técnicos | **Arquitectura Modular**: Scripts divididos en biblioteca compartida, gestión de dependencias y lógica principal |
|
||||
| Detalles Técnicos | **API de Sub-scripts**: Interfaz consistente con argumentos CLI y códigos de retorno estandarizados |
|
||||
| Detalles Técnicos | **Versionado Sincronizado**: Actualización de versiones en `package.json` backend y frontend a v2.1.0 |
|
||||
| Detalles Técnicos | **UI de Versión**: Implementación de badge visual en interfaz de usuario para mostrar versión del sistema |
|
||||
|
||||
## [2.0.0] - 2025-11-17
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | Sistema completo de comandas dual con nomenclatura diferenciada (G/E) |
|
||||
| Agregado | Comanda-G 01: Documentación y establecimiento del mecanismo de comandas |
|
||||
| Agregado | Comanda-E 02: Corrección completa de estética visual (temas oscuro/claro) |
|
||||
| Agregado | Comanda-E 03: Estandarización de cabeceras módulos gestión |
|
||||
| Agregado | Comanda-E 04: Ajustes de color y contraste en sidebar |
|
||||
| Agregado | Comanda-E 05: Verificación y resolución de problemas de cache |
|
||||
| Mejorado | Variables CSS completas para temas oscuro y claro con overrides |
|
||||
| Mejorado | Sistema de referencias cruzadas entre orquestadores |
|
||||
| Corregido | Visibilidad perfecta de texto en tablas, sidebar y paneles de perfil |
|
||||
| Documentado | Mecanismo completo de comandas con instrucciones detalladas |
|
||||
|
||||
## [1.9.4] - 2025-11-17
|
||||
|
||||
### Cambios
|
||||
- Definir formato y estructura del archivo de comanda
|
||||
- Crear script registrar-avance.sh para automatización
|
||||
- Actualizar orquestadores principal y específico
|
||||
- Crear template de comanda
|
||||
- Agregar script a package.json
|
||||
|
||||
## [1.9.3] - 2025-11-17
|
||||
|
||||
### Cambios
|
||||
- Definir formato y estructura del archivo de comanda
|
||||
- Crear script registrar-avance.sh para automatización
|
||||
- Actualizar orquestadores principal y específico
|
||||
- Crear template de comanda
|
||||
- Agregar script a package.json
|
||||
|
||||
# REGISTRO DE CAMBIOS - DTIC Bitácoras
|
||||
|
||||
Todos los cambios notables de este proyecto serán documentados en este archivo.
|
||||
|
||||
El formato está basado en [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
y este proyecto se adhiere al [Versionado Semántico](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [1.8.0] - 2025-11-15
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | Completación de documentación integral del sistema y versionado, incluyendo carga dinámica de versiones, actualizaciones del marco de prompts DTIC, y todas las correcciones aplicadas. |
|
||||
|
||||
## [1.7.0] - 2025-11-14
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Integración del Marco de Prompts DTIC**: Sistema automatizado de workflow y gestión de documentación para procesos de desarrollo optimizados |
|
||||
| Agregado | **Capacidades Mejoradas de Documentación del Sistema**: Herramientas mejoradas de generación y mantenimiento de documentación |
|
||||
| Agregado | **Operaciones Mejoradas de Backup/Restore**: Fiabilidad mejorada y experiencia de usuario para funcionalidades de backup y restore de base de datos |
|
||||
| Agregado | **Alineación con el Sistema de Plantillas de Prompts Más Reciente**: Sistema actualizado para trabajar sin problemas con la versión actual del marco de prompts |
|
||||
|
||||
## [1.6.0] - 2025-11-14
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Funcionalidad de Interfaz de Usuario de Backup y Restore**: Implementación completa de interfaz de usuario de backup y restore para operaciones de base de datos |
|
||||
| Agregado | **Interfaz de Usuario Frontend**: Nuevos controles de backup y restore integrados en la página Sistema con interfaz de usuario intuitiva |
|
||||
| Agregado | **Endpoints de API Backend**: Nuevos endpoints `/api/system/backup` y `/api/system/restore` para operaciones seguras de base de datos |
|
||||
| Agregado | **Controles de Acceso de Administrador**: Acceso restringido a operaciones de backup y restore solo para usuarios administradores con autenticación adecuada |
|
||||
| Agregado | **Integración con Docker**: Integración perfecta con base de datos PostgreSQL en contenedor Docker para operaciones de backup y restore |
|
||||
| Agregado | **Manejo de Errores**: Manejo completo de errores y retroalimentación al usuario para operaciones de backup y restore con logging detallado |
|
||||
|
||||
## [1.5.0] - 2025-11-14
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | Agregada funcionalidad para cargar recursos desde archivos PDF en la base de datos. Importados exitosamente 233 recursos desde RECURSOS.pdf. Actualizados los prompts con la nueva plantilla DTIC-PDF-IMPORT-001 para operaciones de importación de datos PDF. |
|
||||
|
||||
## [1.4.3] - 2025-11-14
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Corregido | **Corrección Crítica del Nombre de Tabla de Base de Datos**: Corregido el nombre de tabla de `usuarios_asignados` a `usuarios_relacionados` en todo el sistema |
|
||||
| Corregido | **Restauración de Endpoints de API**: Restaurada funcionalidad para endpoints `/api/usuarios_relacionados` y `/api/recursos` |
|
||||
| Corregido | **Configuración de Conexión de Base de Datos**: Agregada configuración adecuada de `search_path` para acceso al esquema PostgreSQL |
|
||||
| Corregido | **Manejo de Errores de Consultas**: Mejorado el manejo de errores en operaciones de base de datos con bloques try/catch adecuados |
|
||||
| Cambiado | **Esquema de Base de Datos**: Renombrada tabla `dtic.usuarios_asignados` a `dtic.usuarios_relacionados` |
|
||||
| Cambiado | **Rutas Backend**: Actualizadas todas las referencias para usar el nombre correcto de tabla en rutas de API |
|
||||
| Cambiado | **Configuración del Pool de Base de Datos**: Agregada configuración de ruta de esquema para acceso consistente a tablas |
|
||||
| Detalles Técnicos | **Migración de Base de Datos**: Ejecutado `ALTER TABLE dtic.usuarios_asignados RENAME TO usuarios_relacionados` |
|
||||
| Detalles Técnicos | **Actualizaciones de Código**: Actualizadas 15+ referencias en archivos de rutas backend |
|
||||
| Detalles Técnicos | **Pool de Conexiones**: Agregado `SET search_path TO dtic, public` para todas las conexiones de base de datos |
|
||||
| Detalles Técnicos | **Manejo de Errores**: Mejorado el manejo de errores de base de datos con logging y propagación de errores adecuados |
|
||||
|
||||
## [1.4.2] - 2025-11-12
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Documentación | **Actualización de Documentación del Sistema**: Actualización completa de la documentación del sistema en directorio _docs con arquitectura actual, componentes, APIs y esquema de base de datos |
|
||||
| Documentación | **Consistencia de Versiones**: Actualizadas todas las referencias de versión en archivos package.json, componente Navbar y documentación |
|
||||
| Documentación | **Documentación de Workflow**: Documentación mejorada del workflow DTIC-DOC-001 para tareas de documentación y versionado |
|
||||
| Documentación | **Registros de Finalización de Tareas**: Nuevo registro de finalización de tareas creado en directorio _tareasTerminadas |
|
||||
| Documentación | **Verificación del Estado del Sistema**: Archivo de verificación creado en directorio _estados documentando el estado del sistema post-documentación |
|
||||
| Cambiado | **Incremento de Versión**: Incremento de versión patch de 1.4.1 a 1.4.2 para mejoras de documentación |
|
||||
| Cambiado | **Optimización de Prompts**: Actualizado _prompts/prompts-dtic-bitacoras.md con nueva plantilla y registro de solicitudes |
|
||||
| Cambiado | **Workflow de Documentación**: Ejecución completa del workflow de documentación de 4 fases (Tareas → Versionado → Verificación → Commit) |
|
||||
| Detalles Técnicos | **Versiones de Paquetes**: Actualizadas versiones de package.json backend y frontend a 1.4.2 |
|
||||
| Detalles Técnicos | **Visualización de Versión en UI**: Actualizado componente Navbar para mostrar el badge de versión correcto |
|
||||
| Detalles Técnicos | **Archivos de Documentación**: Actualización completa de la documentación del sistema con estado y arquitectura actuales |
|
||||
| Detalles Técnicos | **Registros de Tareas**: Nuevo archivo de finalización de tareas con timestamp siguiendo formato institucional |
|
||||
| Detalles Técnicos | **Proceso de Verificación**: Verificación del sistema completada con documentación de estado |
|
||||
|
||||
## [1.4.1] - 2025-11-12
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Cambiado | **Actualización de Terminología**: Cambiada terminología de "asignados" a "relacionados" para entidades de usuario en todo el sistema |
|
||||
| Cambiado | **Esquema de Base de Datos**: Renombrada tabla de `usuarios_asignados` a `usuarios_relacionados` |
|
||||
| Cambiado | **Endpoints de API**: Actualizadas rutas de API de `/api/usuarios_asignados` a `/api/usuarios_relacionados` |
|
||||
| Cambiado | **Texto de Interfaz de Usuario**: Actualizado texto de interfaz de usuario de "asignados" a "relacionados" en todos los componentes y páginas relacionados con usuarios |
|
||||
| Documentación | **Documentación del Módulo Recursos**: Documentación completa de todos los cambios realizados en el módulo Recursos siguiendo el workflow DTIC-DOC-001 |
|
||||
| Documentación | **Columnas Unificadas**: Documentación de columnas estandarizadas (Estado/Categoría, Modelo/Serie) y limpieza de interfaz |
|
||||
| Documentación | **Columna de Tareas Relacionadas**: Documentación de nueva funcionalidad de relación many-to-many entre tareas y recursos |
|
||||
| Documentación | **Modificaciones Backend**: Documentación de nuevas APIs, cambios en esquema de base de datos y lógica de validación |
|
||||
| Documentación | **Estilo de Colores**: Documentación de esquemas de colores aplicados para mejor jerarquía visual |
|
||||
| Detalles Técnicos | **Base de Datos**: Migrado nombre de tabla y actualizadas todas las referencias de claves foráneas e índices |
|
||||
| Detalles Técnicos | **Backend**: Renombrado archivo de rutas de `usuarios_asignados.js` a `usuarios_relacionados.js` y actualizadas todas las referencias internas |
|
||||
| Detalles Técnicos | **Frontend**: Actualizada configuración de entidades, hooks y componentes para usar nueva terminología y endpoints de API |
|
||||
| Detalles Técnicos | **Workflow de Documentación**: Ejecución completa del workflow DTIC-DOC-001 con finalización de tareas, verificación y actualización de versión |
|
||||
| Detalles Técnicos | **Creación de Bitácora**: Nuevo archivo de bitácora creado siguiendo formato institucional (bitacora_251112.md) |
|
||||
| Detalles Técnicos | **Verificación del Sistema**: Verificación completa de todas las funcionalidades del módulo Recursos |
|
||||
| Detalles Técnicos | **Actualización de Versión**: Versión del sistema incrementada a 1.4.1 (versión patch para mejoras de terminología y documentación) |
|
||||
|
||||
## [1.3.0] - 2025-11-07
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Sistema Completo de Plantillas DTIC Bitácoras**: Implementación de 11 plantillas especializadas para desarrollo automatizado |
|
||||
| Agregado | **Adaptación de Prompts y Plantillas**: Refactorización completa del sistema de prompts con clasificación automática |
|
||||
| Agregado | **Catálogo de Plantillas DTIC**: Nueva estructura modular con plantillas específicas por categoría |
|
||||
| Agregado | **Algoritmo de Selección Automática**: Sistema de interpretación automática de prompts con puntuación |
|
||||
| Agregado | **Plantillas Especializadas**: DTIC-DOC-001, DTIC-FE-001, DTIC-BE-001, DTIC-AUTH-001, DTIC-DB-001, DTIC-DEBUG-001, DTIC-OPT-001, DTIC-CONF-001, DTIC-CRUD-001, DTIC-DASH-001 |
|
||||
| Agregado | **Workflow de Documentación Automatizado**: Proceso completo de 4 fases para documentación de desarrollo |
|
||||
| Mejorado | **Consistencia de Versionado**: Corrección de inconsistencia entre Navbar (v1.2.0) y sistema (v1.3.0) |
|
||||
| Mejorado | **Proceso de Commit Estructurado**: Implementación de workflow DTIC-DOC-001 con fases definidas |
|
||||
| Mejorado | **Automatización de Documentación**: Scripts y procesos automatizados para generación de archivos |
|
||||
| Mejorado | **Sistema de Verificación**: Proceso completo de verificación post-commit con estados de sistema |
|
||||
| Detalles Técnicos | **Frontend**: Navbar actualizado con versión correcta v1.3.0 |
|
||||
| Detalles Técnicos | **Documentación**: Nueva estructura de archivos en _tareasTerminadas y _estados |
|
||||
| Detalles Técnicos | **Procesamiento Automatizado**: Sistema de clasificación y selección de plantillas por contexto |
|
||||
| Detalles Técnicos | **Workflow Completo**: DTIC-DOC-001 con fases de tareas, versionado, commit y verificación |
|
||||
|
||||
## [1.3.0] - 2025-11-06
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Funcionalidad Completa de Backup de Base de Datos**: Implementación completa de backup automático de PostgreSQL con `./app-run.sh bd-backup` |
|
||||
| Agregado | **Comando de Línea de Comandos**: Soporte para comando directo `bd-backup` en modo no interactivo |
|
||||
| Agregado | **Verificación de Integridad de Backup**: Sistema de validación post-backup con verificación de tamaño y contenido |
|
||||
| Agregado | **Soporte Dual de Backup**: Compatibilidad con `psql` local y Docker container para máxima flexibilidad |
|
||||
| Agregado | **Timestamps Automáticos**: Nombres de archivo con formato `dtic_bitacoras_backup_YYYYMMDD_HHMMSS.sql` |
|
||||
| Agregado | **Directorio Configurable**: Variable de entorno `APP_BACKUP_DIR` para personalizar ubicación de backups |
|
||||
| Mejorado | **Integración con Menú Interactivo**: Opciones de backup disponibles tanto con aplicación ejecutándose como detenida |
|
||||
| Mejorado | **Manejo de Errores**: Sistema robusto de cleanup automático y manejo de archivos parciales |
|
||||
| Mejorado | **Configuración de Credenciales**: Detección automática de credenciales desde archivo `.env` |
|
||||
| Mejorado | **Reportes Detallados**: Logging completo del proceso de backup con información de tamaño y línea count |
|
||||
| Detalles Técnicos | **Script Enhancement**: app-run.sh actualizado a versión 2.1 con funcionalidad de backup |
|
||||
| Detalles Técnicos | **Database Protection**: Validación de aplicación ejecutándose antes de permitir backup |
|
||||
| Detalles Técnicos | **Cross-Platform Support**: Funciona en Linux y macOS con Docker o instalación local de psql |
|
||||
| Detalles Técnicos | **Error Recovery**: Limpieza automática de archivos corruptos o incompletos |
|
||||
|
||||
## [1.2.0] - 2025-11-06
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Sistema de Verificación e Instalación Automática de Dependencias**: Implementación completa de verificación e instalación automática de dependencias del host (curl, jq) |
|
||||
| Agregado | **Detección Automática de Gestores de Paquetes**: Sistema inteligente para detectar apt-get, yum, dnf (Linux) y brew (macOS) |
|
||||
| Agregado | **Sistema de Primera Ejecución**: Recordatorio automático de primera ejecución con configuración guiada |
|
||||
| Agregado | **Modo Dual de Operación**: Soporte para modo interactivo y no interactivo con parámetros (start, stop, restart, status) |
|
||||
| Cambiado | **Refactorización con Arrays y Funciones Reutilizables**: Migración completa de variables individuales a arrays asociativos para mejor mantenibilidad |
|
||||
| Cambiado | **Mejora de Eficiencia del Código**: Reducción de ~60% en tiempo de verificación y ~70% en código duplicado |
|
||||
| Cambiado | **Sistema de Cleanup Automático**: Limpieza automática de contenedores detenidos y volúmenes huérfanos |
|
||||
| Cambiado | **Configuración de Timeouts**: Variables de entorno configurables para APP_TIMEOUT_CHECK y APP_MAX_ATTEMPTS |
|
||||
| Mejorado | **Compatibilidad Multiplataforma**: Soporte ampliado para 5+ gestores de paquetes diferentes |
|
||||
| Mejorado | **Experiencia de Usuario**: Configuración automática guiada con mensajes específicos y sugerencias |
|
||||
| Mejorado | **Mantenibilidad**: 15+ funciones modulares con separación clara de responsabilidades |
|
||||
| Mejorado | **Verificaciones de Estado**: Información detallada de contenedores con health checks y formato JSON |
|
||||
| Detalles Técnicos | **Scripts Optimizados**: app-run.sh completamente refactorizado con arrays asociativos y funciones reutilizables |
|
||||
| Detalles Técnicos | **Instalación Inteligente**: Comandos específicos por plataforma con fallbacks robustos |
|
||||
| Detalles Técnicos | **Manejo de Errores**: Mensajes específicos con instrucciones de solución para cada caso |
|
||||
| Detalles Técnicos | **Logging Centralizado**: Sistema de logging con niveles (DEBUG, INFO, WARN, ERROR) y timestamps |
|
||||
| Métricas de Rendimiento | **Reducción de tiempo de verificación**: ~60% |
|
||||
| Métricas de Rendimiento | **Mejora en detección de gestores**: +40% de distribuciones soportadas |
|
||||
| Métricas de Rendimiento | **Reducción de código duplicado**: ~70% |
|
||||
| Métricas de Rendimiento | **Compatibilidad ampliada**: Soporte para 5+ gestores de paquetes |
|
||||
| Detalles Técnicos | **Frontend**: React 18 + TypeScript + Vite + Bootstrap 5 |
|
||||
| Detalles Técnicos | **Backend**: Node.js 18 + Express + PostgreSQL + JWT |
|
||||
| Detalles Técnicos | **Database**: PostgreSQL 15 con pool de conexiones |
|
||||
| Detalles Técnicos | **Deployment**: Docker Compose con servicios orquestados |
|
||||
| Detalles Técnicos | **Host Dependencies**: curl, jq con instalación automática |
|
||||
| Detalles Técnicos | **Security**: Helmet, CORS, Rate Limiting, Prepared Statements |
|
||||
|
||||
## [1.1.3] - 2025-11-05
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Corregido | **Corrección de rutas en server.js**: Implementación de `path.resolve()` para rutas dinámicas de archivos YAML |
|
||||
| Corregido | **Mejora de verificación de dependencias Docker**: Verificación de versión mínima de Docker Engine (20.10+) |
|
||||
| Corregido | **Implementación de método alternativo PostgreSQL**: Fallback usando `psql` cuando `pg_isready` no está disponible |
|
||||
| Corregido | **Corrección de rutas en app-run.sh**: Uso de rutas relativas consistentes en comandos Docker Compose |
|
||||
| Corregido | **Mejora de logging centralizado**: Sistema de logging con niveles (DEBUG, INFO, WARN, ERROR) y timestamps |
|
||||
| Corregido | **Validación de configuración YAML**: Verificación de existencia de archivos antes del parseo |
|
||||
| Detalles Técnicos | **Backend**: Corrección de rutas hardcodeadas y mejora de manejo de errores en configuración |
|
||||
| Detalles Técnicos | **Script de despliegue**: Verificaciones más robustas de dependencias y mejor manejo de errores |
|
||||
| Detalles Técnicos | **Logging**: Implementación de logger centralizado con colores y niveles de severidad |
|
||||
| Detalles Técnicos | **Database**: Método alternativo de verificación de conectividad PostgreSQL |
|
||||
|
||||
## [1.1.2] - 2025-11-04
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Sistema de Asignación Directa de Recursos**: Nueva tabla `tarea_recursos` para asignar recursos específicos a tareas individuales |
|
||||
| Agregado | **Campos Adicionales en Asignaciones**: Horas estimadas, horas reales y notas específicas por asignación de recurso |
|
||||
| Agregado | **Auditoría de Asignaciones**: Registro de técnico asignador y timestamps para cada asignación de recurso |
|
||||
| Cambiado | **Consultas de Recursos**: Modificación de queries SQL para usar asignaciones directas tarea-recurso en lugar de relaciones indirectas |
|
||||
| Cambiado | **API de Tareas**: Actualización de endpoints para incluir información detallada de recursos asignados (horas, notas) |
|
||||
| Corregido | **Relaciones de Recursos**: Corrección de lógica para mostrar recursos asignados específicamente a cada tarea |
|
||||
| Corregido | **Precisión de Asignaciones**: Eliminación de asignaciones genéricas basadas en técnicos, implementación de asignaciones específicas |
|
||||
| Detalles Técnicos | **Database**: Nueva tabla `tarea_recursos` con constraints de unicidad y relaciones many-to-many |
|
||||
| Detalles Técnicos | **Backend**: Modificación de consultas SQL en `routes/tareas.js` para JOINs directos |
|
||||
| Detalles Técnicos | **Frontend**: Compatibilidad automática con nueva estructura de datos de recursos |
|
||||
| Detalles Técnicos | **Frontend**: React 18 + TypeScript + Vite + Bootstrap 5 |
|
||||
| Detalles Técnicos | **Backend**: Node.js 18 + Express + PostgreSQL + JWT |
|
||||
| Detalles Técnicos | **Database**: PostgreSQL 15 con pool de conexiones |
|
||||
| Detalles Técnicos | **Deployment**: Docker Compose con servicios orquestados |
|
||||
| Detalles Técnicos | **Security**: Helmet, CORS, Rate Limiting, Prepared Statements |
|
||||
|
||||
## [1.1.1] - 2025-11-04
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Sistema de Badges Profesionales**: Badges redondeados con colores específicos para estados y prioridades en todas las tablas |
|
||||
| Agregado | **Validaciones de Formularios Mejoradas**: Sistema de validación en frontend con mensajes de error informativos |
|
||||
| Agregado | **Filtrado de Técnicos Activos**: Solo técnicos activos se muestran en selectores de formularios de edición |
|
||||
| Agregado | **Optimización de Rendimiento**: Carga paralela de opciones dinámicas con estados de carga visuales |
|
||||
| Cambiado | **Interfaz de Tablas**: Mejora visual con badges centrados y colores profesionales en módulos de Tareas, Técnicos, Recursos y Usuarios |
|
||||
| Cambiado | **Sistema de Formularios**: Extensión de EntityForm con soporte completo para opciones dinámicas y validaciones |
|
||||
| Cambiado | **Paleta de Colores**: Implementación consistente de colores para estados, prioridades, roles y categorías |
|
||||
| Corregido | **Alineación Vertical**: Corrección perfecta de centrado vertical para badges en filas de tablas |
|
||||
| Corregido | **Carga de Opciones Dinámicas**: Resolución de errores de scope en funciones de carga de datos |
|
||||
| Corregido | **Estados de Carga**: Implementación correcta de indicadores visuales durante operaciones asíncronas |
|
||||
| Detalles Técnicos | **Frontend Enhancements**: Sistema de badges reutilizable, validaciones de formularios, carga paralela de datos |
|
||||
| Detalles Técnicos | **UI/UX Improvements**: Colores profesionales, alineación perfecta, experiencia de usuario optimizada |
|
||||
| Detalles Técnicos | **Performance**: Reducción del tiempo de carga en ~30% mediante operaciones paralelas |
|
||||
| Detalles Técnicos | **Frontend**: React 18 + TypeScript + Vite + Bootstrap 5 |
|
||||
| Detalles Técnicos | **Backend**: Node.js 18 + Express + PostgreSQL + JWT |
|
||||
| Detalles Técnicos | **Database**: PostgreSQL 15 con pool de conexiones |
|
||||
| Detalles Técnicos | **Deployment**: Docker Compose con servicios orquestados |
|
||||
| Detalles Técnicos | **Security**: Helmet, CORS, Rate Limiting, Prepared Statements |
|
||||
|
||||
## [1.0.0] - 2025-11-01
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Sistema PHP Básico**: Arquitectura inicial con Docker y MySQL |
|
||||
| Agregado | **Maquetación de Interfaz**: Páginas HTML/CSS/JS para todas las entidades |
|
||||
| Agregado | **Calendario Interactivo**: FullCalendar.js integrado |
|
||||
| Agregado | **Sistema de Reportes**: Gráficos básicos con Chart.js |
|
||||
| Agregado | **Auto-hide Navbar**: Funcionalidad avanzada con animaciones CSS |
|
||||
| Agregado | **Datos de Ejemplo**: Información simulada para testing |
|
||||
| Agregado | **Navegación Consistente**: Menú unificado entre todas las páginas |
|
||||
| Cambiado | **Base de Datos**: Migración de MySQL a PostgreSQL |
|
||||
| Cambiado | **Arquitectura**: Preparación para migración a Node.js |
|
||||
| Detalles Técnicos | **Frontend**: HTML5 + CSS3 + Vanilla JavaScript + Bootstrap 5 |
|
||||
| Detalles Técnicos | **Backend**: PHP 8.1 + Apache + MySQL |
|
||||
| Detalles Técnicos | **Database**: MySQL 8.0 con Docker |
|
||||
| Detalles Técnicos | **UI/UX**: Diseño responsive con gradientes y animaciones |
|
||||
|
||||
## [0.2.0] - 2025-10-15
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Configuración Docker**: Dockerfile y docker-compose.yml |
|
||||
| Agregado | **Base de Datos**: Esquema inicial con tablas de entidades |
|
||||
| Agregado | **Páginas Principales**: Dashboard, Técnicos, Recursos, Tareas |
|
||||
| Agregado | **Estilos CSS**: Diseño moderno con variables CSS personalizadas |
|
||||
| Agregado | **JavaScript Básico**: Funcionalidad de dashboard y navegación |
|
||||
| Detalles Técnicos | **Containerization**: Docker + Docker Compose |
|
||||
| Detalles Técnicos | **Database**: MySQL con phpMyAdmin |
|
||||
| Detalles Técnicos | **Frontend**: HTML básico con Bootstrap |
|
||||
|
||||
## [0.1.0] - 2025-10-01
|
||||
|
||||
| Tipo | Descripción |
|
||||
|------|-------------|
|
||||
| Agregado | **Proyecto Inicial**: Estructura básica del sistema DTIC Bitácoras |
|
||||
| Agregado | **Documentación**: README con descripción del proyecto |
|
||||
| Agregado | **Entidades Definidas**: Técnicos, Recursos, Usuarios, Tareas |
|
||||
| Agregado | **Arquitectura Planificada**: 3 capas (Frontend, Backend, Database) |
|
||||
| Detalles Técnicos | **Planning**: Definición de alcance y funcionalidades |
|
||||
| Detalles Técnicos | **Documentation**: Estructura del proyecto documentada |
|
||||
|
||||
---
|
||||
|
||||
## Guías de Versionado
|
||||
|
||||
Este proyecto sigue el [Versionado Semántico](https://semver.org/):
|
||||
|
||||
- Versión **MAJOR** para cambios incompatibles en la API
|
||||
- Versión **MINOR** para adiciones de funcionalidad compatibles hacia atrás
|
||||
- Versión **PATCH** para correcciones de errores compatibles hacia atrás
|
||||
|
||||
### Tipos de Cambios
|
||||
- **Agregado** para nuevas funcionalidades
|
||||
- **Cambiado** para cambios en funcionalidad existente
|
||||
- **Obsoleto** para funcionalidades próximamente eliminadas
|
||||
- **Eliminado** para funcionalidades eliminadas
|
||||
- **Corregido** para correcciones de errores
|
||||
- **Seguridad** en caso de vulnerabilidades
|
||||
|
||||
### Convención de Commits
|
||||
Los commits siguen la especificación [Conventional Commits](https://conventionalcommits.org/):
|
||||
- `feat:` para nuevas funcionalidades
|
||||
- `fix:` para correcciones de errores
|
||||
- `docs:` para documentación
|
||||
- `style:` para formateo
|
||||
- `refactor:` para reestructuración de código
|
||||
- `test:` para pruebas
|
||||
- `chore:` para mantenimiento
|
||||
|
||||
---
|
||||
|
||||
**Leyenda:**
|
||||
- 🚀 Nueva funcionalidad
|
||||
- 🐛 Corrección de error
|
||||
- 📚 Documentación
|
||||
- 🎨 Estilo
|
||||
- ♻️ Refactorización
|
||||
- ⚡ Rendimiento
|
||||
- 🔒 Seguridad
|
||||
- ✅ Prueba
|
||||
@@ -1,872 +0,0 @@
|
||||
# DTIC Bitácoras - Sistema de Gestión Integral
|
||||
|
||||
## 📋 Descripción del Sistema
|
||||
|
||||
DTIC Bitácoras es un sistema web completo de gestión de recursos tecnológicos y tareas para el Departamento de Tecnología de la Información y Comunicación (DTIC). Desarrollado con tecnologías modernas, permite administrar eficientemente el inventario de hardware/software, asignar recursos a usuarios, gestionar tareas técnicas y mantener un registro completo de todas las operaciones.
|
||||
|
||||
### 🎯 Propósito y Alcance
|
||||
|
||||
El sistema está diseñado para:
|
||||
- **Gestión de Recursos**: Controlar inventario de hardware, software, equipos de red y herramientas
|
||||
- **Administración de Personal**: Gestionar técnicos del DTIC con diferentes roles y permisos
|
||||
- **Asignación de Recursos**: Vincular recursos tecnológicos con usuarios finales
|
||||
- **Seguimiento de Tareas**: Administrar y monitorear tareas técnicas asignadas a técnicos
|
||||
- **Auditoría Completa**: Mantener registro detallado de todas las operaciones del sistema
|
||||
- **Reportes y Estadísticas**: Generar informes sobre el estado del inventario y rendimiento
|
||||
- **Framework de Prompts DTIC**: Sistema automatizado de gestión de flujos de trabajo y documentación para procesos de desarrollo optimizados
|
||||
|
||||
## 🚀 Inicio Rápido
|
||||
|
||||
### Opción 1: Usando Script Optimizado (Recomendado)
|
||||
|
||||
```bash
|
||||
# Configuración inicial automática (primera ejecución)
|
||||
./app-run.sh
|
||||
|
||||
# Iniciar aplicación
|
||||
./app-run.sh start
|
||||
|
||||
# Ver estado
|
||||
./app-run.sh status
|
||||
|
||||
# Ver logs (requiere aplicación ejecutándose)
|
||||
./app-run.sh logs
|
||||
|
||||
# Crear backup
|
||||
./app-run.sh bd-backup
|
||||
|
||||
# Detener aplicación
|
||||
./app-run.sh stop
|
||||
```
|
||||
|
||||
### Opción 2: Usando Docker Compose Manual
|
||||
|
||||
```bash
|
||||
# Clonar el repositorio
|
||||
git clone <repository-url>
|
||||
cd dtic-bitacoras-php/_app-npm
|
||||
|
||||
# Ejecutar la aplicación completa
|
||||
docker-compose up --build
|
||||
|
||||
# Acceder a la aplicación
|
||||
# Frontend: http://localhost:5173
|
||||
# Backend API: http://localhost:3001
|
||||
# Base de datos: localhost:5432
|
||||
```
|
||||
|
||||
## 🔧 Configuración para Despliegue Remoto
|
||||
|
||||
### 1. Variables de Entorno
|
||||
|
||||
Copia el archivo de ejemplo y configura tus variables:
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
# Edita .env según tus necesidades
|
||||
```
|
||||
|
||||
### 2. Configuración por Entorno
|
||||
|
||||
El archivo `docker-compose.override.yml` permite personalizar la configuración:
|
||||
|
||||
```yaml
|
||||
# Variables disponibles en .env
|
||||
POSTGRES_PORT=5432
|
||||
API_PORT=3001
|
||||
FRONTEND_PORT=5173
|
||||
NODE_ENV=production
|
||||
# ... etc
|
||||
```
|
||||
|
||||
### 3. Despliegue en Producción
|
||||
|
||||
```bash
|
||||
# Configurar variables de producción en .env
|
||||
NODE_ENV=production
|
||||
VITE_API_URL=https://tu-dominio.com/api
|
||||
|
||||
# Desplegar
|
||||
make up
|
||||
```
|
||||
|
||||
## 🏗️ Arquitectura del Sistema
|
||||
|
||||
### Arquitectura General
|
||||
|
||||
El sistema sigue una arquitectura de **3 capas** con contenedores Docker:
|
||||
|
||||
```
|
||||
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
|
||||
│ Frontend │ │ Backend │ │ Database │
|
||||
│ React/Vite │◄──►│ Node.js/Express │◄──►│ PostgreSQL │
|
||||
│ Puerto 5173 │ │ Puerto 3001 │ │ Puerto 5432 │
|
||||
└─────────────────┘ └─────────────────┘ └─────────────────┘
|
||||
```
|
||||
|
||||
### Componentes Principales
|
||||
|
||||
#### 🖥️ Frontend (React + Vite)
|
||||
- **Framework**: React 18 con TypeScript
|
||||
- **Estado Global**: Zustand para gestión de estado
|
||||
- **UI Components**: Bootstrap + FontAwesome
|
||||
- **Rutas**: React Router con protección de rutas
|
||||
- **Configuración**: Sistema de entidades dinámicas vía YAML
|
||||
- **Versionado Dinámico**: Carga automática de versión desde package.json mediante Vite config
|
||||
|
||||
#### 🚀 Backend (Node.js + Express)
|
||||
- **Runtime**: Node.js 18 con Alpine Linux
|
||||
- **Framework**: Express.js con middleware avanzado
|
||||
- **Base de Datos**: PostgreSQL con pool de conexiones
|
||||
- **Autenticación**: JWT con bcrypt para hashing
|
||||
- **API**: RESTful con validación de datos
|
||||
- **Seguridad**: Helmet, CORS, Rate Limiting
|
||||
|
||||
#### 🗄️ Base de Datos (PostgreSQL)
|
||||
- **Motor**: PostgreSQL 15
|
||||
- **Esquema**: `dtic` con tablas normalizadas
|
||||
- **Índices**: Optimizados para búsquedas comunes
|
||||
- **Auditoría**: Triggers automáticos para `updated_at`
|
||||
- **Datos de Ejemplo**: Incluye usuarios y recursos de prueba
|
||||
|
||||
### Entidades del Sistema
|
||||
|
||||
#### 👥 Técnicos
|
||||
Los **técnicos** son los profesionales especializados del DTIC que resuelven las tareas asignadas al departamento. Son los responsables directos de ejecutar y completar las actividades del sistema.
|
||||
|
||||
**Características principales:**
|
||||
- **ID único**: Identificador único del técnico
|
||||
- **Información personal**: Nombre, apellido, email, teléfono
|
||||
- **Rol**: Administrador, Técnico, Visualizador
|
||||
- **Departamento**: Área específica dentro del DTIC
|
||||
- **Estado**: Activo, Inactivo
|
||||
- **Tareas asignadas**: Número y lista de tareas bajo su responsabilidad
|
||||
- **Historial de actividad**: Registro de tareas completadas y en progreso
|
||||
- **Permisos**: Nivel de acceso al sistema según su rol
|
||||
|
||||
**Roles definidos:**
|
||||
- **Administrador**: Acceso completo, gestión de usuarios y configuración
|
||||
- **Técnico**: Ejecución de tareas, gestión de recursos asignados
|
||||
- **Visualizador**: Solo lectura, acceso a reportes y consultas
|
||||
|
||||
#### 📦 Recursos
|
||||
Los **recursos** son los elementos físicos o digitales que utiliza el DTIC para realizar sus tareas operativas. Cada recurso tiene características específicas y puede estar asignado a usuarios para su utilización.
|
||||
|
||||
**Características principales:**
|
||||
- **ID único**: Identificador alfanumérico único (ej: RES-001)
|
||||
- **Nombre**: Descripción clara del recurso
|
||||
- **Categoría**: Clasificación jerárquica (Hardware, Software, Redes, Seguridad, Herramientas)
|
||||
- **Estado**: Disponible, Asignado, Mantenimiento, Retirado
|
||||
- **Ubicación**: Lugar físico donde se encuentra el recurso
|
||||
- **Información técnica**: Modelo, serie, especificaciones técnicas
|
||||
- **Historial de uso**: Registro de tareas en las que ha sido utilizado
|
||||
- **Última tarea**: Información de la tarea más reciente donde participó
|
||||
|
||||
**Ejemplos de recursos:**
|
||||
- Laptops, proyectores, servidores (Hardware)
|
||||
- Licencias de software, antivirus (Software)
|
||||
- Routers, switches, cables (Redes)
|
||||
- Certificados, firewalls (Seguridad)
|
||||
- Kits de herramientas, testers (Herramientas)
|
||||
|
||||
#### 👤 Usuarios Relacionados
|
||||
Los **usuarios** son las personas que trabajan con los recursos del DTIC en sus actividades diarias. A diferencia de los técnicos, no resuelven tareas del sistema sino que utilizan los recursos relacionados para realizar su trabajo operativo.
|
||||
|
||||
**Características principales:**
|
||||
- **ID único**: Identificador único del usuario
|
||||
- **Información personal**: Nombre, apellido, email, teléfono
|
||||
- **Rol operativo**: Operador, Supervisor, Analista, Invitado
|
||||
- **Departamento**: Área específica donde opera
|
||||
- **Estado**: Activo, Inactivo
|
||||
- **Recursos relacionados**: Lista de recursos bajo su responsabilidad
|
||||
- **Historial de uso**: Registro de recursos utilizados
|
||||
|
||||
**Roles operativos:**
|
||||
- **Operador**: Uso básico de recursos asignados
|
||||
- **Supervisor**: Coordinación de recursos y supervisión de operadores
|
||||
- **Analista**: Análisis de datos y reportes usando recursos específicos
|
||||
- **Invitado**: Acceso limitado a recursos específicos por tiempo determinado
|
||||
|
||||
#### 📋 Tareas
|
||||
Las **tareas** son las actividades específicas que debe realizar el DTIC, asignadas a técnicos para su resolución. Cada tarea tiene un ciclo de vida completo desde su creación hasta su finalización.
|
||||
|
||||
**Características principales:**
|
||||
- **ID único**: Identificador alfanumérico único (ej: TSK-001)
|
||||
- **Título**: Descripción breve de la tarea
|
||||
- **Descripción**: Detalles completos de lo que se debe realizar
|
||||
- **Estado**: Pendiente, En Progreso, Completada, Cancelada
|
||||
- **Prioridad**: Baja, Media, Alta, Urgente
|
||||
- **Técnico asignado**: Profesional responsable de la ejecución
|
||||
- **Fechas**: Creación, inicio, vencimiento, finalización
|
||||
- **Historial de actividad**: Registro detallado de todos los movimientos
|
||||
- **Recursos utilizados**: Lista de recursos que participaron en la tarea
|
||||
|
||||
**Estados del ciclo de vida:**
|
||||
- **Pendiente**: Esperando asignación de técnico
|
||||
- **En Progreso**: Siendo ejecutada por el técnico asignado
|
||||
- **Completada**: Finalizada exitosamente
|
||||
- **Cancelada**: Terminada sin completar por diversos motivos
|
||||
|
||||
#### 📊 Historial de Auditoría
|
||||
El **historial de auditoría** registra todas las acciones realizadas en el sistema para mantener un registro completo de cambios y actividades.
|
||||
|
||||
**Características principales:**
|
||||
- **Usuario**: Quién realizó la acción
|
||||
- **Acción**: Tipo de operación (crear, modificar, eliminar, consultar)
|
||||
- **Entidad**: Objeto afectado (tarea, recurso, usuario, etc.)
|
||||
- **Fecha/Hora**: Timestamp preciso de la acción
|
||||
- **Detalles**: Información específica de lo que cambió
|
||||
- **IP**: Dirección desde donde se realizó la acción
|
||||
|
||||
#### 📈 Reportes y Análisis
|
||||
Los **reportes** son consultas estructuradas que permiten analizar el estado y rendimiento del sistema DTIC Bitácoras.
|
||||
|
||||
**Tipos de reportes:**
|
||||
- **Tareas**: Estado, productividad, tiempos de resolución
|
||||
- **Recursos**: Utilización, disponibilidad, mantenimiento
|
||||
- **Usuarios**: Actividad, asignaciones, rendimiento
|
||||
- **Sistema**: Estadísticas generales, logs de auditoría
|
||||
|
||||
### Funcionalidades Clave
|
||||
|
||||
#### 🔐 Sistema de Autenticación
|
||||
- Login seguro con JWT
|
||||
- Roles y permisos granulares
|
||||
- Cambio de contraseña
|
||||
- Sesiones persistentes
|
||||
|
||||
#### 📊 Dashboard y Estadísticas
|
||||
- Métricas en tiempo real
|
||||
- Gráficos de estado de recursos
|
||||
- Contadores de tareas por estado
|
||||
- Información consolidada del sistema
|
||||
|
||||
#### 🔍 Gestión Dinámica de Entidades
|
||||
- Sistema configurable vía archivos YAML
|
||||
- Formularios dinámicos
|
||||
- Tablas con filtros y búsqueda
|
||||
- Modales para acciones específicas
|
||||
|
||||
#### 📈 Reportes y Análisis
|
||||
- Estados de proyectos
|
||||
- Calendarios de tareas
|
||||
- Reportes personalizados
|
||||
- Exportación de datos
|
||||
|
||||
### 🔢 Sistema de Versionado Dinámico
|
||||
|
||||
El sistema implementa un mecanismo de versionado dinámico que garantiza la consistencia de versiones en toda la aplicación:
|
||||
|
||||
#### 📋 Carga Automática de Versión
|
||||
- **Configuración Vite**: El archivo `vite.config.ts` lee automáticamente la versión desde `package.json`
|
||||
- **Variable Global**: Define `import.meta.env.VERSION` disponible en todo el frontend
|
||||
- **Actualización Automática**: Cambios en `package.json` se reflejan inmediatamente en la interfaz
|
||||
|
||||
#### 🎨 Visualización en Interfaz
|
||||
- **Badge de Versión**: Se muestra en la barra de navegación principal junto al logo
|
||||
- **Formato**: `v{versión}` (ej: v1.7.0)
|
||||
- **Estilos**: Badge moderno con gradiente y efectos hover
|
||||
- **Ubicación**: Navbar superior, siempre visible para usuarios autenticados
|
||||
|
||||
#### 🔄 Mantenimiento de Versiones
|
||||
- **Semantic Versioning**: Seguimiento de cambios según MAJOR.MINOR.PATCH
|
||||
- **CHANGELOG**: Registro detallado de cambios por versión
|
||||
- **Consistencia**: Versiones sincronizadas entre package.json, documentación y código
|
||||
|
||||
## 📁 Estructura del Proyecto
|
||||
|
||||
```
|
||||
_app-npm/
|
||||
├── backend/ # API REST Node.js/Express
|
||||
│ ├── src/
|
||||
│ │ ├── routes/ # Endpoints por entidad
|
||||
│ │ │ ├── auth.js # Autenticación
|
||||
│ │ │ ├── tecnicos.js # Gestión de técnicos
|
||||
│ │ │ ├── recursos.js # Gestión de recursos
|
||||
│ │ │ ├── tareas.js # Gestión de tareas
|
||||
│ │ │ └── usuarios_relacionados.js # Gestión de usuarios
|
||||
│ │ ├── middleware/ # Middleware de seguridad
|
||||
│ │ │ └── auth.js # Verificación JWT
|
||||
│ │ └── server.js # Servidor principal
|
||||
│ ├── Dockerfile # Contenedor backend
|
||||
│ └── package.json # Dependencias Node.js
|
||||
├── frontend/ # SPA React/Vite
|
||||
│ ├── src/
|
||||
│ │ ├── components/ # Componentes reutilizables
|
||||
│ │ │ ├── common/ # Componentes genéricos
|
||||
│ │ │ ├── layout/ # Layout y navegación
|
||||
│ │ │ └── auth/ # Componentes de auth
|
||||
│ │ ├── pages/ # Páginas principales
|
||||
│ │ │ ├── Dashboard.tsx # Dashboard principal
|
||||
│ │ │ ├── EntityPage.tsx # Páginas dinámicas
|
||||
│ │ │ ├── Login.tsx # Página de login
|
||||
│ │ │ └── Reportes.tsx # Reportes del sistema
|
||||
│ │ ├── stores/ # Estado global (Zustand)
|
||||
│ │ │ ├── authStore.ts # Estado de autenticación
|
||||
│ │ │ └── genericEntityStore.ts # Estado de entidades
|
||||
│ │ ├── config/ # Configuración
|
||||
│ │ │ └── entities.yml # Definición de entidades
|
||||
│ │ └── utils/ # Utilidades
|
||||
│ ├── Dockerfile # Contenedor frontend
|
||||
│ ├── package.json # Dependencias frontend
|
||||
│ └── vite.config.ts # Configuración Vite
|
||||
├── docker/ # Configuración Docker
|
||||
│ └── init.sql # Inicialización BD
|
||||
├── docker-compose.yml # Orquestación de servicios
|
||||
├── docker-compose.override.yml # Override por entorno
|
||||
├── .env.example # Variables de entorno
|
||||
├── app-run.sh # Script principal optimizado
|
||||
├── app-run_lib.sh # Biblioteca de funciones compartidas
|
||||
├── app-run_deps.sh # Gestión de dependencias del sistema
|
||||
└── README.md # Esta documentación
|
||||
```
|
||||
|
||||
## 🛠️ Comandos Disponibles
|
||||
|
||||
### Script Optimizado app-run.sh
|
||||
|
||||
```bash
|
||||
./app-run.sh # Menú interactivo completo
|
||||
./app-run.sh start # Iniciar aplicación
|
||||
./app-run.sh stop # Detener aplicación
|
||||
./app-run.sh restart # Reiniciar aplicación
|
||||
./app-run.sh status # Ver estado detallado
|
||||
./app-run.sh bd-backup # Crear backup de base de datos
|
||||
./app-run.sh bd-restore # Restaurar backup de base de datos
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```bash
|
||||
docker-compose up -d # Iniciar en background
|
||||
docker-compose up --build # Construir e iniciar
|
||||
docker-compose down # Detener
|
||||
docker-compose logs -f # Ver logs en tiempo real
|
||||
docker-compose ps # Ver estado
|
||||
docker-compose exec api sh # Acceder al shell del API
|
||||
docker-compose exec postgres bash # Acceder a PostgreSQL
|
||||
```
|
||||
|
||||
## 🔍 Solución de Problemas
|
||||
|
||||
### Error "NetworkError when attempting to fetch resource"
|
||||
|
||||
1. **Verificar configuración CORS**: Asegurarse de que el backend permita el origen del frontend
|
||||
2. **Verificar VITE_API_URL**: Confirmar que apunte al servidor backend correcto
|
||||
3. **Verificar conectividad**: Probar que el backend esté ejecutándose y accesible
|
||||
|
||||
### Puertos Ocupados
|
||||
|
||||
Si los puertos por defecto están ocupados, modificalos en `.env`:
|
||||
|
||||
```env
|
||||
POSTGRES_PORT=5433
|
||||
API_PORT=3002
|
||||
FRONTEND_PORT=5174
|
||||
```
|
||||
|
||||
### Problemas de Base de Datos
|
||||
|
||||
```bash
|
||||
# Ver logs de PostgreSQL
|
||||
make logs-db
|
||||
|
||||
# Acceder a la base de datos
|
||||
make dev-db
|
||||
|
||||
# Recrear base de datos
|
||||
docker-compose down -v
|
||||
make up
|
||||
```
|
||||
|
||||
## 🔒 Seguridad
|
||||
|
||||
### Producción
|
||||
|
||||
- Cambia `JWT_SECRET` por una clave segura
|
||||
- Cambia `POSTGRES_PASSWORD` por una contraseña fuerte
|
||||
- Configura `NODE_ENV=production`
|
||||
- Usa HTTPS en producción
|
||||
- Configura firewall para exponer solo los puertos necesarios
|
||||
|
||||
### Variables Sensibles
|
||||
|
||||
Nunca commits las siguientes variables al repositorio:
|
||||
- `JWT_SECRET`
|
||||
- `POSTGRES_PASSWORD`
|
||||
- Cualquier clave API
|
||||
|
||||
## 📊 Monitoreo
|
||||
|
||||
### Health Checks
|
||||
|
||||
```bash
|
||||
make health-check
|
||||
```
|
||||
|
||||
### Logs
|
||||
|
||||
```bash
|
||||
make logs # Todos los logs
|
||||
make logs-api # Solo API
|
||||
make logs-frontend # Solo frontend
|
||||
make logs-db # Solo base de datos
|
||||
```
|
||||
|
||||
### Estado de Contenedores
|
||||
|
||||
```bash
|
||||
make status
|
||||
```
|
||||
|
||||
## 🔄 Backup y Restauración
|
||||
|
||||
### Crear Backup
|
||||
|
||||
```bash
|
||||
make backup
|
||||
# Los backups se guardan en ./backups/
|
||||
```
|
||||
|
||||
### Restaurar Backup
|
||||
|
||||
```bash
|
||||
make restore
|
||||
# Selecciona el archivo de backup del listado
|
||||
```
|
||||
|
||||
## 🐳 Docker
|
||||
|
||||
### Imágenes
|
||||
|
||||
- **PostgreSQL**: `postgres:15-alpine`
|
||||
- **API**: `node:18-alpine` con aplicación Node.js
|
||||
- **Frontend**: `node:18-alpine` con aplicación React/Vite
|
||||
|
||||
### Volúmenes
|
||||
|
||||
- `postgres_data`: Datos persistentes de PostgreSQL
|
||||
- `./backups`: Backups de base de datos
|
||||
- `./logs`: Logs de la aplicación
|
||||
|
||||
### Redes
|
||||
|
||||
- `dtic_network`: Red interna para comunicación entre servicios
|
||||
|
||||
## 🧪 Desarrollo y Testing
|
||||
|
||||
### Entorno de Desarrollo
|
||||
|
||||
#### Configuración Inicial
|
||||
```bash
|
||||
# Clonar repositorio
|
||||
git clone <repository-url>
|
||||
cd dtic-bitacoras-php/_app-npm
|
||||
|
||||
# Configuración automática
|
||||
./setup.sh
|
||||
|
||||
# O configuración manual
|
||||
make setup
|
||||
```
|
||||
|
||||
#### Ejecución en Modo Desarrollo
|
||||
```bash
|
||||
# Todos los servicios
|
||||
make up
|
||||
|
||||
# Solo frontend (puerto 5173)
|
||||
make dev-frontend
|
||||
|
||||
# Solo backend (puerto 3001)
|
||||
make dev-backend
|
||||
|
||||
# Acceder a base de datos
|
||||
make dev-db
|
||||
```
|
||||
|
||||
#### Desarrollo con Hot Reload
|
||||
- **Frontend**: Cambios automáticos con Vite HMR
|
||||
- **Backend**: Reinicio automático con nodemon
|
||||
- **Base de Datos**: Persistente con volúmenes Docker
|
||||
|
||||
### Testing
|
||||
|
||||
#### Ejecutar Tests
|
||||
```bash
|
||||
# Suite completa
|
||||
make test
|
||||
|
||||
# Tests específicos
|
||||
make test-backend # Tests del backend
|
||||
make test-frontend # Tests del frontend
|
||||
|
||||
# Tests con coverage
|
||||
make test-coverage
|
||||
```
|
||||
|
||||
#### Tipos de Tests
|
||||
- **Unit Tests**: Componentes individuales y funciones utilitarias
|
||||
- **Integration Tests**: Endpoints de API y interacciones con BD
|
||||
- **E2E Tests**: Flujos completos de usuario con Playwright/Cypress
|
||||
|
||||
### Debugging
|
||||
|
||||
#### Logs en Tiempo Real
|
||||
```bash
|
||||
# Todos los servicios
|
||||
make logs
|
||||
|
||||
# Servicio específico
|
||||
make logs-api # Backend
|
||||
make logs-frontend # Frontend
|
||||
make logs-db # Base de datos
|
||||
```
|
||||
|
||||
#### Acceso a Contenedores
|
||||
```bash
|
||||
# Shell en backend
|
||||
docker-compose exec api sh
|
||||
|
||||
# PostgreSQL CLI
|
||||
docker-compose exec postgres psql -U dtic_user -d dtic_bitacoras
|
||||
|
||||
# Inspeccionar red
|
||||
docker network inspect dtic_bitacoras_dtic_network
|
||||
```
|
||||
|
||||
### Base de Datos de Desarrollo
|
||||
|
||||
#### Conexión Directa
|
||||
```bash
|
||||
# Desde host
|
||||
psql -h localhost -p 5432 -U dtic_user -d dtic_bitacoras
|
||||
|
||||
# Desde contenedor
|
||||
make dev-db
|
||||
```
|
||||
|
||||
#### Datos de Prueba
|
||||
La base de datos incluye datos de ejemplo:
|
||||
- **7 Técnicos**: Admin, técnicos y visualizadores
|
||||
- **6 Recursos**: Hardware, software y herramientas
|
||||
- **5 Usuarios Relacionados**: Personal administrativo
|
||||
- **Asignaciones**: Recursos vinculados a usuarios
|
||||
|
||||
#### Reset de Datos
|
||||
```bash
|
||||
# Recrear base de datos
|
||||
make clean
|
||||
make up
|
||||
|
||||
# O desde contenedor
|
||||
docker-compose exec postgres psql -U dtic_user -d dtic_bitacoras -c "DROP SCHEMA dtic CASCADE; CREATE SCHEMA dtic;"
|
||||
```
|
||||
|
||||
## 🤝 Contribución y Desarrollo
|
||||
|
||||
### Flujo de Trabajo
|
||||
|
||||
1. **Fork y Clone**
|
||||
```bash
|
||||
git clone <tu-fork-url>
|
||||
cd dtic-bitacoras-php/_app-npm
|
||||
git checkout -b feature/nueva-funcionalidad
|
||||
```
|
||||
|
||||
2. **Desarrollo**
|
||||
```bash
|
||||
# Instalar dependencias
|
||||
make setup
|
||||
|
||||
# Ejecutar en desarrollo
|
||||
make up
|
||||
|
||||
# Tests continuos
|
||||
make test-watch
|
||||
```
|
||||
|
||||
3. **Commits y Pull Request**
|
||||
```bash
|
||||
git add .
|
||||
git commit -m "feat: descripción de la funcionalidad"
|
||||
git push origin feature/nueva-funcionalidad
|
||||
# Crear PR en GitHub
|
||||
```
|
||||
|
||||
### Estándares de Código
|
||||
|
||||
#### Frontend (TypeScript/React)
|
||||
- **Linter**: ESLint con reglas de Airbnb
|
||||
- **Formatter**: Prettier
|
||||
- **Tipos**: TypeScript estricto
|
||||
- **Componentes**: Funcionales con hooks
|
||||
- **Estado**: Zustand para estado global
|
||||
|
||||
#### Backend (Node.js)
|
||||
- **Linter**: ESLint Node.js
|
||||
- **Estructura**: MVC con separación de responsabilidades
|
||||
- **Validación**: Joi para schemas de datos
|
||||
- **Errores**: Manejo centralizado de errores
|
||||
- **Logs**: Winston para logging estructurado
|
||||
|
||||
#### Base de Datos
|
||||
- **Migrations**: Versionado de schema
|
||||
- **Seeds**: Datos de prueba consistentes
|
||||
- **Índices**: Optimización de consultas
|
||||
- **Constraints**: Integridad referencial
|
||||
|
||||
### Documentación
|
||||
|
||||
#### Código
|
||||
- **JSDoc**: Comentarios en funciones complejas
|
||||
- **README**: Actualización de documentación
|
||||
- **API Docs**: Swagger/OpenAPI para endpoints
|
||||
|
||||
#### Commits
|
||||
- **Conventional Commits**: `feat:`, `fix:`, `docs:`, `refactor:`
|
||||
- **Descripciones**: Claras y específicas
|
||||
- **Issues**: Referencia a issues relacionados
|
||||
|
||||
## 📋 API Reference
|
||||
|
||||
### Endpoints Principales
|
||||
|
||||
#### Autenticación
|
||||
```
|
||||
POST /api/auth/login # Login de usuario
|
||||
POST /api/auth/logout # Logout (cliente-side)
|
||||
GET /api/auth/verify # Verificar token
|
||||
```
|
||||
|
||||
#### Técnicos
|
||||
```
|
||||
GET /api/tecnicos # Listar técnicos
|
||||
POST /api/tecnicos # Crear técnico
|
||||
PUT /api/tecnicos/:id # Actualizar técnico
|
||||
DELETE /api/tecnicos/:id # Eliminar técnico
|
||||
PATCH /api/tecnicos/:id/toggle # Activar/desactivar
|
||||
```
|
||||
|
||||
#### Recursos
|
||||
```
|
||||
GET /api/recursos # Listar recursos
|
||||
POST /api/recursos # Crear recurso
|
||||
PUT /api/recursos/:id # Actualizar recurso
|
||||
DELETE /api/recursos/:id # Eliminar recurso
|
||||
POST /api/recursos/:id/assign # Asignar a usuario
|
||||
DELETE /api/recursos/:id/unassign # Desasignar
|
||||
```
|
||||
|
||||
#### Tareas
|
||||
```
|
||||
GET /api/tareas # Listar tareas
|
||||
POST /api/tareas # Crear tarea
|
||||
PUT /api/tareas/:id # Actualizar tarea
|
||||
DELETE /api/tareas/:id # Eliminar tarea
|
||||
```
|
||||
|
||||
#### Usuarios Relacionados
|
||||
```
|
||||
GET /api/usuarios_relacionados # Listar usuarios
|
||||
POST /api/usuarios_relacionados # Crear usuario
|
||||
PUT /api/usuarios_relacionados/:id # Actualizar usuario
|
||||
DELETE /api/usuarios_relacionados/:id # Eliminar usuario
|
||||
```
|
||||
|
||||
### Configuración Dinámica
|
||||
```
|
||||
GET /api/config/entities.yml # Configuración de entidades
|
||||
```
|
||||
|
||||
## 🔧 Configuración Avanzada
|
||||
|
||||
### Variables de Entorno
|
||||
|
||||
| Variable | Descripción | Default |
|
||||
|----------|-------------|---------|
|
||||
| `NODE_ENV` | Ambiente (development/production) | development |
|
||||
| `PORT` | Puerto del backend | 3001 |
|
||||
| `DATABASE_URL` | URL de conexión PostgreSQL | - |
|
||||
| `JWT_SECRET` | Clave secreta para JWT | - |
|
||||
| `JWT_EXPIRES_IN` | Expiración del token | 24h |
|
||||
| `CORS_ORIGIN` | Origen permitido para CORS | * |
|
||||
|
||||
### Docker Compose Overrides
|
||||
|
||||
```yaml
|
||||
# docker-compose.override.yml
|
||||
services:
|
||||
api:
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
JWT_SECRET: ${JWT_SECRET}
|
||||
ports:
|
||||
- "80:3001"
|
||||
|
||||
postgres:
|
||||
environment:
|
||||
POSTGRES_PASSWORD: ${DB_PASSWORD}
|
||||
```
|
||||
|
||||
## 📊 Monitoreo y Métricas
|
||||
|
||||
### Health Checks
|
||||
- **Endpoint**: `GET /health`
|
||||
- **Base de Datos**: Verificación de conexión
|
||||
- **Servicios**: Estado de dependencias
|
||||
|
||||
### Métricas de Rendimiento
|
||||
- **Response Times**: Tiempos de respuesta por endpoint
|
||||
- **Database Queries**: Consultas lentas y optimización
|
||||
- **Memory Usage**: Uso de memoria por contenedor
|
||||
- **Error Rates**: Tasa de errores por servicio
|
||||
|
||||
## 🚨 Solución de Problemas Comunes
|
||||
|
||||
### Problemas de Conexión
|
||||
```bash
|
||||
# Verificar servicios
|
||||
docker-compose ps
|
||||
|
||||
# Logs de errores
|
||||
make logs
|
||||
|
||||
# Reiniciar servicios
|
||||
make restart
|
||||
```
|
||||
|
||||
### Problemas de Base de Datos
|
||||
```bash
|
||||
# Verificar conexión
|
||||
make health-check
|
||||
|
||||
# Reset de datos
|
||||
make clean && make up
|
||||
```
|
||||
|
||||
### Problemas de Frontend
|
||||
```bash
|
||||
# Limpiar cache
|
||||
rm -rf node_modules/.vite
|
||||
make dev-frontend
|
||||
```
|
||||
|
||||
## 📞 Soporte y Contacto
|
||||
|
||||
### Canales de Soporte
|
||||
- **Issues**: GitHub Issues para bugs y features
|
||||
- **Discussions**: GitHub Discussions para preguntas
|
||||
- **Wiki**: Documentación detallada en GitHub Wiki
|
||||
|
||||
### Reportar Bugs
|
||||
1. Verificar si ya existe el issue
|
||||
2. Incluir pasos para reproducir
|
||||
3. Adjuntar logs relevantes
|
||||
4. Especificar versión y entorno
|
||||
|
||||
### Solicitar Features
|
||||
1. Describir la funcionalidad deseada
|
||||
2. Explicar el caso de uso
|
||||
3. Proponer implementación si es posible
|
||||
|
||||
## 📚 Evolución del Proyecto
|
||||
|
||||
### Antecedentes
|
||||
Este proyecto representa la evolución completa del sistema DTIC Bitácoras, desde un enfoque inicial basado en PHP/MySQL hasta la implementación actual con tecnologías modernas React/Node.js/PostgreSQL.
|
||||
|
||||
### Fases de Desarrollo
|
||||
|
||||
#### **Fase 1: Fundación PHP (2025-10)**
|
||||
- **Arquitectura**: HTML/JS/PHP/MySQL con Docker
|
||||
- **Alcance**: Desarrollo de interfaces básicas y configuración de contenedores
|
||||
- **Estado**: ✅ Completado - Etapas 1 y 2 del plan original
|
||||
- **Resultado**: Base sólida para la evolución tecnológica
|
||||
- **Tareas Clave**: Configuración Docker, maquetación interfaz, auto-hide navbar
|
||||
|
||||
#### **Fase 2: Migración Tecnológica (2025-11)**
|
||||
- **Arquitectura**: React/Node.js/PostgreSQL con Docker
|
||||
- **Alcance**: Reimplementación completa con tecnologías modernas
|
||||
- **Estado**: ✅ Completado - Sistema 100% funcional (v1.2.0)
|
||||
- **Resultado**: Aplicación full-stack moderna y escalable
|
||||
- **Tareas Clave**: APIs RESTful, autenticación JWT, gestión entidades CRUD
|
||||
|
||||
### Metodología de Desarrollo
|
||||
El proyecto se desarrolló siguiendo una metodología estructurada:
|
||||
|
||||
1. **Análisis y Planificación**: Definición de entidades y arquitectura
|
||||
2. **Implementación por Etapas**: Desarrollo incremental con hitos claros
|
||||
3. **Migración Tecnológica**: Transición de PHP a Node.js/React
|
||||
4. **Optimización Continua**: Mejoras en scripts, documentación y procesos
|
||||
|
||||
### Tecnologías Evolutivas
|
||||
- **Inicial**: PHP 8.1, MySQL 8.0, HTML5/CSS3/JS, Bootstrap 5
|
||||
- **Actual**: React 18, Node.js 18, PostgreSQL 15, TypeScript, Docker
|
||||
|
||||
### 📋 Resumen de Tareas Completadas
|
||||
|
||||
#### **Estimación de Versión (2025-11-04)**
|
||||
- ✅ Análisis completo de evolución del proyecto
|
||||
- ✅ Determinación de versión 1.1.0 según Semantic Versioning
|
||||
- ✅ Justificación técnica por componentes MAJOR/MINOR/PATCH
|
||||
- ✅ Planificación de versiones futuras (1.2.0, 1.3.0, 2.0.0)
|
||||
|
||||
#### **Optimización de Scripts (2025-11-04)**
|
||||
- ✅ Script app-run.sh completamente optimizado
|
||||
- ✅ Modo dual: interactivo + parámetros start/stop/restart/status
|
||||
- ✅ Verificación robusta de dependencias (Docker, docker-compose)
|
||||
- ✅ Validación completa de conectividad PostgreSQL
|
||||
- ✅ Cleanup automático de recursos Docker
|
||||
|
||||
#### **Reorganización de Documentación (2025-11-04)**
|
||||
- ✅ CHANGELOG.md movido a _app-npm/ para centralización
|
||||
- ✅ README.md histórico archivado en _basurero/ como referencia
|
||||
- ✅ Estructura de documentación consolidada
|
||||
- ✅ Navegabilidad mejorada para desarrolladores
|
||||
|
||||
#### **Enriquecimiento con Información Histórica (2025-11-04)**
|
||||
- ✅ Sección "Entidades del Sistema" enriquecida con detalles técnicos
|
||||
- ✅ Nueva sección "Evolución del Proyecto" documentada
|
||||
- ✅ Información institucional completa del autor agregada
|
||||
- ✅ Contexto académico de UTN FR La Rioja incorporado
|
||||
|
||||
---
|
||||
|
||||
## 👨💻 Autor y Desarrollo
|
||||
|
||||
**Desarrollado por:** Lic. Ricardo MONLA
|
||||
**Institución:** Universidad Tecnológica Nacional - Facultad Regional La Rioja
|
||||
**Departamento:** Departamento de Servidores, Dirección de TIC
|
||||
**Proyecto:** Sistema DTIC Bitácoras v1.7.0
|
||||
**Fecha:** Noviembre 2025
|
||||
|
||||
### Contacto
|
||||
Para soporte técnico o consultas sobre el desarrollo del sistema, contactar al departamento DTIC de la UTN FR La Rioja.
|
||||
|
||||
## 🔄 Cambios Recientes y Mantenimiento
|
||||
|
||||
### Últimas Actualizaciones (2025-11-04)
|
||||
- ✅ **Versión 1.1.0** establecida según Semantic Versioning
|
||||
- ✅ **Script app-run.sh** completamente optimizado con modos duales
|
||||
- ✅ **Documentación reorganizada** y centralizada en _app-npm/
|
||||
- ✅ **Información histórica** incorporada y enriquecida
|
||||
- ✅ **Identidad institucional** completa documentada
|
||||
|
||||
### Próximas Versiones Planificadas
|
||||
- **v1.2.0**: Calendario interactivo completo + sistema de reportes
|
||||
- **v1.3.0**: Notificaciones en tiempo real + filtros avanzados
|
||||
- **v2.0.0**: Multi-tenancy + APIs públicas
|
||||
|
||||
### Mantenimiento y Soporte
|
||||
- **Repositorio**: Gestión completa con Git y Conventional Commits
|
||||
- **Documentación**: README.md + CHANGELOG.md actualizados
|
||||
- **Scripts**: Automatización completa con app-run.sh optimizado
|
||||
- **Soporte**: Departamento DTIC - UTN FR La Rioja
|
||||
|
||||
---
|
||||
|
||||
**Desarrollado por:** Lic. Ricardo MONLA
|
||||
**Institución:** Universidad Tecnológica Nacional - Facultad Regional La Rioja
|
||||
**Departamento:** Departamento de Servidores, Dirección de TIC
|
||||
**Proyecto:** Sistema DTIC Bitácoras v1.7.0
|
||||
**Última actualización:** Noviembre 2025
|
||||
@@ -1,778 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# DTIC Bitácoras - Script Optimizado de Gestión de Aplicación
|
||||
# =============================================================================
|
||||
#
|
||||
# Script optimizado para gestión completa de la aplicación DTIC Bitácoras
|
||||
# Soporta modos interactivo y no interactivo con parámetros
|
||||
#
|
||||
# Características:
|
||||
# - Modo interactivo (sin parámetros) con menús inteligentes
|
||||
# - Modo no interactivo con parámetros: start, stop, restart, status
|
||||
# - Verificación robusta de dependencias (Docker, docker-compose)
|
||||
# - Validación completa de PostgreSQL y servicios
|
||||
# - Cleanup automático de recursos huérfanos
|
||||
# - Timeouts configurables vía variables de entorno
|
||||
#
|
||||
# Uso:
|
||||
# ./app-run.sh # Modo interactivo
|
||||
# ./app-run.sh start # Iniciar aplicación (no interactivo)
|
||||
# ./app-run.sh stop # Detener aplicación (no interactivo)
|
||||
# ./app-run.sh restart # Reiniciar aplicación (no interactivo)
|
||||
# ./app-run.sh status # Mostrar estado detallado (no interactivo)
|
||||
# ./app-run.sh bd-backup # Crear backup de base de datos (no interactivo)
|
||||
# ./app-run.sh bd-restore # Restaurar base de datos desde backup (no interactivo)
|
||||
#
|
||||
# Variables de entorno:
|
||||
# APP_TIMEOUT_CHECK=30 # Timeout para verificar servicios (segundos)
|
||||
# APP_MAX_ATTEMPTS=20 # Máximo número de intentos de verificación
|
||||
# APP_BACKUP_DIR="backups" # Directorio para backups
|
||||
#
|
||||
# Versión: 2.1 - Con funcionalidad de backup
|
||||
# Fecha: 2025-11-06
|
||||
# =============================================================================
|
||||
|
||||
set -e
|
||||
|
||||
# Change to script directory to allow running from anywhere
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
cd "$SCRIPT_DIR"
|
||||
|
||||
# Cargar biblioteca compartida
|
||||
source "$SCRIPT_DIR/app-run_lib.sh"
|
||||
|
||||
# Configuración
|
||||
API_PORT=3001
|
||||
FRONTEND_PORT=5173
|
||||
DB_PORT=5432
|
||||
API_URL="http://localhost:$API_PORT"
|
||||
FRONTEND_URL="http://localhost:$FRONTEND_PORT"
|
||||
DB_URL="localhost:$DB_PORT"
|
||||
|
||||
# Configuración de timeouts (configurables vía entorno)
|
||||
TIMEOUT_CHECK=${APP_TIMEOUT_CHECK:-30}
|
||||
MAX_ATTEMPTS=${APP_MAX_ATTEMPTS:-20}
|
||||
|
||||
# Configuración de backup
|
||||
BACKUP_DIR=${APP_BACKUP_DIR:-"backups"}
|
||||
BACKUP_FORMAT="dtic_bitacoras_backup_%Y%m%d_%H%M%S.sql"
|
||||
|
||||
# Modo de operación
|
||||
INTERACTIVE_MODE=true
|
||||
COMMAND=""
|
||||
|
||||
|
||||
# Función para verificar si la aplicación está ejecutándose
|
||||
check_app_running() {
|
||||
log "🔍 Verificando estado de contenedores Docker..."
|
||||
# Verificar contenedores Docker
|
||||
if docker compose ps 2>/dev/null | grep -q "dtic_bitacoras"; then
|
||||
log "✅ Contenedores encontrados ejecutándose"
|
||||
return 0
|
||||
else
|
||||
log "❌ No se encontraron contenedores ejecutándose"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para verificar conectividad a PostgreSQL
|
||||
check_db_connection() {
|
||||
log "🔍 Verificando conexión a PostgreSQL..."
|
||||
|
||||
# Método 1: Usar psql si está disponible
|
||||
if command -v psql &> /dev/null; then
|
||||
log "📡 Intentando conectar a PostgreSQL con psql..."
|
||||
if PGPASSWORD=dtic_password psql -h localhost -p $DB_PORT -U dtic_user -d dtic_bitacoras -c "SELECT 1;" &> /dev/null; then
|
||||
log "✅ Conexión a PostgreSQL exitosa (psql)"
|
||||
return 0
|
||||
else
|
||||
log "❌ Fallo en conexión a PostgreSQL (psql)"
|
||||
fi
|
||||
else
|
||||
log "⚠️ psql no disponible, intentando método alternativo con curl..."
|
||||
fi
|
||||
|
||||
# Método 2: Verificar conectividad usando la API (que internamente usa PostgreSQL)
|
||||
log "🌐 Verificando conectividad de BD a través de la API..."
|
||||
if curl -s --max-time 5 "$API_URL/health" >/dev/null 2>&1; then
|
||||
log "✅ API responde, indicando que PostgreSQL está conectado"
|
||||
return 0
|
||||
else
|
||||
log "❌ API no responde, posible problema con PostgreSQL"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para verificar si la API está accesible
|
||||
check_api_accessible() {
|
||||
log "🔍 Verificando accesibilidad de la API..."
|
||||
log "🌐 Probando endpoint: $API_URL/health"
|
||||
if curl -s --max-time 5 "$API_URL/health" >/dev/null 2>&1; then
|
||||
log "✅ API accesible"
|
||||
return 0
|
||||
else
|
||||
log "❌ API no accesible"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para verificar si el frontend está accesible
|
||||
check_frontend_accessible() {
|
||||
log "🔍 Verificando accesibilidad del frontend..."
|
||||
log "🌐 Probando URL: $FRONTEND_URL"
|
||||
if curl -s --max-time 5 "$FRONTEND_URL" >/dev/null 2>&1; then
|
||||
log "✅ Frontend accesible"
|
||||
return 0
|
||||
else
|
||||
log "❌ Frontend no accesible"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para mostrar estado actual
|
||||
show_status() {
|
||||
echo ""
|
||||
echo "📊 Estado Actual de DTIC Bitácoras:"
|
||||
echo "=================================="
|
||||
|
||||
if check_app_running; then
|
||||
echo -e "🐳 Contenedores: ${GREEN}✅ Ejecutándose${NC}"
|
||||
|
||||
if check_api_accessible; then
|
||||
echo -e "🔧 API: ${GREEN}✅ Accesible${NC} (puerto $API_PORT)"
|
||||
else
|
||||
echo -e "🔧 API: ${RED}❌ No accesible${NC} (puerto $API_PORT)"
|
||||
fi
|
||||
|
||||
if check_frontend_accessible; then
|
||||
echo -e "🌐 Frontend: ${GREEN}✅ Accesible${NC} (puerto $FRONTEND_PORT)"
|
||||
else
|
||||
echo -e "🌐 Frontend: ${RED}❌ No accesible${NC} (puerto $FRONTEND_PORT)"
|
||||
fi
|
||||
|
||||
if check_db_connection; then
|
||||
echo -e "🗄️ Base de Datos: ${GREEN}✅ Conectada${NC} (puerto $DB_PORT)"
|
||||
else
|
||||
echo -e "🗄️ Base de Datos: ${RED}❌ No conectada${NC} (puerto $DB_PORT)"
|
||||
fi
|
||||
else
|
||||
echo -e "� Contenedores: ${RED}❌ Detenidos${NC}"
|
||||
echo -e "🔧 API: ${YELLOW}❓ No verificable${NC}"
|
||||
echo -e "🌐 Frontend: ${YELLOW}❓ No verificable${NC}"
|
||||
echo -e "🗄️ Base de Datos: ${YELLOW}❓ No verificable${NC}"
|
||||
fi
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Función para mostrar menú de opciones
|
||||
show_menu() {
|
||||
echo "Opciones disponibles:"
|
||||
echo "==================="
|
||||
|
||||
local option_num=1
|
||||
|
||||
if check_app_running; then
|
||||
echo -e "${GREEN}${option_num})${NC} 🛑 Detener aplicación"
|
||||
((option_num++))
|
||||
echo -e "${GREEN}${option_num})${NC} 🔄 Reiniciar aplicación"
|
||||
((option_num++))
|
||||
echo -e "${YELLOW}${option_num})${NC} 💾 Crear backup de BD"
|
||||
((option_num++))
|
||||
echo -e "${YELLOW}${option_num})${NC} 🔄 Restaurar BD desde backup"
|
||||
((option_num++))
|
||||
else
|
||||
echo -e "${GREEN}${option_num})${NC} ▶️ Iniciar aplicación"
|
||||
((option_num++))
|
||||
echo -e "${YELLOW}${option_num})${NC} 💾 Crear backup de BD"
|
||||
((option_num++))
|
||||
echo -e "${YELLOW}${option_num})${NC} 🔄 Restaurar BD desde backup"
|
||||
((option_num++))
|
||||
fi
|
||||
|
||||
echo -e "${BLUE}${option_num})${NC} 📊 Ver estado detallado"
|
||||
((option_num++))
|
||||
echo -e "${BLUE}${option_num})${NC} 🚪 Salir"
|
||||
echo ""
|
||||
}
|
||||
|
||||
# Función para iniciar aplicación
|
||||
start_app() {
|
||||
log "🚀 Iniciando aplicación DTIC Bitácoras..."
|
||||
|
||||
if check_app_running; then
|
||||
warning "La aplicación ya está ejecutándose"
|
||||
return 0
|
||||
fi
|
||||
|
||||
# Cleanup automático antes de iniciar
|
||||
cleanup_resources
|
||||
|
||||
log "🐳 Ejecutando 'docker compose up --build -d'..."
|
||||
if docker compose up --build -d; then
|
||||
success "Aplicación iniciada"
|
||||
|
||||
# Esperar a que esté lista
|
||||
log "⏳ Esperando que los servicios estén listos..."
|
||||
sleep 5
|
||||
|
||||
local attempts=0
|
||||
while [ $attempts -lt $MAX_ATTEMPTS ]; do
|
||||
log "🔄 Intento $((attempts+1))/$MAX_ATTEMPTS de verificación de servicios..."
|
||||
if check_api_accessible && check_frontend_accessible && check_db_connection; then
|
||||
success "✅ Todos los servicios están listos"
|
||||
if [ "$INTERACTIVE_MODE" = false ]; then
|
||||
show_access_urls
|
||||
fi
|
||||
break
|
||||
fi
|
||||
sleep 3
|
||||
((attempts++))
|
||||
done
|
||||
|
||||
if [ $attempts -eq $MAX_ATTEMPTS ]; then
|
||||
warning "⚠️ Algunos servicios pueden no estar completamente listos aún"
|
||||
log "📊 Estado final de servicios:"
|
||||
check_api_accessible
|
||||
check_frontend_accessible
|
||||
check_db_connection
|
||||
fi
|
||||
else
|
||||
error "❌ Fallo al iniciar la aplicación"
|
||||
log "🔍 Verificando logs de Docker para más detalles..."
|
||||
docker compose logs --tail=20
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para detener aplicación
|
||||
stop_app() {
|
||||
log "🛑 Deteniendo aplicación DTIC Bitácoras..."
|
||||
|
||||
if ! check_app_running; then
|
||||
warning "La aplicación no está ejecutándose"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "🐳 Ejecutando 'docker compose down'..."
|
||||
if docker compose down; then
|
||||
success "Aplicación detenida"
|
||||
# Cleanup automático después de detener
|
||||
cleanup_resources
|
||||
else
|
||||
error "❌ Fallo al detener la aplicación"
|
||||
log "🔍 Verificando estado actual de contenedores..."
|
||||
docker compose ps
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para cleanup de recursos
|
||||
cleanup_resources() {
|
||||
log "🧹 Realizando limpieza automática de recursos..."
|
||||
|
||||
# Limpiar contenedores detenidos
|
||||
log "🗑️ Limpiando contenedores detenidos..."
|
||||
if docker container prune -f >/dev/null 2>&1; then
|
||||
log "✅ Contenedores huérfanos limpiados"
|
||||
else
|
||||
log "⚠️ No se pudieron limpiar contenedores huérfanos"
|
||||
fi
|
||||
|
||||
# Limpiar imágenes no utilizadas (opcional, solo si hay muchas)
|
||||
# docker image prune -f >/dev/null 2>&1
|
||||
|
||||
# Limpiar volúmenes huérfanos (con cuidado)
|
||||
log "🗂️ Limpiando volúmenes huérfanos..."
|
||||
if docker volume prune -f >/dev/null 2>&1; then
|
||||
log "✅ Volúmenes huérfanos limpiados"
|
||||
else
|
||||
log "⚠️ No se pudieron limpiar volúmenes huérfanos"
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para crear backup de la base de datos
|
||||
backup_database() {
|
||||
log "💾 Iniciando proceso de backup de base de datos..."
|
||||
|
||||
# Verificar que la aplicación esté ejecutándose
|
||||
if ! check_app_running; then
|
||||
error "❌ La aplicación no está ejecutándose. Inicia la aplicación antes de hacer backup."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Crear directorio de backups si no existe
|
||||
log "📁 Verificando directorio de backups: $BACKUP_DIR"
|
||||
mkdir -p "$BACKUP_DIR"
|
||||
|
||||
if [ ! -d "$BACKUP_DIR" ]; then
|
||||
error "❌ No se pudo crear el directorio de backups: $BACKUP_DIR"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Generar nombre del archivo de backup con timestamp
|
||||
local backup_filename
|
||||
backup_filename=$(date +"$BACKUP_FORMAT")
|
||||
local backup_path="$BACKUP_DIR/$backup_filename"
|
||||
|
||||
log "📄 Archivo de backup: $backup_path"
|
||||
|
||||
# Verificar conexión a PostgreSQL
|
||||
if ! check_db_connection; then
|
||||
error "❌ No se puede conectar a la base de datos. Verifica que PostgreSQL esté funcionando."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Obtener credenciales de la base de datos desde docker-compose
|
||||
local db_host="localhost"
|
||||
local db_port=$DB_PORT
|
||||
local db_name="dtic_bitacoras"
|
||||
local db_user="dtic_user"
|
||||
local db_password="dtic_password"
|
||||
|
||||
# Verificar si hay variables de entorno en el archivo .env
|
||||
if [ -f "backend/.env" ]; then
|
||||
source backend/.env 2>/dev/null || true
|
||||
fi
|
||||
|
||||
log "🔐 Conectando a PostgreSQL para crear backup..."
|
||||
log "📡 Host: $db_host:$db_port"
|
||||
log "🗄️ Base de datos: $db_name"
|
||||
log "👤 Usuario: $db_user"
|
||||
|
||||
# Verificar si psql está disponible localmente
|
||||
local use_docker_psql=false
|
||||
if ! command -v psql &> /dev/null; then
|
||||
log "⚠️ psql no está disponible localmente, usando Docker container..."
|
||||
use_docker_psql=true
|
||||
fi
|
||||
|
||||
# Crear el backup usando pg_dump
|
||||
log "⏳ Ejecutando pg_dump..."
|
||||
|
||||
local backup_success=false
|
||||
|
||||
if [ "$use_docker_psql" = true ]; then
|
||||
# Usar psql desde el contenedor de PostgreSQL
|
||||
log "🐳 Usando PostgreSQL client desde Docker container..."
|
||||
|
||||
# Crear el backup dentro del contenedor y copiarlo al host
|
||||
local temp_backup_name="temp_backup_$(date +%s).sql"
|
||||
if docker exec -e PGPASSWORD="$db_password" dtic_bitacoras_postgres pg_dump -h localhost -p 5432 -U "$db_user" -d "$db_name" -f "/tmp/$temp_backup_name"; then
|
||||
log "📁 Copiando backup desde contenedor al host..."
|
||||
if docker cp dtic_bitacoras_postgres:/tmp/"$temp_backup_name" "$backup_path"; then
|
||||
# Limpiar el archivo temporal del contenedor
|
||||
docker exec dtic_bitacoras_postgres rm -f "/tmp/$temp_backup_name"
|
||||
backup_success=true
|
||||
else
|
||||
error "❌ Error al copiar el backup desde el contenedor"
|
||||
fi
|
||||
else
|
||||
error "❌ Error al crear el backup dentro del contenedor"
|
||||
fi
|
||||
else
|
||||
# Usar psql local
|
||||
log "💻 Usando PostgreSQL client local..."
|
||||
if PGPASSWORD="$db_password" pg_dump -h "$db_host" -p "$db_port" -U "$db_user" -d "$db_name" -f "$backup_path"; then
|
||||
backup_success=true
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$backup_success" = true ]; then
|
||||
success "✅ Backup creado exitosamente: $backup_path"
|
||||
|
||||
# Verificar que el archivo se creó y tiene contenido
|
||||
if [ -f "$backup_path" ] && [ -s "$backup_path" ]; then
|
||||
local file_size
|
||||
file_size=$(du -h "$backup_path" | cut -f1)
|
||||
log "📊 Tamaño del backup: $file_size"
|
||||
|
||||
# Mostrar información adicional del backup
|
||||
log "🔍 Verificando integridad del backup..."
|
||||
local line_count
|
||||
line_count=$(wc -l < "$backup_path")
|
||||
log "📋 Líneas en el backup: $line_count"
|
||||
|
||||
if [ $line_count -gt 10 ]; then
|
||||
success "✅ Backup verificado correctamente"
|
||||
else
|
||||
warning "⚠️ El backup parece tener pocas líneas, pero se creó exitosamente"
|
||||
fi
|
||||
|
||||
return 0
|
||||
else
|
||||
error "❌ El archivo de backup se creó pero está vacío o no existe"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
error "❌ Error al crear el backup. Verifica la conectividad y credenciales de la base de datos."
|
||||
|
||||
# Limpiar archivo de backup parcial si existe
|
||||
if [ -f "$backup_path" ]; then
|
||||
rm -f "$backup_path"
|
||||
log "🗑️ Archivo de backup parcial eliminado"
|
||||
fi
|
||||
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para restaurar base de datos desde backup
|
||||
restore_database() {
|
||||
log "💾 Iniciando proceso de restauración de base de datos..."
|
||||
|
||||
# Verificar que la aplicación esté ejecutándose
|
||||
if ! check_app_running; then
|
||||
error "❌ La aplicación no está ejecutándose. Inicia la aplicación antes de restaurar."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Ruta del archivo de backup
|
||||
local backup_file="backups/dtic_bitacoras_backup_20251107_171026.sql"
|
||||
|
||||
# Verificar que el archivo existe
|
||||
if [ ! -f "$backup_file" ]; then
|
||||
error "❌ Archivo de backup no encontrado: $backup_file"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Verificar conexión a PostgreSQL
|
||||
if ! check_db_connection; then
|
||||
error "❌ No se puede conectar a la base de datos. Verifica que PostgreSQL esté funcionando."
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Obtener credenciales de la base de datos
|
||||
local db_name="dtic_bitacoras"
|
||||
local db_user="dtic_user"
|
||||
local db_password="dtic_password"
|
||||
|
||||
log "🔐 Conectando a PostgreSQL para restaurar..."
|
||||
log "📄 Archivo de backup: $backup_file"
|
||||
log "🗄️ Base de datos: $db_name"
|
||||
log "👤 Usuario: $db_user"
|
||||
|
||||
# Copiar archivo de backup al contenedor
|
||||
local temp_backup_name="restore_backup.sql"
|
||||
log "📁 Copiando archivo de backup al contenedor..."
|
||||
if ! docker cp "$backup_file" dtic_bitacoras_postgres:/tmp/"$temp_backup_name"; then
|
||||
error "❌ Error al copiar el archivo de backup al contenedor"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Preparar base de datos para restauración (drop y recreate)
|
||||
log "🗄️ Preparando base de datos para restauración..."
|
||||
if ! docker exec -e PGPASSWORD="$db_password" dtic_bitacoras_postgres psql -h localhost -p 5432 -U "$db_user" -d postgres -c "DROP DATABASE IF EXISTS $db_name;"; then
|
||||
error "❌ Error al eliminar la base de datos existente"
|
||||
# Limpiar archivo temporal
|
||||
docker exec dtic_bitacoras_postgres rm -f "/tmp/$temp_backup_name" 2>/dev/null || true
|
||||
return 1
|
||||
fi
|
||||
|
||||
if ! docker exec -e PGPASSWORD="$db_password" dtic_bitacoras_postgres psql -h localhost -p 5432 -U "$db_user" -d postgres -c "CREATE DATABASE $db_name;"; then
|
||||
error "❌ Error al crear la base de datos"
|
||||
# Limpiar archivo temporal
|
||||
docker exec dtic_bitacoras_postgres rm -f "/tmp/$temp_backup_name" 2>/dev/null || true
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Ejecutar restauración
|
||||
log "⏳ Ejecutando restauración desde backup..."
|
||||
if docker exec -e PGPASSWORD="$db_password" dtic_bitacoras_postgres psql -h localhost -p 5432 -U "$db_user" -d "$db_name" -f "/tmp/$temp_backup_name"; then
|
||||
success "✅ Restauración completada exitosamente"
|
||||
|
||||
# Verificar que la restauración fue exitosa
|
||||
log "🔍 Verificando restauración..."
|
||||
if docker exec -e PGPASSWORD="$db_password" dtic_bitacoras_postgres psql -h localhost -p 5432 -U "$db_user" -d "$db_name" -c "SELECT 1;" &>/dev/null; then
|
||||
success "✅ Base de datos restaurada y verificada correctamente"
|
||||
else
|
||||
warning "⚠️ La restauración se completó pero la verificación falló"
|
||||
fi
|
||||
|
||||
# Limpiar archivo temporal
|
||||
docker exec dtic_bitacoras_postgres rm -f "/tmp/$temp_backup_name"
|
||||
return 0
|
||||
else
|
||||
error "❌ Error durante la restauración"
|
||||
# Limpiar archivo temporal
|
||||
docker exec dtic_bitacoras_postgres rm -f "/tmp/$temp_backup_name"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para reiniciar aplicación
|
||||
restart_app() {
|
||||
log "🔄 Reiniciando aplicación DTIC Bitácoras..."
|
||||
|
||||
if ! check_app_running; then
|
||||
warning "La aplicación no está ejecutándose. Iniciándola..."
|
||||
start_app
|
||||
return $?
|
||||
fi
|
||||
|
||||
log "🐳 Ejecutando 'docker compose restart'..."
|
||||
if docker compose restart; then
|
||||
success "Aplicación reiniciada"
|
||||
|
||||
# Verificar que esté funcionando después del reinicio
|
||||
log "⏳ Verificando servicios después del reinicio..."
|
||||
sleep 3
|
||||
if check_api_accessible && check_frontend_accessible; then
|
||||
success "✅ Servicios verificados después del reinicio"
|
||||
else
|
||||
warning "⚠️ Algunos servicios pueden tardar en estar listos"
|
||||
log "📊 Estado de servicios post-reinicio:"
|
||||
check_api_accessible
|
||||
check_frontend_accessible
|
||||
fi
|
||||
else
|
||||
error "❌ Fallo al reiniciar la aplicación"
|
||||
log "🔍 Verificando logs de reinicio..."
|
||||
docker compose logs --tail=10
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para mostrar estado detallado
|
||||
show_detailed_status() {
|
||||
echo ""
|
||||
echo "📊 Estado Detallado del Sistema:"
|
||||
echo "==============================="
|
||||
|
||||
echo "🐳 Contenedores Docker:"
|
||||
docker compose ps
|
||||
echo ""
|
||||
|
||||
if check_app_running; then
|
||||
echo "🔧 API Health Check:"
|
||||
if check_api_accessible; then
|
||||
curl -s "$API_URL/health" | jq . 2>/dev/null || curl -s "$API_URL/health"
|
||||
else
|
||||
echo -e "${RED}❌ API no accesible${NC}"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
echo "🌐 Frontend Status:"
|
||||
if check_frontend_accessible; then
|
||||
echo -e "${GREEN}✅ Frontend accesible${NC}"
|
||||
else
|
||||
echo -e "${RED}❌ Frontend no accesible${NC}"
|
||||
fi
|
||||
echo ""
|
||||
|
||||
echo "🗄️ Base de Datos:"
|
||||
if check_db_connection; then
|
||||
echo -e "${GREEN}✅ Conexión exitosa a PostgreSQL${NC}"
|
||||
# Mostrar información básica de la BD
|
||||
if command -v psql &> /dev/null; then
|
||||
echo "Tablas en la base de datos:"
|
||||
PGPASSWORD=dtic_password psql -h localhost -p $DB_PORT -U dtic_user -d dtic_bitacoras -c "\dt" 2>/dev/null | head -10
|
||||
fi
|
||||
else
|
||||
echo -e "${RED}❌ No se puede conectar a PostgreSQL${NC}"
|
||||
fi
|
||||
echo ""
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para mostrar URLs de acceso
|
||||
show_access_urls() {
|
||||
echo ""
|
||||
echo "🌐 URLs de Acceso:"
|
||||
echo "================="
|
||||
|
||||
if check_api_accessible; then
|
||||
echo -e "🔧 API: ${GREEN}$API_URL${NC}"
|
||||
echo -e " Health Check: ${GREEN}$API_URL/health${NC}"
|
||||
else
|
||||
echo -e "🔧 API: ${RED}$API_URL${NC} (no accesible)"
|
||||
fi
|
||||
|
||||
if check_frontend_accessible; then
|
||||
echo -e "🌐 Frontend: ${GREEN}$FRONTEND_URL${NC}"
|
||||
else
|
||||
echo -e "🌐 Frontend: ${RED}$FRONTEND_URL${NC} (no accesible)"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo -e "${BLUE}💡 Para acceder a la aplicación, use la URL del Frontend en su navegador${NC}"
|
||||
}
|
||||
|
||||
# Función para procesar parámetros de línea de comandos
|
||||
parse_command() {
|
||||
case "$1" in
|
||||
start)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="start"
|
||||
;;
|
||||
stop)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="stop"
|
||||
;;
|
||||
restart)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="restart"
|
||||
;;
|
||||
status)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="status"
|
||||
;;
|
||||
bd-backup)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="backup"
|
||||
;;
|
||||
bd-restore)
|
||||
INTERACTIVE_MODE=false
|
||||
COMMAND="restore"
|
||||
;;
|
||||
*)
|
||||
INTERACTIVE_MODE=true
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Función principal
|
||||
main() {
|
||||
# Ejecutar configuración inicial solo en la primera ejecución
|
||||
if is_first_run; then
|
||||
"$SCRIPT_DIR/app-run_deps.sh" initial-setup || exit 1
|
||||
fi
|
||||
|
||||
# Procesar parámetros de línea de comandos
|
||||
parse_command "$1"
|
||||
|
||||
if [ "$INTERACTIVE_MODE" = false ]; then
|
||||
# Modo no interactivo
|
||||
case "$COMMAND" in
|
||||
start)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
start_app
|
||||
;;
|
||||
stop)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
stop_app
|
||||
;;
|
||||
restart)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
restart_app
|
||||
;;
|
||||
status)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
show_status
|
||||
show_access_urls
|
||||
;;
|
||||
backup)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
backup_database
|
||||
;;
|
||||
restore)
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
restore_database
|
||||
;;
|
||||
esac
|
||||
else
|
||||
# Modo interactivo (comportamiento original)
|
||||
echo ""
|
||||
echo "🚀 DTIC Bitácoras - Gestor Inteligente"
|
||||
echo "====================================="
|
||||
echo ""
|
||||
|
||||
# Mostrar estado inicial
|
||||
show_status
|
||||
|
||||
# Bucle principal
|
||||
while true; do
|
||||
show_menu
|
||||
|
||||
# Determinar rango de opciones válido
|
||||
local max_option
|
||||
if check_app_running; then
|
||||
max_option=6 # 1:detener, 2:reiniciar, 3:backup, 4:restore, 5:estado, 6:salir
|
||||
read -p "Seleccione una opción (1-6): " choice
|
||||
else
|
||||
max_option=5 # 1:iniciar, 2:backup, 3:restore, 4:estado, 5:salir
|
||||
read -p "Seleccione una opción (1-5): " choice
|
||||
fi
|
||||
|
||||
case $choice in
|
||||
1)
|
||||
if check_app_running; then
|
||||
stop_app
|
||||
else
|
||||
start_app
|
||||
fi
|
||||
echo ""
|
||||
read -p "Presione Enter para continuar..."
|
||||
;;
|
||||
2)
|
||||
if check_app_running; then
|
||||
restart_app
|
||||
else
|
||||
backup_database
|
||||
fi
|
||||
echo ""
|
||||
read -p "Presione Enter para continuar..."
|
||||
;;
|
||||
3)
|
||||
if check_app_running; then
|
||||
backup_database
|
||||
else
|
||||
restore_database
|
||||
fi
|
||||
echo ""
|
||||
read -p "Presione Enter para continuar..."
|
||||
;;
|
||||
4)
|
||||
if check_app_running; then
|
||||
restore_database
|
||||
else
|
||||
show_detailed_status
|
||||
fi
|
||||
echo ""
|
||||
read -p "Presione Enter para continuar..."
|
||||
;;
|
||||
5)
|
||||
if check_app_running; then
|
||||
show_detailed_status
|
||||
else
|
||||
echo ""
|
||||
log "¡Hasta luego!"
|
||||
break
|
||||
fi
|
||||
echo ""
|
||||
read -p "Presione Enter para continuar..."
|
||||
;;
|
||||
6)
|
||||
if check_app_running; then
|
||||
echo ""
|
||||
log "¡Hasta luego!"
|
||||
break
|
||||
else
|
||||
error "Opción inválida."
|
||||
sleep 2
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
error "Opción inválida."
|
||||
sleep 2
|
||||
;;
|
||||
esac
|
||||
|
||||
# Mostrar estado actualizado y URLs después de cada acción
|
||||
show_status
|
||||
show_access_urls
|
||||
done
|
||||
fi
|
||||
}
|
||||
|
||||
# Verificar dependencias antes de continuar
|
||||
"$SCRIPT_DIR/app-run_deps.sh" check-docker-deps || exit 1
|
||||
|
||||
# Verificar que estamos en el directorio correcto
|
||||
if [ ! -f "docker-compose.yml" ]; then
|
||||
error "No se encuentra docker-compose.yml. Asegúrese de ejecutar este script desde el directorio _app-bitacoras"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Ejecutar función principal con parámetros
|
||||
main "$@"
|
||||
@@ -1,249 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# DTIC Bitácoras - Gestión de Dependencias
|
||||
# =============================================================================
|
||||
#
|
||||
# Script modular para gestión de dependencias del sistema
|
||||
# Actúa como API: recibe argumentos CLI y retorna códigos de salida
|
||||
#
|
||||
# Uso:
|
||||
# ./app-run_deps.sh check-host-deps # Verifica dependencias del host
|
||||
# ./app-run_deps.sh install-host-deps # Instala dependencias del host
|
||||
# ./app-run_deps.sh check-docker-deps # Verifica dependencias Docker
|
||||
# ./app-run_deps.sh initial-setup # Ejecuta configuración inicial
|
||||
#
|
||||
# Códigos de salida:
|
||||
# 0: Éxito
|
||||
# 1: Fallo
|
||||
#
|
||||
# Versión: 1.0
|
||||
# Fecha: 2025-11-28
|
||||
# =============================================================================
|
||||
|
||||
# Cargar biblioteca compartida
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
source "$SCRIPT_DIR/app-run_lib.sh"
|
||||
|
||||
# Dependencias del host con sus comandos de instalación por sistema operativo
|
||||
declare -A HOST_DEPENDENCIES=(
|
||||
[curl]="Utilizado para verificar conectividad de servicios"
|
||||
[jq]="Utilizado para formatear respuestas JSON (opcional)"
|
||||
)
|
||||
|
||||
declare -A INSTALL_COMMANDS_LINUX=(
|
||||
[curl]="apt-get install -y curl"
|
||||
[jq]="apt-get install -y jq"
|
||||
)
|
||||
|
||||
declare -A INSTALL_COMMANDS_MACOS=(
|
||||
[curl]="brew install curl"
|
||||
[jq]="brew install jq"
|
||||
)
|
||||
|
||||
# Función para obtener el gestor de paquetes del sistema
|
||||
get_package_manager() {
|
||||
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
|
||||
if command -v apt-get &> /dev/null; then
|
||||
echo "apt-get"
|
||||
elif command -v yum &> /dev/null; then
|
||||
echo "yum"
|
||||
elif command -v dnf &> /dev/null; then
|
||||
echo "dnf"
|
||||
else
|
||||
echo "none"
|
||||
fi
|
||||
elif [[ "$OSTYPE" == "darwin"* ]]; then
|
||||
if command -v brew &> /dev/null; then
|
||||
echo "brew"
|
||||
else
|
||||
echo "none"
|
||||
fi
|
||||
else
|
||||
echo "unsupported"
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para verificar dependencias del host
|
||||
check_host_dependencies() {
|
||||
log "🔍 Verificando dependencias del sistema host..."
|
||||
local missing_deps=()
|
||||
|
||||
for dep in "${!HOST_DEPENDENCIES[@]}"; do
|
||||
if ! command -v "$dep" &> /dev/null; then
|
||||
missing_deps+=("$dep")
|
||||
fi
|
||||
done
|
||||
|
||||
if [ ${#missing_deps[@]} -eq 0 ]; then
|
||||
log "✅ Dependencias del host verificadas correctamente"
|
||||
return 0
|
||||
else
|
||||
log "⚠️ Dependencias faltantes detectadas: ${missing_deps[*]}"
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
# Función para instalar dependencias automáticamente
|
||||
install_host_dependencies() {
|
||||
log "🛠️ Instalando dependencias del sistema host..."
|
||||
local package_manager=$(get_package_manager)
|
||||
|
||||
case "$package_manager" in
|
||||
"apt-get"|"yum"|"dnf")
|
||||
sudo "$package_manager" update
|
||||
;;
|
||||
"brew")
|
||||
# brew no necesita update para install
|
||||
;;
|
||||
"none")
|
||||
error "❌ No se encontró un gestor de paquetes compatible"
|
||||
return 1
|
||||
;;
|
||||
"unsupported")
|
||||
error "❌ Sistema operativo no soportado para instalación automática"
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
|
||||
for dep in "${!HOST_DEPENDENCIES[@]}"; do
|
||||
if ! command -v "$dep" &> /dev/null; then
|
||||
log "📦 Instalando $dep..."
|
||||
|
||||
case "$package_manager" in
|
||||
"apt-get")
|
||||
sudo apt-get install -y "$dep"
|
||||
;;
|
||||
"yum")
|
||||
sudo yum install -y "$dep"
|
||||
;;
|
||||
"dnf")
|
||||
sudo dnf install -y "$dep"
|
||||
;;
|
||||
"brew")
|
||||
brew install "$dep"
|
||||
;;
|
||||
*)
|
||||
error "❌ No se puede instalar $dep: $package_manager no soportado"
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
if command -v "$dep" &> /dev/null; then
|
||||
success "✅ $dep instalado correctamente"
|
||||
else
|
||||
error "❌ Error al instalar $dep"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
|
||||
return 0
|
||||
}
|
||||
|
||||
# Función para verificar dependencias Docker
|
||||
check_docker_dependencies() {
|
||||
log "🔍 Verificando dependencias del sistema..."
|
||||
local missing_deps=()
|
||||
|
||||
if ! command -v docker &> /dev/null; then
|
||||
missing_deps+=("docker")
|
||||
fi
|
||||
|
||||
if ! command -v docker &> /dev/null || ! docker compose version &> /dev/null; then
|
||||
missing_deps+=("docker-compose")
|
||||
fi
|
||||
|
||||
if [ ${#missing_deps[@]} -ne 0 ]; then
|
||||
error "Dependencias faltantes: ${missing_deps[*]}"
|
||||
error "Por favor instala las dependencias requeridas antes de continuar"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Verificar que Docker esté ejecutándose
|
||||
log "🔍 Verificando que Docker daemon esté ejecutándose..."
|
||||
if ! docker info &> /dev/null; then
|
||||
error "Docker daemon no está ejecutándose"
|
||||
error "Por favor inicia Docker y vuelve a intentar"
|
||||
return 1
|
||||
fi
|
||||
|
||||
# Verificar que docker-compose funcione
|
||||
log "🔍 Verificando funcionalidad de docker-compose..."
|
||||
if ! docker compose version &> /dev/null; then
|
||||
error "docker-compose no funciona correctamente"
|
||||
return 1
|
||||
fi
|
||||
|
||||
log "✅ Todas las dependencias verificadas correctamente"
|
||||
return 0
|
||||
}
|
||||
|
||||
# Función para ejecutar configuración inicial
|
||||
run_initial_setup() {
|
||||
echo ""
|
||||
echo "🚀 Configuración Inicial de DTIC Bitácoras"
|
||||
echo "========================================="
|
||||
echo ""
|
||||
log "🔧 Esta es la primera vez que ejecutas el script en este sistema"
|
||||
log "🛠️ Se verificarán e instalarán las dependencias necesarias"
|
||||
echo ""
|
||||
|
||||
# Verificar dependencias del host
|
||||
if ! check_host_dependencies; then
|
||||
echo ""
|
||||
warning "⚠️ Se detectaron dependencias faltantes en el sistema host:"
|
||||
echo ""
|
||||
echo "Dependencias que se pueden instalar automáticamente:"
|
||||
for dep in "${!HOST_DEPENDENCIES[@]}"; do
|
||||
echo " • $dep - ${HOST_DEPENDENCIES[$dep]}"
|
||||
done
|
||||
echo ""
|
||||
echo "Sistemas soportados:"
|
||||
echo " • Linux (Ubuntu/Debian, CentOS/RHEL, Fedora)"
|
||||
echo " • macOS (con Homebrew)"
|
||||
echo ""
|
||||
|
||||
# En modo API, siempre intentar instalar automáticamente
|
||||
log "Ejecutando instalación automática de dependencias..."
|
||||
if install_host_dependencies; then
|
||||
success "✅ Dependencias instaladas correctamente"
|
||||
else
|
||||
error "❌ Error al instalar algunas dependencias"
|
||||
echo ""
|
||||
echo "Puedes instalar manualmente en:"
|
||||
echo " • curl: https://curl.se/download.html"
|
||||
echo " • jq: https://stedolan.github.io/jq/download/"
|
||||
return 1
|
||||
fi
|
||||
else
|
||||
log "✅ Todas las dependencias ya están instaladas"
|
||||
fi
|
||||
|
||||
# Marcar configuración como completada
|
||||
mark_setup_complete
|
||||
echo ""
|
||||
success "🎉 Configuración inicial completada"
|
||||
echo ""
|
||||
sleep 2
|
||||
return 0
|
||||
}
|
||||
|
||||
# Procesar argumentos CLI
|
||||
case "$1" in
|
||||
check-host-deps)
|
||||
check_host_dependencies
|
||||
;;
|
||||
install-host-deps)
|
||||
install_host_dependencies
|
||||
;;
|
||||
check-docker-deps)
|
||||
check_docker_dependencies
|
||||
;;
|
||||
initial-setup)
|
||||
run_initial_setup
|
||||
;;
|
||||
*)
|
||||
error "Uso: $0 {check-host-deps|install-host-deps|check-docker-deps|initial-setup}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@@ -1,38 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
# =============================================================================
|
||||
# DTIC Bitácoras - Biblioteca de Funciones Compartidas
|
||||
# =============================================================================
|
||||
#
|
||||
# Biblioteca de funciones reutilizables para scripts de gestión de aplicación
|
||||
#
|
||||
# Versión: 1.0
|
||||
# Fecha: 2025-11-28
|
||||
# =============================================================================
|
||||
|
||||
# Colores para salida
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m'
|
||||
|
||||
# Archivo para recordar si ya se ejecutó la configuración inicial
|
||||
SETUP_MARKER=".dtic_setup_done"
|
||||
|
||||
# Funciones de logging
|
||||
log() { echo -e "${BLUE}[INFO]${NC} $1"; }
|
||||
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
|
||||
error() { echo -e "${RED}[ERROR]${NC} $1"; }
|
||||
warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
|
||||
|
||||
# Función para verificar si es la primera ejecución
|
||||
is_first_run() {
|
||||
[ ! -f "$SETUP_MARKER" ]
|
||||
}
|
||||
|
||||
# Función para marcar que la configuración inicial se completó
|
||||
mark_setup_complete() {
|
||||
touch "$SETUP_MARKER"
|
||||
log "📝 Configuración inicial completada"
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
FROM node:18-alpine
|
||||
|
||||
# Instalar Docker CLI para poder ejecutar comandos Docker desde el contenedor
|
||||
RUN apk add --no-cache docker-cli
|
||||
|
||||
# Establecer directorio de trabajo
|
||||
WORKDIR /app
|
||||
|
||||
# Copiar archivos de configuración de paquetes
|
||||
COPY package*.json ./
|
||||
|
||||
# Instalar dependencias
|
||||
RUN npm install --omit=dev
|
||||
|
||||
# Copiar código fuente
|
||||
COPY . .
|
||||
|
||||
# Crear directorio para logs
|
||||
RUN mkdir -p logs
|
||||
|
||||
# Exponer puerto
|
||||
EXPOSE 3001
|
||||
|
||||
# Comando para ejecutar la aplicación
|
||||
CMD ["npm", "start"]
|
||||
-5843
File diff suppressed because it is too large
Load Diff
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"name": "dtic-bitacoras-api",
|
||||
"version": "2.1.2",
|
||||
"description": "API backend para DTIC Bitácoras - Sistema de gestión de técnicos y tareas",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"dev": "nodemon src/server.js",
|
||||
"test": "jest",
|
||||
"migrate": "node scripts/migrate.js"
|
||||
},
|
||||
"keywords": [
|
||||
"dtic",
|
||||
"bitacoras",
|
||||
"api",
|
||||
"nodejs",
|
||||
"express"
|
||||
],
|
||||
"author": "Lic. Ricardo MONLA - Departamento de Servidores, Dirección de TIC, Universidad Tecnológica Nacional - Facultad Regional La Rioja",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bcryptjs": "^2.4.3",
|
||||
"compression": "^1.7.4",
|
||||
"cors": "^2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^7.1.5",
|
||||
"express-validator": "^7.0.1",
|
||||
"helmet": "^7.1.0",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"multer": "^1.4.5-lts.1",
|
||||
"pdf-parse": "^1.1.1",
|
||||
"pg": "^8.11.3",
|
||||
"winston": "^3.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jest": "^29.7.0",
|
||||
"nodemon": "^3.0.2",
|
||||
"supertest": "^6.3.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
async function checkTasks() {
|
||||
try {
|
||||
console.log('📊 VERIFICANDO TAREAS EN BASE DE DATOS');
|
||||
console.log('=====================================');
|
||||
|
||||
const result = await executeQuery(
|
||||
'SELECT dtic_id, title, status, priority, created_at FROM dtic.tareas ORDER BY created_at DESC LIMIT 10'
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
console.log('❌ No se encontraron tareas en la base de datos');
|
||||
return;
|
||||
}
|
||||
|
||||
console.log(`✅ Encontradas ${result.rows.length} tareas:`);
|
||||
console.log('');
|
||||
|
||||
result.rows.forEach((task, index) => {
|
||||
console.log(`${index + 1}. ${task.dtic_id} - ${task.title}`);
|
||||
console.log(` Estado: ${task.status} | Prioridad: ${task.priority}`);
|
||||
console.log(` Creado: ${new Date(task.created_at).toLocaleString('es-AR')}`);
|
||||
console.log('');
|
||||
});
|
||||
|
||||
// Verificar total
|
||||
const countResult = await executeQuery('SELECT COUNT(*) as total FROM dtic.tareas');
|
||||
console.log(`📈 Total de tareas en BD: ${countResult.rows[0].total}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error verificando datos:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
checkTasks();
|
||||
}
|
||||
|
||||
module.exports = { checkTasks };
|
||||
@@ -1,50 +0,0 @@
|
||||
const { executeQuery } = require('./database');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
async function checkPassword() {
|
||||
try {
|
||||
console.log('🔐 VERIFICANDO CONTRASEÑA DEL USUARIO');
|
||||
console.log('=====================================');
|
||||
|
||||
const result = await executeQuery(
|
||||
'SELECT password_hash FROM dtic.tecnicos WHERE email = $1',
|
||||
['rmonla@frlr.utn.edu.ar']
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
console.log('❌ Usuario no encontrado');
|
||||
return;
|
||||
}
|
||||
|
||||
const hash = result.rows[0].password_hash;
|
||||
console.log(`Hash encontrado: ${hash ? 'SÍ' : 'NO'}`);
|
||||
|
||||
if (hash) {
|
||||
const testPasswords = ['utn123', 'password', 'admin123', '123456'];
|
||||
|
||||
console.log('');
|
||||
console.log('🧪 Probando contraseñas comunes:');
|
||||
|
||||
for (const password of testPasswords) {
|
||||
const isValid = await bcrypt.compare(password, hash);
|
||||
console.log(` "${password}": ${isValid ? '✅ VÁLIDA' : '❌ Inválida'}`);
|
||||
}
|
||||
|
||||
console.log('');
|
||||
console.log('💡 Si ninguna contraseña funciona, el usuario necesita reset de contraseña');
|
||||
console.log(' O la contraseña fue cambiada desde la última vez que se configuró');
|
||||
|
||||
} else {
|
||||
console.log('⚠️ El usuario no tiene contraseña configurada');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error verificando contraseña:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
checkPassword();
|
||||
}
|
||||
|
||||
module.exports = { checkPassword };
|
||||
@@ -1,52 +0,0 @@
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
async function checkUser() {
|
||||
try {
|
||||
console.log('🔍 VERIFICANDO USUARIO: rmonla@frlr.utn.edu.ar');
|
||||
console.log('==============================================');
|
||||
|
||||
const result = await executeQuery(
|
||||
'SELECT id, dtic_id, email, first_name, last_name, password_hash, is_active, role FROM dtic.tecnicos WHERE email = $1',
|
||||
['rmonla@frlr.utn.edu.ar']
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
console.log('❌ Usuario NO encontrado en la base de datos');
|
||||
console.log('');
|
||||
console.log('🔧 POSIBLES SOLUCIONES:');
|
||||
console.log('1. El usuario no existe - crear usuario');
|
||||
console.log('2. Email incorrecto - verificar ortografía');
|
||||
console.log('3. Base de datos vacía - cargar datos iniciales');
|
||||
return;
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
console.log('✅ Usuario encontrado:');
|
||||
console.log(` ID: ${user.id}`);
|
||||
console.log(` DTIC ID: ${user.dtic_id}`);
|
||||
console.log(` Email: ${user.email}`);
|
||||
console.log(` Nombre: ${user.first_name} ${user.last_name}`);
|
||||
console.log(` Rol: ${user.role}`);
|
||||
console.log(` Activo: ${user.is_active ? 'SÍ' : 'NO'}`);
|
||||
console.log(` Tiene contraseña: ${!!user.password_hash ? 'SÍ' : 'NO'}`);
|
||||
|
||||
if (!user.is_active) {
|
||||
console.log('');
|
||||
console.log('⚠️ USUARIO INACTIVO - No puede iniciar sesión');
|
||||
}
|
||||
|
||||
if (!user.password_hash) {
|
||||
console.log('');
|
||||
console.log('⚠️ USUARIO SIN CONTRASEÑA - Necesita configuración inicial');
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error verificando usuario:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
checkUser();
|
||||
}
|
||||
|
||||
module.exports = { checkUser };
|
||||
@@ -1,31 +0,0 @@
|
||||
const { Pool } = require('pg');
|
||||
require('dotenv').config();
|
||||
|
||||
// Configuración de PostgreSQL
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
});
|
||||
|
||||
// Establecer search_path para incluir el esquema dtic
|
||||
pool.on('connect', (client) => {
|
||||
client.query('SET search_path TO dtic, public');
|
||||
});
|
||||
|
||||
// Función helper para ejecutar queries
|
||||
const executeQuery = async (query, params = []) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await client.query(query, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Database query error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { pool, executeQuery };
|
||||
@@ -1,245 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
// Función para leer todos los archivos de bitácoras
|
||||
function readBitacoraFiles() {
|
||||
// Dentro del contenedor Docker, el path es diferente
|
||||
const bitacorasDir = path.join('/host', '_bitacoras_anteriores');
|
||||
console.log('📂 Buscando bitácoras en:', bitacorasDir);
|
||||
|
||||
const files = fs.readdirSync(bitacorasDir);
|
||||
const bitacoraFiles = files.filter(file => file.startsWith('bitacora_'));
|
||||
|
||||
console.log(`📄 Encontrados ${bitacoraFiles.length} archivos de bitácora`);
|
||||
|
||||
const data = {
|
||||
recursos: [],
|
||||
usuarios: [],
|
||||
tareas: []
|
||||
};
|
||||
|
||||
bitacoraFiles.forEach(file => {
|
||||
const filePath = path.join(bitacorasDir, file);
|
||||
const content = fs.readFileSync(filePath, 'utf8');
|
||||
|
||||
// Extraer recursos mencionados
|
||||
extractRecursos(content, data.recursos);
|
||||
|
||||
// Extraer usuarios mencionados
|
||||
extractUsuarios(content, data.usuarios);
|
||||
|
||||
// Extraer tareas mencionadas
|
||||
extractTareas(content, data.tareas);
|
||||
});
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
// Función para extraer recursos del contenido
|
||||
function extractRecursos(content, recursos) {
|
||||
// Patrones para identificar recursos
|
||||
const resourcePatterns = [
|
||||
/srvv-([A-Z0-9-]+)/g, // srvv-SITIO, srvv-DTIC, etc.
|
||||
/dtic-([A-Z0-9-]+)/g, // dtic-BITÁCORAS, dtic-UPTIME, etc.
|
||||
/srv-([A-Z0-9-]+)/g, // srv-PMOX1, srv-NS8, etc.
|
||||
/pcv-([A-Z0-9-]+)/g, // pcv-DASU1, pcv-DASU2, etc.
|
||||
/x_srvv-([A-Z0-9-]+)/g // x_srvv-TORII, etc.
|
||||
];
|
||||
|
||||
resourcePatterns.forEach(pattern => {
|
||||
let match;
|
||||
while ((match = pattern.exec(content)) !== null) {
|
||||
const resourceName = match[0];
|
||||
if (!recursos.find(r => r.name === resourceName)) {
|
||||
recursos.push({
|
||||
name: resourceName,
|
||||
category: categorizeResource(resourceName),
|
||||
description: `Recurso identificado en bitácoras históricas`,
|
||||
status: 'available',
|
||||
location: 'DTIC - UTN La Rioja'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Función para categorizar recursos
|
||||
function categorizeResource(name) {
|
||||
if (name.startsWith('srvv-') || name.startsWith('srv-')) {
|
||||
return 'hardware'; // Servidores virtuales o físicos
|
||||
} else if (name.startsWith('dtic-')) {
|
||||
return 'facilities'; // Servicios DTIC
|
||||
} else if (name.startsWith('pcv-')) {
|
||||
return 'network'; // Componentes de red
|
||||
} else {
|
||||
return 'tools'; // Otros
|
||||
}
|
||||
}
|
||||
|
||||
// Función para extraer usuarios del contenido
|
||||
function extractUsuarios(content, usuarios) {
|
||||
// Patrones para identificar usuarios
|
||||
const userPatterns = [
|
||||
/rmonla/g, // Ricardo MONLA
|
||||
/jessisanchez/g, // Jessica Sánchez
|
||||
/silviaromero/g, // Silvia Romero
|
||||
/sofiaemelivega/g, // Sofía Emeli Vega
|
||||
/silromero/g // Silvia Romero (variante)
|
||||
];
|
||||
|
||||
userPatterns.forEach(pattern => {
|
||||
let match;
|
||||
while ((match = pattern.exec(content)) !== null) {
|
||||
const userId = match[0];
|
||||
if (!usuarios.find(u => u.email === `${userId}@frlr.utn.edu.ar`)) {
|
||||
const userInfo = getUserInfo(userId);
|
||||
usuarios.push({
|
||||
first_name: userInfo.firstName,
|
||||
last_name: userInfo.lastName,
|
||||
email: `${userId}@frlr.utn.edu.ar`,
|
||||
department: 'DTIC',
|
||||
position: userInfo.position
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Función para obtener información de usuario
|
||||
function getUserInfo(userId) {
|
||||
const userMap = {
|
||||
'rmonla': { firstName: 'Ricardo', lastName: 'MONLA', position: 'Responsable DTIC' },
|
||||
'jessisanchez': { firstName: 'Jessica', lastName: 'SÁNCHEZ', position: 'Administradora' },
|
||||
'silviaromero': { firstName: 'Silvia', lastName: 'ROMERO', position: 'Administradora' },
|
||||
'sofiaemelivega': { firstName: 'Sofía Emeli', lastName: 'VEGA', position: 'Usuario' },
|
||||
'silromero': { firstName: 'Silvia', lastName: 'ROMERO', position: 'Administradora' }
|
||||
};
|
||||
|
||||
return userMap[userId] || { firstName: userId, lastName: 'Usuario', position: 'Usuario' };
|
||||
}
|
||||
|
||||
// Función para extraer tareas del contenido
|
||||
function extractTareas(content, tareas) {
|
||||
// Buscar patrones de tareas en las bitácoras
|
||||
const taskPatterns = [
|
||||
/Actualización.*sistema operativo/g,
|
||||
/Configuración.*DNS/g,
|
||||
/Backup.*VM/g,
|
||||
/Instalación.*software/g,
|
||||
/Mantenimiento.*servidor/g,
|
||||
/Resolución.*problema/g,
|
||||
/Creación.*usuario/g,
|
||||
/Actualización.*servicio/g
|
||||
];
|
||||
|
||||
taskPatterns.forEach(pattern => {
|
||||
let match;
|
||||
while ((match = pattern.exec(content)) !== null) {
|
||||
const taskTitle = match[0];
|
||||
if (!tareas.find(t => t.title === taskTitle)) {
|
||||
tareas.push({
|
||||
title: taskTitle,
|
||||
description: `Tarea identificada en bitácoras históricas`,
|
||||
status: 'completed',
|
||||
priority: 'medium'
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Función principal para procesar los datos
|
||||
async function processRealData() {
|
||||
try {
|
||||
console.log('🔍 Extrayendo datos reales de las bitácoras...');
|
||||
|
||||
const data = readBitacoraFiles();
|
||||
|
||||
console.log(`📊 Datos extraídos:`);
|
||||
console.log(` - Recursos: ${data.recursos.length}`);
|
||||
console.log(` - Usuarios: ${data.usuarios.length}`);
|
||||
console.log(` - Tareas: ${data.tareas.length}`);
|
||||
|
||||
// Limpiar datos existentes
|
||||
console.log('🧹 Eliminando datos existentes...');
|
||||
await clearExistingData();
|
||||
|
||||
// Insertar nuevos datos
|
||||
console.log('📥 Insertando datos reales...');
|
||||
await insertRealData(data);
|
||||
|
||||
console.log('✅ Proceso completado exitosamente!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error procesando datos reales:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Función para limpiar datos existentes
|
||||
async function clearExistingData() {
|
||||
try {
|
||||
// Eliminar en orden correcto (por dependencias)
|
||||
await executeQuery('DELETE FROM dtic.recurso_historial');
|
||||
await executeQuery('DELETE FROM dtic.recurso_asignaciones');
|
||||
await executeQuery('DELETE FROM dtic.tareas');
|
||||
await executeQuery('DELETE FROM dtic.recursos');
|
||||
await executeQuery('DELETE FROM dtic.usuarios_relacionados');
|
||||
|
||||
console.log('✅ Datos existentes eliminados');
|
||||
} catch (error) {
|
||||
console.error('❌ Error eliminando datos existentes:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Función para insertar datos reales
|
||||
async function insertRealData(data) {
|
||||
try {
|
||||
// Insertar recursos
|
||||
for (let i = 0; i < data.recursos.length; i++) {
|
||||
const recurso = data.recursos[i];
|
||||
const dticId = `REC-${String(i + 1).padStart(4, '0')}`;
|
||||
|
||||
await executeQuery(`
|
||||
INSERT INTO dtic.recursos (dtic_id, name, description, category, status, location)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`, [dticId, recurso.name, recurso.description, recurso.category, recurso.status, recurso.location]);
|
||||
}
|
||||
|
||||
// Insertar usuarios
|
||||
for (let i = 0; i < data.usuarios.length; i++) {
|
||||
const usuario = data.usuarios[i];
|
||||
const dticId = `USR-${String(i + 1).padStart(4, '0')}`;
|
||||
|
||||
await executeQuery(`
|
||||
INSERT INTO dtic.usuarios_relacionados (dtic_id, first_name, last_name, email, department, position)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
`, [dticId, usuario.first_name, usuario.last_name, usuario.email, usuario.department, usuario.position]);
|
||||
}
|
||||
|
||||
// Insertar tareas
|
||||
for (let i = 0; i < data.tareas.length; i++) {
|
||||
const tarea = data.tareas[i];
|
||||
const dticId = `TAR-${String(i + 1).padStart(4, '0')}`;
|
||||
|
||||
await executeQuery(`
|
||||
INSERT INTO dtic.tareas (dtic_id, title, description, status, priority)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`, [dticId, tarea.title, tarea.description, tarea.status, tarea.priority]);
|
||||
}
|
||||
|
||||
console.log('✅ Datos reales insertados correctamente');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error insertando datos reales:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Ejecutar si se llama directamente
|
||||
if (require.main === module) {
|
||||
processRealData();
|
||||
}
|
||||
|
||||
module.exports = { processRealData, readBitacoraFiles };
|
||||
@@ -1,173 +0,0 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const pdf = require('pdf-parse');
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
async function loadResourcesFromPDF() {
|
||||
try {
|
||||
// Path to the PDF file
|
||||
const pdfPath = path.join(__dirname, '../../../_basurero/RECURSOs.pdf');
|
||||
|
||||
// Read and parse the PDF
|
||||
const dataBuffer = fs.readFileSync(pdfPath);
|
||||
const data = await pdf(dataBuffer);
|
||||
const text = data.text;
|
||||
|
||||
console.log('Extracted text from PDF:');
|
||||
console.log(text);
|
||||
|
||||
// Parse the text into resource objects
|
||||
const resources = parseResources(text);
|
||||
|
||||
console.log(`Parsed ${resources.length} resources from PDF`);
|
||||
|
||||
// Insert resources into database in batch to avoid pool exhaustion
|
||||
const { insertedCount, skippedCount } = await insertResourcesBatch(resources);
|
||||
|
||||
console.log(`Total resources processed: ${resources.length}`);
|
||||
console.log(`Successfully inserted: ${insertedCount}`);
|
||||
console.log(`Skipped (duplicates): ${skippedCount}`);
|
||||
} catch (error) {
|
||||
console.error('Error loading resources from PDF:', error);
|
||||
}
|
||||
}
|
||||
|
||||
function parseResources(text) {
|
||||
const resources = [];
|
||||
const lines = text.split('\n').map(line => line.trim()).filter(line => line && !line.startsWith('lstRECUsDETALLES'));
|
||||
|
||||
let currentEntry = '';
|
||||
for (const line of lines) {
|
||||
if (line.includes('|')) {
|
||||
if (currentEntry) {
|
||||
const resource = parseResourceLine(currentEntry);
|
||||
if (resource) resources.push(resource);
|
||||
}
|
||||
currentEntry = line;
|
||||
} else {
|
||||
currentEntry += '\n' + line;
|
||||
}
|
||||
}
|
||||
if (currentEntry) {
|
||||
const resource = parseResourceLine(currentEntry);
|
||||
if (resource) resources.push(resource);
|
||||
}
|
||||
|
||||
return resources;
|
||||
}
|
||||
|
||||
function parseResourceLine(entry) {
|
||||
// Example: ap-GOB-02 | GOB-PasilloAp 2 en Gobierno; SN: F3608; #AP001
|
||||
const parts = entry.split('|');
|
||||
if (parts.length < 2) return null;
|
||||
|
||||
const name = parts[0].trim();
|
||||
const rest = parts.slice(1).join('|').trim();
|
||||
|
||||
// Extract ID from end
|
||||
const idMatch = rest.match(/#(\w+)$/);
|
||||
const dtic_id = idMatch ? idMatch[1] : null;
|
||||
|
||||
if (!dtic_id) return null; // Skip entries without valid dtic_id
|
||||
|
||||
// Remove ID from rest
|
||||
const details = rest.replace(/\s*#(\w+)$/, '').trim();
|
||||
|
||||
const resource = {
|
||||
dtic_id: dtic_id,
|
||||
name: name,
|
||||
description: details,
|
||||
category: 'hardware', // default
|
||||
status: 'available', // default
|
||||
location: null,
|
||||
serial_number: null,
|
||||
model: null,
|
||||
technical_specs: {}
|
||||
};
|
||||
|
||||
// Infer category from name prefix
|
||||
const code = name.toLowerCase();
|
||||
if (code.startsWith('ap-') || code.startsWith('sw-') || code.startsWith('rut-')) {
|
||||
resource.category = 'network';
|
||||
} else if (code.startsWith('pc-') || code.startsWith('imp-') || code.startsWith('tv') || code.startsWith('tbl-') || code.startsWith('dsp-') || code.startsWith('dvr-')) {
|
||||
resource.category = 'hardware';
|
||||
} else if (code.startsWith('srv') || code.startsWith('pcv-') || code.startsWith('netb-')) {
|
||||
resource.category = 'software';
|
||||
} else if (code.startsWith('cam-') || code.startsWith('cel-')) {
|
||||
resource.category = 'security';
|
||||
} else if (code.startsWith('not-')) {
|
||||
resource.category = 'hardware'; // notebooks
|
||||
} else if (code.startsWith('tel-')) {
|
||||
resource.category = 'hardware';
|
||||
}
|
||||
|
||||
// Parse details for SN, MOD, USR, location
|
||||
const snMatch = details.match(/SN:\s*([^;]+)/);
|
||||
if (snMatch) resource.serial_number = snMatch[1].trim();
|
||||
|
||||
const modMatch = details.match(/MOD(?:ELO)?:\s*([^;]+)/);
|
||||
if (modMatch) resource.model = modMatch[1].trim();
|
||||
|
||||
const usrMatch = details.match(/USR:\s*([^;]+)/);
|
||||
if (usrMatch) {
|
||||
resource.status = 'assigned';
|
||||
resource.technical_specs.usr = usrMatch[1].trim();
|
||||
}
|
||||
|
||||
// Location from description, e.g., GOB-Pasillo
|
||||
const locMatch = details.match(/^([^-]+)-/);
|
||||
if (locMatch) resource.location = locMatch[1].trim();
|
||||
|
||||
return resource;
|
||||
}
|
||||
|
||||
async function insertResourcesBatch(resources) {
|
||||
const { pool } = require('./database');
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
const values = resources.map((resource, index) => {
|
||||
const baseIndex = index * 9;
|
||||
return `($${baseIndex + 1}, $${baseIndex + 2}, $${baseIndex + 3}, $${baseIndex + 4}, $${baseIndex + 5}, $${baseIndex + 6}, $${baseIndex + 7}, $${baseIndex + 8}, $${baseIndex + 9})`;
|
||||
}).join(', ');
|
||||
|
||||
const query = `
|
||||
INSERT INTO recursos (dtic_id, name, description, category, status, location, technical_specs, serial_number, model)
|
||||
VALUES ${values}
|
||||
ON CONFLICT (dtic_id) DO NOTHING
|
||||
`;
|
||||
|
||||
const params = resources.flatMap(resource => [
|
||||
resource.dtic_id,
|
||||
resource.name,
|
||||
resource.description,
|
||||
resource.category,
|
||||
resource.status,
|
||||
resource.location,
|
||||
JSON.stringify(resource.technical_specs),
|
||||
resource.serial_number,
|
||||
resource.model
|
||||
]);
|
||||
|
||||
const result = await client.query(query, params);
|
||||
const insertedCount = result.rowCount;
|
||||
const skippedCount = resources.length - insertedCount;
|
||||
|
||||
await client.query('COMMIT');
|
||||
return { insertedCount, skippedCount };
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK');
|
||||
console.error('Error inserting resources batch:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
// Run the script
|
||||
if (require.main === module) {
|
||||
loadResourcesFromPDF();
|
||||
}
|
||||
|
||||
module.exports = { loadResourcesFromPDF };
|
||||
@@ -1,250 +0,0 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { pool } = require('../database');
|
||||
|
||||
// Función helper para ejecutar queries
|
||||
const executeQuery = async (query, params = []) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await client.query(query, params);
|
||||
return result;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware de autenticación JWT
|
||||
*/
|
||||
const authenticateToken = async (req, res, next) => {
|
||||
try {
|
||||
const authHeader = req.headers.authorization;
|
||||
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token de acceso requerido'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar token
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
// Verificar que el usuario aún existe y está activo
|
||||
const query = 'SELECT id, is_active, role FROM dtic.tecnicos WHERE id = $1';
|
||||
const result = await executeQuery(query, [decoded.id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
|
||||
if (!user.is_active) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario inactivo'
|
||||
});
|
||||
}
|
||||
|
||||
// Agregar información del usuario a la request
|
||||
req.user = {
|
||||
id: decoded.id,
|
||||
dtic_id: decoded.dtic_id,
|
||||
email: decoded.email,
|
||||
role: user.role,
|
||||
department: decoded.department
|
||||
};
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('Error en autenticación:', error);
|
||||
|
||||
if (error.name === 'JsonWebTokenError') {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token inválido'
|
||||
});
|
||||
}
|
||||
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token expirado'
|
||||
});
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware para verificar permisos por rol
|
||||
*/
|
||||
const requirePermission = (requiredRole) => {
|
||||
return (req, res, next) => {
|
||||
if (!req.user) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario no autenticado'
|
||||
});
|
||||
}
|
||||
|
||||
const roleHierarchy = {
|
||||
'viewer': 1,
|
||||
'technician': 2,
|
||||
'admin': 3
|
||||
};
|
||||
|
||||
const userRoleLevel = roleHierarchy[req.user.role] || 0;
|
||||
const requiredRoleLevel = roleHierarchy[requiredRole] || 0;
|
||||
|
||||
if (userRoleLevel < requiredRoleLevel) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'Permisos insuficientes'
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware para verificar propiedad de recursos
|
||||
*/
|
||||
const requireOwnership = (resourceType) => {
|
||||
return async (req, res, next) => {
|
||||
if (!req.user) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario no autenticado'
|
||||
});
|
||||
}
|
||||
|
||||
// Los administradores pueden acceder a todo
|
||||
if (req.user.role === 'admin') {
|
||||
return next();
|
||||
}
|
||||
|
||||
const resourceId = req.params.id;
|
||||
|
||||
try {
|
||||
let query;
|
||||
let params;
|
||||
|
||||
switch (resourceType) {
|
||||
case 'technician':
|
||||
// Los técnicos solo pueden acceder a su propio perfil
|
||||
if (req.user.id !== parseInt(resourceId)) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'No tienes permisos para acceder a este recurso'
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'task':
|
||||
// Verificar si el usuario es el asignado a la tarea
|
||||
query = 'SELECT technician_id FROM dtic.tareas WHERE id = $1';
|
||||
params = [resourceId];
|
||||
break;
|
||||
|
||||
default:
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Tipo de recurso no válido'
|
||||
});
|
||||
}
|
||||
|
||||
if (query) {
|
||||
const result = await executeQuery(query, params);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
if (result.rows[0].technician_id !== req.user.id) {
|
||||
return res.status(403).json({
|
||||
success: false,
|
||||
message: 'No tienes permisos para acceder a este recurso'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('Error verificando propiedad:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Middleware para logging de auditoría
|
||||
*/
|
||||
const auditLog = (action) => {
|
||||
return async (req, res, next) => {
|
||||
const originalSend = res.send;
|
||||
|
||||
res.send = function(data) {
|
||||
// Solo loguear si la operación fue exitosa
|
||||
if (res.statusCode >= 200 && res.statusCode < 300) {
|
||||
try {
|
||||
const auditData = {
|
||||
user_id: req.user?.id,
|
||||
action: action,
|
||||
entity_type: req.route?.path?.split('/')[1] || 'unknown',
|
||||
entity_id: req.params?.id ? parseInt(req.params.id) : null,
|
||||
old_values: null, // Para actualizaciones, se podría implementar comparación
|
||||
new_values: req.method === 'POST' || req.method === 'PUT' ? req.body : null,
|
||||
ip_address: req.ip,
|
||||
user_agent: req.get('User-Agent')
|
||||
};
|
||||
|
||||
// Insertar en auditoría (de forma asíncrona, no bloqueante)
|
||||
executeQuery(`
|
||||
INSERT INTO dtic.audit_log
|
||||
(user_id, action, entity_type, entity_id, old_values, new_values, ip_address, user_agent)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
`, [
|
||||
auditData.user_id,
|
||||
auditData.action,
|
||||
auditData.entity_type,
|
||||
auditData.entity_id,
|
||||
auditData.old_values ? JSON.stringify(auditData.old_values) : null,
|
||||
auditData.new_values ? JSON.stringify(auditData.new_values) : null,
|
||||
auditData.ip_address,
|
||||
auditData.user_agent
|
||||
]).catch(err => console.error('Error en audit log:', err));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando audit log:', error);
|
||||
}
|
||||
}
|
||||
|
||||
originalSend.call(this, data);
|
||||
};
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
authenticateToken,
|
||||
requirePermission,
|
||||
requireOwnership,
|
||||
auditLog
|
||||
};
|
||||
@@ -1,306 +0,0 @@
|
||||
const express = require('express');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const { executeQuery } = require('../database');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// POST /api/auth/login - Iniciar sesión
|
||||
router.post('/login', [
|
||||
body('email').isEmail().normalizeEmail(),
|
||||
body('password').notEmpty().trim()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos de entrada inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { email, password } = req.body;
|
||||
|
||||
// Buscar usuario por email
|
||||
const query = `
|
||||
SELECT id, dtic_id, first_name, last_name, email, password_hash, role, department, is_active
|
||||
FROM dtic.tecnicos
|
||||
WHERE email = $1
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [email]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Credenciales inválidas'
|
||||
});
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
|
||||
// Verificar si el usuario está activo
|
||||
if (!user.is_active) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario inactivo'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar contraseña
|
||||
if (!user.password_hash) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario no tiene contraseña configurada'
|
||||
});
|
||||
}
|
||||
|
||||
const isValidPassword = await bcrypt.compare(password, user.password_hash);
|
||||
if (!isValidPassword) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Credenciales inválidas'
|
||||
});
|
||||
}
|
||||
|
||||
// Generar token JWT
|
||||
const token = jwt.sign(
|
||||
{
|
||||
id: user.id,
|
||||
dtic_id: user.dtic_id,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
department: user.department
|
||||
},
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '8h' }
|
||||
);
|
||||
|
||||
// Actualizar último acceso
|
||||
await executeQuery(
|
||||
'UPDATE dtic.tecnicos SET updated_at = CURRENT_TIMESTAMP WHERE id = $1',
|
||||
[user.id]
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Inicio de sesión exitoso',
|
||||
data: {
|
||||
token,
|
||||
user: {
|
||||
id: user.id,
|
||||
dtic_id: user.dtic_id,
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
email: user.email,
|
||||
role: user.role,
|
||||
department: user.department
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error en login:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/register - Registrar nuevo usuario (solo admin)
|
||||
router.post('/register', [
|
||||
body('first_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('last_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('email').isEmail().normalizeEmail(),
|
||||
body('password').isLength({ min: 8 }),
|
||||
body('department').isIn(['dtic', 'sistemas', 'redes', 'seguridad']),
|
||||
body('role').isIn(['admin', 'technician', 'viewer'])
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { first_name, last_name, email, password, department, role } = req.body;
|
||||
|
||||
// Verificar email único
|
||||
const emailCheck = await executeQuery('SELECT id FROM dtic.tecnicos WHERE email = $1', [email]);
|
||||
if (emailCheck.rows.length > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El email ya está registrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Generar DTIC ID
|
||||
const dticIdResult = await executeQuery('SELECT generate_dtic_id($1) as new_id', ['TEC']);
|
||||
const dticId = dticIdResult.rows[0].new_id;
|
||||
|
||||
// Hashear contraseña
|
||||
const saltRounds = 12;
|
||||
const hashedPassword = await bcrypt.hash(password, saltRounds);
|
||||
|
||||
// Insertar usuario
|
||||
const query = `
|
||||
INSERT INTO dtic.tecnicos
|
||||
(dtic_id, first_name, last_name, email, password_hash, department, role, is_active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [
|
||||
dticId, first_name, last_name.toUpperCase(), email, hashedPassword, department, role, true
|
||||
]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Usuario registrado exitosamente',
|
||||
data: {
|
||||
user_id: result.rows[0].id,
|
||||
dtic_id: dticId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error en registro:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/logout - Cerrar sesión
|
||||
router.post('/logout', (req, res) => {
|
||||
// En una implementación real, podrías mantener una lista negra de tokens
|
||||
// Por ahora, simplemente respondemos con éxito
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Sesión cerrada exitosamente'
|
||||
});
|
||||
});
|
||||
|
||||
// GET /api/auth/me - Obtener información del usuario actual
|
||||
router.get('/me', async (req, res) => {
|
||||
try {
|
||||
// El middleware de auth debería haber establecido req.user
|
||||
const token = req.headers.authorization?.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token no proporcionado'
|
||||
});
|
||||
}
|
||||
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET);
|
||||
|
||||
const query = `
|
||||
SELECT id, dtic_id, first_name, last_name, email, role, department, is_active, created_at, updated_at
|
||||
FROM dtic.tecnicos
|
||||
WHERE id = $1
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [decoded.id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Usuario no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Información de usuario obtenida exitosamente',
|
||||
data: { user }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo usuario actual:', error);
|
||||
|
||||
if (error.name === 'JsonWebTokenError') {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token inválido'
|
||||
});
|
||||
}
|
||||
|
||||
if (error.name === 'TokenExpiredError') {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token expirado'
|
||||
});
|
||||
}
|
||||
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/auth/refresh - Refrescar token
|
||||
router.post('/refresh', async (req, res) => {
|
||||
try {
|
||||
const { token } = req.body;
|
||||
|
||||
if (!token) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Token requerido'
|
||||
});
|
||||
}
|
||||
|
||||
const decoded = jwt.verify(token, process.env.JWT_SECRET, { ignoreExpiration: true });
|
||||
|
||||
// Verificar que el usuario aún existe y está activo
|
||||
const query = 'SELECT id, is_active FROM dtic.tecnicos WHERE id = $1';
|
||||
const result = await executeQuery(query, [decoded.id]);
|
||||
|
||||
if (result.rows.length === 0 || !result.rows[0].is_active) {
|
||||
return res.status(401).json({
|
||||
success: false,
|
||||
message: 'Usuario no válido'
|
||||
});
|
||||
}
|
||||
|
||||
// Generar nuevo token
|
||||
const newToken = jwt.sign(
|
||||
{
|
||||
id: decoded.id,
|
||||
dtic_id: decoded.dtic_id,
|
||||
email: decoded.email,
|
||||
role: decoded.role,
|
||||
department: decoded.department
|
||||
},
|
||||
process.env.JWT_SECRET,
|
||||
{ expiresIn: '8h' }
|
||||
);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Token refrescado exitosamente',
|
||||
data: { token: newToken }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error refrescando token:', error);
|
||||
res.status(401).json({
|
||||
success: false,
|
||||
message: 'Token inválido'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,605 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, query, validationResult } = require('express-validator');
|
||||
const { executeQuery } = require('../database');
|
||||
const auth = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Middleware de autenticación (temporalmente comentado para desarrollo)
|
||||
// router.use(auth);
|
||||
|
||||
// Función helper para generar DTIC ID para recursos
|
||||
const generateDTICId = async (prefix = 'REC') => {
|
||||
const query = `
|
||||
SELECT dtic.generate_dtic_id($1) as new_id
|
||||
`;
|
||||
const result = await executeQuery(query, [prefix]);
|
||||
return result.rows[0].new_id;
|
||||
};
|
||||
|
||||
// GET /api/recursos - Obtener lista de recursos con filtros
|
||||
router.get('/', [
|
||||
query('page').optional().isInt({ min: 1 }).toInt(),
|
||||
query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
|
||||
query('search').optional().isString().trim(),
|
||||
query('category').optional().isIn(['hardware', 'software', 'network', 'security', 'tools', 'facilities']),
|
||||
query('status').optional().isIn(['available', 'assigned', 'maintenance', 'retired']),
|
||||
query('location').optional().isString().trim()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 12,
|
||||
search,
|
||||
category,
|
||||
status,
|
||||
location
|
||||
} = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
r.id, r.dtic_id, r.name, r.description, r.category, r.status,
|
||||
r.location, r.technical_specs, r.serial_number, r.model,
|
||||
r.created_at, r.updated_at,
|
||||
COALESCE(json_agg(DISTINCT jsonb_build_object('id', u.id, 'first_name', u.first_name, 'last_name', u.last_name, 'full_name', CONCAT(u.first_name, ' ', u.last_name))) FILTER (WHERE ra.user_id IS NOT NULL), '[]'::json) as assigned_users,
|
||||
COALESCE(json_agg(DISTINCT jsonb_build_object('id', t.id, 'title', t.title, 'status', t.status)) FILTER (WHERE t.id IS NOT NULL), '[]'::json) as related_tasks
|
||||
FROM recursos r
|
||||
LEFT JOIN recurso_asignaciones ra ON ra.recurso_id = r.id AND ra.activo = true
|
||||
LEFT JOIN usuarios_relacionados u ON u.id = ra.user_id
|
||||
LEFT JOIN tarea_recursos tr ON tr.recurso_id = r.id AND tr.activo = true
|
||||
LEFT JOIN tareas t ON t.id = tr.tarea_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
|
||||
// Filtros
|
||||
if (search) {
|
||||
conditions.push("(r.name ILIKE $1 OR r.description ILIKE $1 OR r.dtic_id ILIKE $1 OR r.serial_number ILIKE $1 OR r.model ILIKE $1)");
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
if (category) {
|
||||
conditions.push("r.category = $" + (params.length + 1));
|
||||
params.push(category);
|
||||
}
|
||||
|
||||
if (status) {
|
||||
conditions.push("r.status = $" + (params.length + 1));
|
||||
params.push(status);
|
||||
}
|
||||
|
||||
if (location) {
|
||||
conditions.push("r.location ILIKE $" + (params.length + 1));
|
||||
params.push(`%${location}%`);
|
||||
}
|
||||
|
||||
if (conditions.length > 0) {
|
||||
query += " AND " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
query += " GROUP BY r.id, r.dtic_id, r.name, r.description, r.category, r.status, r.location, r.technical_specs, r.serial_number, r.model, r.created_at, r.updated_at ORDER BY r.created_at DESC";
|
||||
|
||||
// Paginación
|
||||
const offset = (page - 1) * limit;
|
||||
query += ` LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
|
||||
params.push(limit, offset);
|
||||
|
||||
const result = await executeQuery(query, params);
|
||||
|
||||
// Obtener total para paginación
|
||||
let countQuery = "SELECT COUNT(*) as total FROM dtic.recursos r WHERE 1=1";
|
||||
const countParams = [];
|
||||
|
||||
if (conditions.length > 0) {
|
||||
countQuery += " AND " + conditions.join(" AND ");
|
||||
countParams.push(...params.slice(0, -2));
|
||||
}
|
||||
|
||||
const countResult = await executeQuery(countQuery, countParams);
|
||||
const total = parseInt(countResult.rows[0].total);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recursos obtenidos exitosamente',
|
||||
data: {
|
||||
recursos: result.rows,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
pages: Math.ceil(total / limit)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo recursos:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/recursos/:id - Obtener recurso específico
|
||||
router.get('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { include_history } = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT r.*
|
||||
FROM dtic.recursos r
|
||||
WHERE r.id = $1
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const recurso = result.rows[0];
|
||||
|
||||
// Obtener usuarios asignados
|
||||
const assignedUsersQuery = `
|
||||
SELECT
|
||||
u.id, u.dtic_id, u.first_name, u.last_name,
|
||||
CONCAT(u.first_name, ' ', u.last_name) as full_name,
|
||||
ra.assigned_at, ra.assigned_by
|
||||
FROM dtic.recurso_asignaciones ra
|
||||
JOIN dtic.usuarios_relacionados u ON u.id = ra.user_id
|
||||
WHERE ra.recurso_id = $1 AND ra.activo = true
|
||||
ORDER BY ra.assigned_at DESC
|
||||
`;
|
||||
const assignedUsersResult = await executeQuery(assignedUsersQuery, [id]);
|
||||
recurso.assigned_users = assignedUsersResult.rows;
|
||||
|
||||
// Obtener historial si se solicita
|
||||
if (include_history === 'true') {
|
||||
const historyQuery = `
|
||||
SELECT
|
||||
h.*,
|
||||
t.dtic_id as tecnico_dtic_id,
|
||||
CONCAT(t.first_name, ' ', t.last_name) as tecnico_name,
|
||||
u.dtic_id as usuario_dtic_id,
|
||||
CONCAT(u.first_name, ' ', u.last_name) as usuario_name
|
||||
FROM dtic.recurso_historial h
|
||||
LEFT JOIN dtic.tecnicos t ON t.id = h.tecnico_id
|
||||
LEFT JOIN dtic.usuarios_relacionados u ON u.id = h.usuario_id
|
||||
WHERE h.recurso_id = $1
|
||||
ORDER BY h.created_at DESC
|
||||
LIMIT 20
|
||||
`;
|
||||
const historyResult = await executeQuery(historyQuery, [id]);
|
||||
recurso.history = historyResult.rows;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso obtenido exitosamente',
|
||||
data: { recurso }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/recursos - Crear nuevo recurso
|
||||
router.post('/', [
|
||||
body('name').trim().isLength({ min: 2, max: 200 }),
|
||||
body('description').optional().trim().isLength({ max: 1000 }),
|
||||
body('category').isIn(['hardware', 'software', 'network', 'security', 'tools', 'facilities']),
|
||||
body('status').optional().isIn(['available', 'assigned', 'maintenance', 'retired']),
|
||||
body('location').optional().trim().isLength({ max: 200 }),
|
||||
body('technical_specs').optional(),
|
||||
body('serial_number').optional().trim().isLength({ max: 100 }),
|
||||
body('model').optional().trim().isLength({ max: 100 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
name, description, category, status = 'available',
|
||||
location, technical_specs, serial_number, model
|
||||
} = req.body;
|
||||
|
||||
// Generar DTIC ID
|
||||
const dticId = await generateDTICId('REC');
|
||||
|
||||
// Insertar recurso
|
||||
const query = `
|
||||
INSERT INTO dtic.recursos
|
||||
(dtic_id, name, description, category, status, location, technical_specs, serial_number, model)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [
|
||||
dticId, name, description, category, status, location,
|
||||
technical_specs, serial_number, model
|
||||
]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Recurso creado exitosamente',
|
||||
data: {
|
||||
recurso_id: result.rows[0].id,
|
||||
dtic_id: dticId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/recursos/:id - Actualizar recurso
|
||||
router.put('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('name').optional().trim().isLength({ min: 2, max: 200 }),
|
||||
body('description').optional().trim().isLength({ max: 1000 }),
|
||||
body('category').optional().isIn(['hardware', 'software', 'network', 'security', 'tools', 'facilities']),
|
||||
body('status').optional().isIn(['available', 'assigned', 'maintenance', 'retired']),
|
||||
body('location').optional().trim().isLength({ max: 200 }),
|
||||
body('technical_specs').optional(),
|
||||
body('serial_number').optional().trim().isLength({ max: 100 }),
|
||||
body('model').optional().trim().isLength({ max: 100 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const {
|
||||
name, description, category, status, location,
|
||||
technical_specs, serial_number, model
|
||||
} = req.body;
|
||||
|
||||
// Verificar que el recurso existe
|
||||
const existingQuery = 'SELECT * FROM dtic.recursos WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Construir query de actualización
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
|
||||
const allowedFields = [
|
||||
'name', 'description', 'category', 'status', 'location',
|
||||
'technical_specs', 'serial_number', 'model'
|
||||
];
|
||||
|
||||
allowedFields.forEach(field => {
|
||||
if (req.body[field] !== undefined) {
|
||||
updateFields.push(`${field} = $${params.length + 1}`);
|
||||
params.push(req.body[field]);
|
||||
}
|
||||
});
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'No se proporcionaron campos para actualizar'
|
||||
});
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const query = `
|
||||
UPDATE dtic.recursos
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
`;
|
||||
|
||||
await executeQuery(query, params);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso actualizado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error actualizando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/recursos/:id - Eliminar recurso
|
||||
router.delete('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
|
||||
// Verificar que el recurso existe
|
||||
const existingQuery = 'SELECT * FROM dtic.recursos WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const recurso = existingResult.rows[0];
|
||||
|
||||
if (recurso.status === 'assigned') {
|
||||
// Verificar si tiene usuarios asignados activos
|
||||
const assignedUsersQuery = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM dtic.recurso_asignaciones
|
||||
WHERE recurso_id = $1 AND activo = true
|
||||
`;
|
||||
const assignedResult = await executeQuery(assignedUsersQuery, [id]);
|
||||
|
||||
if (parseInt(assignedResult.rows[0].count) > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'No se puede eliminar el recurso porque tiene usuarios asignados'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Cambiar estado a retirado (eliminación lógica)
|
||||
await executeQuery('UPDATE dtic.recursos SET status = $1 WHERE id = $2', ['retired', id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso retirado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error eliminando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/recursos/:id/asignar - Asignar recurso a usuario
|
||||
router.post('/:id/asignar', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('usuario_id').isInt({ min: 1 }),
|
||||
body('tecnico_id').optional().isInt({ min: 1 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { usuario_id, tecnico_id } = req.body;
|
||||
|
||||
// Verificar que el recurso existe
|
||||
const recursoQuery = 'SELECT * FROM dtic.recursos WHERE id = $1';
|
||||
const recursoResult = await executeQuery(recursoQuery, [id]);
|
||||
|
||||
if (recursoResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar que el usuario existe
|
||||
const usuarioQuery = 'SELECT * FROM dtic.usuarios_relacionados WHERE id = $1';
|
||||
const usuarioResult = await executeQuery(usuarioQuery, [usuario_id]);
|
||||
|
||||
if (usuarioResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Usuario no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar que no esté ya asignado
|
||||
const existingQuery = `
|
||||
SELECT id FROM dtic.recurso_asignaciones
|
||||
WHERE recurso_id = $1 AND user_id = $2 AND activo = true
|
||||
`;
|
||||
const existingResult = await executeQuery(existingQuery, [id, usuario_id]);
|
||||
|
||||
if (existingResult.rows.length > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El recurso ya está asignado a este usuario'
|
||||
});
|
||||
}
|
||||
|
||||
// Crear asignación
|
||||
const assignQuery = `
|
||||
INSERT INTO dtic.recurso_asignaciones
|
||||
(recurso_id, user_id, assigned_by, activo)
|
||||
VALUES ($1, $2, $3, true)
|
||||
`;
|
||||
|
||||
await executeQuery(assignQuery, [id, usuario_id, tecnico_id]);
|
||||
|
||||
// Actualizar estado del recurso si estaba disponible
|
||||
if (recursoResult.rows[0].status === 'available') {
|
||||
await executeQuery('UPDATE dtic.recursos SET status = $1 WHERE id = $2', ['assigned', id]);
|
||||
}
|
||||
|
||||
// Registrar en historial
|
||||
const historyQuery = `
|
||||
INSERT INTO dtic.recurso_historial
|
||||
(recurso_id, action, usuario_id, tecnico_id, details)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`;
|
||||
|
||||
await executeQuery(historyQuery, [
|
||||
id, 'assigned', usuario_id, tecnico_id,
|
||||
`Recurso asignado a ${usuarioResult.rows[0].first_name} ${usuarioResult.rows[0].last_name}`
|
||||
]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso asignado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error asignando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/recursos/:id/desasignar - Desasignar recurso de usuario
|
||||
router.post('/:id/desasignar', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('usuario_id').isInt({ min: 1 }),
|
||||
body('tecnico_id').optional().isInt({ min: 1 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { usuario_id, tecnico_id } = req.body;
|
||||
|
||||
// Verificar que la asignación existe
|
||||
const assignmentQuery = `
|
||||
SELECT ra.*, u.first_name, u.last_name
|
||||
FROM dtic.recurso_asignaciones ra
|
||||
JOIN dtic.usuarios_relacionados u ON u.id = ra.user_id
|
||||
WHERE ra.recurso_id = $1 AND ra.user_id = $2 AND ra.activo = true
|
||||
`;
|
||||
const assignmentResult = await executeQuery(assignmentQuery, [id, usuario_id]);
|
||||
|
||||
if (assignmentResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Asignación no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
// Desactivar asignación
|
||||
const updateQuery = `
|
||||
UPDATE dtic.recurso_asignaciones
|
||||
SET activo = false, unassigned_at = CURRENT_TIMESTAMP, unassigned_by = $1
|
||||
WHERE recurso_id = $2 AND user_id = $3 AND activo = true
|
||||
`;
|
||||
|
||||
await executeQuery(updateQuery, [tecnico_id, id, usuario_id]);
|
||||
|
||||
// Verificar si quedan usuarios asignados
|
||||
const remainingQuery = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM dtic.recurso_asignaciones
|
||||
WHERE recurso_id = $1 AND activo = true
|
||||
`;
|
||||
const remainingResult = await executeQuery(remainingQuery, [id]);
|
||||
|
||||
// Si no quedan usuarios asignados, cambiar estado a disponible
|
||||
if (parseInt(remainingResult.rows[0].count) === 0) {
|
||||
await executeQuery('UPDATE dtic.recursos SET status = $1 WHERE id = $2', ['available', id]);
|
||||
}
|
||||
|
||||
// Registrar en historial
|
||||
const usuario = assignmentResult.rows[0];
|
||||
const historyQuery = `
|
||||
INSERT INTO dtic.recurso_historial
|
||||
(recurso_id, action, usuario_id, tecnico_id, details)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
`;
|
||||
|
||||
await executeQuery(historyQuery, [
|
||||
id, 'unassigned', usuario_id, tecnico_id,
|
||||
`Recurso desasignado de ${usuario.first_name} ${usuario.last_name}`
|
||||
]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso desasignado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error desasignando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,384 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, validationResult } = require('express-validator');
|
||||
const { exec } = require('child_process');
|
||||
const fs = require('fs').promises;
|
||||
const path = require('path');
|
||||
const url = require('url');
|
||||
const auth = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Middleware de autenticación y permisos de admin
|
||||
router.use(auth.authenticateToken);
|
||||
router.use(auth.requirePermission('admin'));
|
||||
|
||||
// Función helper para parsear DATABASE_URL
|
||||
const parseDatabaseUrl = (databaseUrl) => {
|
||||
const parsedUrl = url.parse(databaseUrl);
|
||||
return {
|
||||
host: parsedUrl.hostname,
|
||||
port: parsedUrl.port,
|
||||
database: parsedUrl.pathname.substring(1),
|
||||
username: parsedUrl.auth.split(':')[0],
|
||||
password: parsedUrl.auth.split(':')[1]
|
||||
};
|
||||
};
|
||||
|
||||
// POST /api/system/backup - Crear backup de la base de datos
|
||||
router.post('/backup', async (req, res) => {
|
||||
try {
|
||||
const dbConfig = parseDatabaseUrl(process.env.DATABASE_URL);
|
||||
const timestamp = new Date().toISOString().replace(/[:.]/g, '').replace('T', '_').split('.')[0];
|
||||
const backupFileName = `dtic_bitacoras_backup_${timestamp}.sql`;
|
||||
const backupPath = path.join('/host', '_app-bitacoras', 'backups', backupFileName);
|
||||
|
||||
// Usar Docker para ejecutar pg_dump en el contenedor de PostgreSQL
|
||||
const tempBackupName = `temp_backup_${Date.now()}.sql`;
|
||||
const dockerPgDumpCommand = `docker exec -e PGPASSWORD=${dbConfig.password} dtic_bitacoras_postgres pg_dump -h localhost -p 5432 -U ${dbConfig.username} -d ${dbConfig.database} -f /tmp/${tempBackupName}`;
|
||||
|
||||
// Ejecutar pg_dump dentro del contenedor PostgreSQL
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerPgDumpCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error('Error en pg_dump dentro del contenedor:', error);
|
||||
console.error('Stderr:', stderr);
|
||||
reject(new Error(`Error creando backup: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
console.log('Backup creado exitosamente en contenedor:', backupFileName);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// Copiar el backup desde el contenedor al host
|
||||
const dockerCpCommand = `docker cp dtic_bitacoras_postgres:/tmp/${tempBackupName} ${backupPath}`;
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerCpCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error('Error copiando backup desde contenedor:', error);
|
||||
console.error('Stderr:', stderr);
|
||||
reject(new Error(`Error copiando backup: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
console.log('Backup copiado exitosamente al host:', backupPath);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// Limpiar archivo temporal del contenedor
|
||||
const dockerRmCommand = `docker exec dtic_bitacoras_postgres rm -f /tmp/${tempBackupName}`;
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerRmCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.warn('Advertencia: No se pudo limpiar archivo temporal del contenedor:', error.message);
|
||||
// No rechazamos aquí, ya que el backup ya se copió exitosamente
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Backup creado exitosamente',
|
||||
data: {
|
||||
backup_file: backupFileName,
|
||||
backup_path: backupPath,
|
||||
created_at: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando backup:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al crear backup'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/system/restore - Restaurar base de datos desde backup
|
||||
router.post('/restore', [
|
||||
body('backup_file').isString().notEmpty().withMessage('Nombre del archivo de backup es requerido')
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { backup_file } = req.body;
|
||||
const dbConfig = parseDatabaseUrl(process.env.DATABASE_URL);
|
||||
const backupPath = path.join('/host', '_app-bitacoras', 'backups', backup_file);
|
||||
|
||||
// Verificar que el archivo existe
|
||||
try {
|
||||
await fs.access(backupPath);
|
||||
} catch (error) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Archivo de backup no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Usar Docker para ejecutar psql en el contenedor de PostgreSQL
|
||||
const tempBackupName = `temp_restore_${Date.now()}.sql`;
|
||||
const dockerCpCommand = `docker cp ${backupPath} dtic_bitacoras_postgres:/tmp/${tempBackupName}`;
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerCpCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error('Error copiando backup al contenedor:', error);
|
||||
console.error('Stderr:', stderr);
|
||||
reject(new Error(`Error copiando backup: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
console.log('Backup copiado al contenedor exitosamente');
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// Ejecutar psql dentro del contenedor PostgreSQL
|
||||
const dockerPsqlCommand = `docker exec -e PGPASSWORD=${dbConfig.password} dtic_bitacoras_postgres psql -h localhost -p 5432 -U ${dbConfig.username} -d ${dbConfig.database} -f /tmp/${tempBackupName}`;
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerPsqlCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.error('Error en psql dentro del contenedor:', error);
|
||||
console.error('Stderr:', stderr);
|
||||
reject(new Error(`Error restaurando backup: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
console.log('Backup restaurado exitosamente:', backup_file);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
// Limpiar archivo temporal del contenedor
|
||||
const dockerRmCommand = `docker exec dtic_bitacoras_postgres rm -f /tmp/${tempBackupName}`;
|
||||
await new Promise((resolve, reject) => {
|
||||
const child = exec(dockerRmCommand, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.warn('Advertencia: No se pudo limpiar archivo temporal del contenedor:', error.message);
|
||||
// No rechazamos aquí, ya que la restauración ya se completó exitosamente
|
||||
}
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Base de datos restaurada exitosamente',
|
||||
data: {
|
||||
backup_file: backup_file,
|
||||
restored_at: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error restaurando backup:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al restaurar backup'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/system/backups - Listar archivos de backup disponibles
|
||||
router.get('/backups', async (req, res) => {
|
||||
console.log('GET /backups - Starting list backups request');
|
||||
try {
|
||||
const backupsDir = path.join('/host', '_app-bitacoras', 'backups');
|
||||
console.log('GET /backups - Backups dir:', backupsDir);
|
||||
|
||||
// Leer directorio de backups
|
||||
const files = await fs.readdir(backupsDir);
|
||||
console.log('GET /backups - Files in dir:', files);
|
||||
|
||||
// Filtrar archivos .sql y obtener información
|
||||
const backupFiles = await Promise.all(
|
||||
files
|
||||
.filter(file => file.endsWith('.sql'))
|
||||
.map(async (file) => {
|
||||
const filePath = path.join(backupsDir, file);
|
||||
const stats = await fs.stat(filePath);
|
||||
|
||||
// Extraer timestamp del nombre del archivo
|
||||
const timestampMatch = file.match(/dtic_bitacoras_backup_(\d{4}-?\d{2}-?\d{2})_(\d{6,9})(Z?)\.sql/);
|
||||
let createdAt = null;
|
||||
if (timestampMatch) {
|
||||
const dateStr = timestampMatch[1];
|
||||
const timeStr = timestampMatch[2];
|
||||
const z = timestampMatch[3];
|
||||
let year, month, day;
|
||||
if (dateStr.includes('-')) {
|
||||
[year, month, day] = dateStr.split('-');
|
||||
} else {
|
||||
year = dateStr.substring(0, 4);
|
||||
month = dateStr.substring(4, 6);
|
||||
day = dateStr.substring(6, 8);
|
||||
}
|
||||
let hour, minute, second, ms = '000';
|
||||
if (timeStr.length === 6) {
|
||||
hour = timeStr.substring(0, 2);
|
||||
minute = timeStr.substring(2, 4);
|
||||
second = timeStr.substring(4, 6);
|
||||
} else if (timeStr.length === 9) {
|
||||
hour = timeStr.substring(0, 2);
|
||||
minute = timeStr.substring(2, 4);
|
||||
second = timeStr.substring(4, 6);
|
||||
ms = timeStr.substring(6, 9);
|
||||
}
|
||||
createdAt = `${year}-${month}-${day}T${hour}:${minute}:${second}.${ms}Z`;
|
||||
}
|
||||
|
||||
return {
|
||||
filename: file,
|
||||
size: stats.size,
|
||||
created_at: createdAt || stats.birthtime.toISOString(),
|
||||
modified_at: stats.mtime.toISOString()
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
// Ordenar por fecha de creación descendente
|
||||
backupFiles.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Archivos de backup obtenidos exitosamente',
|
||||
data: {
|
||||
backups: backupFiles,
|
||||
total: backupFiles.length
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error listando backups:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al listar backups'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/system/backups/:filename - Eliminar archivo de backup
|
||||
router.delete('/backups/:filename', [
|
||||
param('filename').isString().matches(/^dtic_bitacoras_backup_(?:\d{4}-\d{2}-\d{2}|\d{8})_\d{6,9}Z?\.sql$/).withMessage('Nombre de archivo de backup inválido')
|
||||
], async (req, res) => {
|
||||
console.log('DELETE /backups/:filename - Starting deletion request');
|
||||
console.log('Filename param:', req.params.filename);
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
console.log('DELETE /backups/:filename - Validation errors:', errors.array());
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { filename } = req.params;
|
||||
const backupsDir = path.join('/host', '_app-bitacoras', 'backups');
|
||||
const filePath = path.join(backupsDir, filename);
|
||||
console.log('DELETE /backups/:filename - Backups dir:', backupsDir);
|
||||
console.log('DELETE /backups/:filename - File path:', filePath);
|
||||
|
||||
// Verificar que el archivo existe
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
console.log('DELETE /backups/:filename - File exists');
|
||||
} catch (error) {
|
||||
console.log('DELETE /backups/:filename - File does not exist, error:', error.message);
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Archivo de backup no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Eliminar el archivo
|
||||
await fs.unlink(filePath);
|
||||
console.log('DELETE /backups/:filename - File deleted successfully');
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Archivo de backup eliminado exitosamente',
|
||||
data: {
|
||||
filename: filename,
|
||||
deleted_at: new Date().toISOString()
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error eliminando backup:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al eliminar backup'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/system/backups/:filename/download - Descargar archivo de backup
|
||||
router.get('/backups/:filename/download', [
|
||||
param('filename').isString().matches(/^dtic_bitacoras_backup_(?:\d{4}-\d{2}-\d{2}|\d{8})_\d{6,9}Z?\.sql$/).withMessage('Nombre de archivo de backup inválido')
|
||||
], async (req, res) => {
|
||||
console.log('GET /backups/:filename/download - Starting download request');
|
||||
console.log('Filename param:', req.params.filename);
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
console.log('GET /backups/:filename/download - Validation errors:', errors.array());
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { filename } = req.params;
|
||||
const backupsDir = path.join('/host', '_app-bitacoras', 'backups');
|
||||
const filePath = path.join(backupsDir, filename);
|
||||
console.log('GET /backups/:filename/download - Backups dir:', backupsDir);
|
||||
console.log('GET /backups/:filename/download - File path:', filePath);
|
||||
|
||||
// Verificar que el archivo existe
|
||||
try {
|
||||
await fs.access(filePath);
|
||||
console.log('GET /backups/:filename/download - File exists');
|
||||
} catch (error) {
|
||||
console.log('GET /backups/:filename/download - File does not exist, error:', error.message);
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Archivo de backup no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Enviar el archivo como descarga
|
||||
console.log('GET /backups/:filename/download - Starting file download');
|
||||
res.download(filePath, filename, (error) => {
|
||||
if (error) {
|
||||
console.error('Error descargando backup:', error);
|
||||
// Si la respuesta ya fue enviada, no hacer nada
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al descargar backup'
|
||||
});
|
||||
}
|
||||
} else {
|
||||
console.log('GET /backups/:filename/download - File download completed successfully');
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error procesando descarga de backup:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor al procesar descarga'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,488 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, query, validationResult } = require('express-validator');
|
||||
const { Pool } = require('pg');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Configuración de PostgreSQL
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
});
|
||||
|
||||
// Función helper para ejecutar queries
|
||||
const executeQuery = async (query, params = []) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await client.query(query, params);
|
||||
return result;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
// GET /api/tareas/:id/recursos - Obtener recursos asignados a una tarea
|
||||
router.get('/tareas/:id/recursos', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
query('include_details').optional().isBoolean()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { include_details } = req.query;
|
||||
|
||||
// Verificar que la tarea existe
|
||||
const taskQuery = 'SELECT id, title FROM dtic.tareas WHERE id = $1';
|
||||
const taskResult = await executeQuery(taskQuery, [id]);
|
||||
|
||||
if (taskResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tarea no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
tr.id,
|
||||
tr.tarea_id,
|
||||
tr.recurso_id,
|
||||
tr.assigned_by,
|
||||
tr.assigned_at,
|
||||
tr.estimated_hours,
|
||||
tr.actual_hours,
|
||||
tr.notes,
|
||||
tr.activo,
|
||||
r.dtic_id as recurso_dtic_id,
|
||||
r.name as recurso_name,
|
||||
r.category as recurso_category,
|
||||
r.status as recurso_status,
|
||||
r.location as recurso_location,
|
||||
r.model as recurso_model,
|
||||
t.first_name || ' ' || t.last_name as assigned_by_name
|
||||
FROM dtic.tarea_recursos tr
|
||||
JOIN dtic.recursos r ON r.id = tr.recurso_id
|
||||
LEFT JOIN dtic.tecnicos t ON t.id = tr.assigned_by
|
||||
WHERE tr.tarea_id = $1 AND tr.activo = true
|
||||
ORDER BY tr.assigned_at DESC
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
// Si se solicitan detalles adicionales
|
||||
if (include_details === 'true') {
|
||||
for (let assignment of result.rows) {
|
||||
// Obtener historial de esta asignación
|
||||
const historyQuery = `
|
||||
SELECT action, created_at, details
|
||||
FROM dtic.tarea_recurso_historial
|
||||
WHERE tarea_recurso_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 5
|
||||
`;
|
||||
const historyResult = await executeQuery(historyQuery, [assignment.id]);
|
||||
assignment.history = historyResult.rows;
|
||||
}
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recursos asignados obtenidos exitosamente',
|
||||
data: {
|
||||
task: taskResult.rows[0],
|
||||
assignments: result.rows
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo recursos asignados:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/tareas/:id/recursos - Asignar recursos a una tarea
|
||||
router.post('/tareas/:id/recursos', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('recurso_id').isInt({ min: 1 }),
|
||||
body('estimated_hours').optional().isFloat({ min: 0 }),
|
||||
body('notes').optional().isString().trim()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { recurso_id, estimated_hours, notes } = req.body;
|
||||
|
||||
// Verificar que la tarea existe
|
||||
const taskQuery = 'SELECT id, title FROM dtic.tareas WHERE id = $1';
|
||||
const taskResult = await executeQuery(taskQuery, [id]);
|
||||
|
||||
if (taskResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tarea no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar que el recurso existe y está disponible
|
||||
const resourceQuery = 'SELECT id, name, status FROM dtic.recursos WHERE id = $1';
|
||||
const resourceResult = await executeQuery(resourceQuery, [recurso_id]);
|
||||
|
||||
if (resourceResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
if (resourceResult.rows[0].status !== 'available') {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El recurso no está disponible para asignación'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar que no esté ya asignado a esta tarea
|
||||
const existingQuery = `
|
||||
SELECT id FROM dtic.tarea_recursos
|
||||
WHERE tarea_id = $1 AND recurso_id = $2 AND activo = true
|
||||
`;
|
||||
const existingResult = await executeQuery(existingQuery, [id, recurso_id]);
|
||||
|
||||
if (existingResult.rows.length > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El recurso ya está asignado a esta tarea'
|
||||
});
|
||||
}
|
||||
|
||||
// Obtener ID del técnico actual (debería venir del middleware de auth)
|
||||
const assigned_by = req.user?.id || 1; // Temporal hasta implementar auth
|
||||
|
||||
// Insertar asignación
|
||||
const insertQuery = `
|
||||
INSERT INTO dtic.tarea_recursos
|
||||
(tarea_id, recurso_id, assigned_by, estimated_hours, notes)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const insertResult = await executeQuery(insertQuery, [
|
||||
id, recurso_id, assigned_by, estimated_hours, notes
|
||||
]);
|
||||
|
||||
// TODO: Registrar en historial - tabla tarea_recurso_historial no existe
|
||||
// const historyQuery = `
|
||||
// INSERT INTO dtic.tarea_recurso_historial
|
||||
// (tarea_recurso_id, action, tecnico_id, details)
|
||||
// VALUES ($1, 'assigned', $2, $3)
|
||||
// `;
|
||||
|
||||
// await executeQuery(historyQuery, [
|
||||
// insertResult.rows[0].id,
|
||||
// assigned_by,
|
||||
// `Recurso asignado a tarea: ${taskResult.rows[0].title}`
|
||||
// ]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Recurso asignado exitosamente a la tarea',
|
||||
data: {
|
||||
assignment_id: insertResult.rows[0].id,
|
||||
task: taskResult.rows[0],
|
||||
resource: resourceResult.rows[0]
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error asignando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/tareas/:id/recursos/:recursoId - Actualizar asignación
|
||||
router.put('/tareas/:id/recursos/:recursoId', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
param('recursoId').isInt({ min: 1 }).toInt(),
|
||||
body('estimated_hours').optional().isFloat({ min: 0 }),
|
||||
body('actual_hours').optional().isFloat({ min: 0 }),
|
||||
body('notes').optional().isString().trim()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id, recursoId } = req.params;
|
||||
const { estimated_hours, actual_hours, notes } = req.body;
|
||||
|
||||
// Verificar que la asignación existe y está activa
|
||||
const assignmentQuery = `
|
||||
SELECT tr.*, t.title as task_title, r.name as resource_name
|
||||
FROM dtic.tarea_recursos tr
|
||||
JOIN dtic.tareas t ON t.id = tr.tarea_id
|
||||
JOIN dtic.recursos r ON r.id = tr.recurso_id
|
||||
WHERE tr.tarea_id = $1 AND tr.recurso_id = $2 AND tr.activo = true
|
||||
`;
|
||||
|
||||
const assignmentResult = await executeQuery(assignmentQuery, [id, recursoId]);
|
||||
|
||||
if (assignmentResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Asignación no encontrada o inactiva'
|
||||
});
|
||||
}
|
||||
|
||||
const assignment = assignmentResult.rows[0];
|
||||
|
||||
// Obtener técnico actual
|
||||
const tecnico_id = req.user?.id || 1;
|
||||
|
||||
// Construir query de actualización
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
const oldValues = {};
|
||||
|
||||
if (estimated_hours !== undefined) {
|
||||
updateFields.push(`estimated_hours = $${params.length + 1}`);
|
||||
params.push(estimated_hours);
|
||||
oldValues.estimated_hours = assignment.estimated_hours;
|
||||
}
|
||||
|
||||
if (actual_hours !== undefined) {
|
||||
updateFields.push(`actual_hours = $${params.length + 1}`);
|
||||
params.push(actual_hours);
|
||||
oldValues.actual_hours = assignment.actual_hours;
|
||||
}
|
||||
|
||||
if (notes !== undefined) {
|
||||
updateFields.push(`notes = $${params.length + 1}`);
|
||||
params.push(notes);
|
||||
oldValues.notes = assignment.notes;
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'No se proporcionaron campos para actualizar'
|
||||
});
|
||||
}
|
||||
|
||||
params.push(id, recursoId);
|
||||
const updateQuery = `
|
||||
UPDATE dtic.tarea_recursos
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE tarea_id = $${params.length - 1} AND recurso_id = $${params.length} AND activo = true
|
||||
`;
|
||||
|
||||
await executeQuery(updateQuery, params);
|
||||
|
||||
// TODO: Registrar en historial - tabla tarea_recurso_historial no existe
|
||||
// const historyQuery = `
|
||||
// INSERT INTO dtic.tarea_recurso_historial
|
||||
// (tarea_recurso_id, action, tecnico_id, old_values, new_values, details)
|
||||
// VALUES ($1, 'updated', $2, $3, $4, $5)
|
||||
// `;
|
||||
|
||||
// const newValues = { estimated_hours, actual_hours, notes };
|
||||
// await executeQuery(historyQuery, [
|
||||
// assignment.id,
|
||||
// tecnico_id,
|
||||
// JSON.stringify(oldValues),
|
||||
// JSON.stringify(newValues),
|
||||
// `Asignación actualizada: ${assignment.task_title} - ${assignment.resource_name}`
|
||||
// ]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Asignación actualizada exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error actualizando asignación:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/tareas/:id/recursos/:recursoId - Desasignar recurso de tarea
|
||||
router.delete('/tareas/:id/recursos/:recursoId', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
param('recursoId').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id, recursoId } = req.params;
|
||||
|
||||
// Verificar que la asignación existe y está activa
|
||||
const assignmentQuery = `
|
||||
SELECT tr.*, t.title as task_title, r.name as resource_name
|
||||
FROM dtic.tarea_recursos tr
|
||||
JOIN dtic.tareas t ON t.id = tr.tarea_id
|
||||
JOIN dtic.recursos r ON r.id = tr.recurso_id
|
||||
WHERE tr.tarea_id = $1 AND tr.recurso_id = $2 AND tr.activo = true
|
||||
`;
|
||||
|
||||
const assignmentResult = await executeQuery(assignmentQuery, [id, recursoId]);
|
||||
|
||||
if (assignmentResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Asignación no encontrada o ya inactiva'
|
||||
});
|
||||
}
|
||||
|
||||
const assignment = assignmentResult.rows[0];
|
||||
const tecnico_id = req.user?.id || 1;
|
||||
|
||||
// Desactivar asignación
|
||||
const updateQuery = `
|
||||
UPDATE dtic.tarea_recursos
|
||||
SET activo = false, unassigned_by = $1, unassigned_at = CURRENT_TIMESTAMP
|
||||
WHERE tarea_id = $2 AND recurso_id = $3 AND activo = true
|
||||
`;
|
||||
|
||||
await executeQuery(updateQuery, [tecnico_id, id, recursoId]);
|
||||
|
||||
// TODO: Registrar en historial - tabla tarea_recurso_historial no existe
|
||||
// const historyQuery = `
|
||||
// INSERT INTO dtic.tarea_recurso_historial
|
||||
// (tarea_recurso_id, action, tecnico_id, details)
|
||||
// VALUES ($1, 'unassigned', $2, $3)
|
||||
// `;
|
||||
|
||||
// await executeQuery(historyQuery, [
|
||||
// assignment.id,
|
||||
// tecnico_id,
|
||||
// `Recurso desasignado de tarea: ${assignment.task_title}`
|
||||
// ]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Recurso desasignado exitosamente de la tarea'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error desasignando recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/recursos/:id/tareas - Obtener tareas que usan un recurso
|
||||
router.get('/recursos/:id/tareas', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
query('include_completed').optional().isBoolean()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { include_completed } = req.query;
|
||||
|
||||
// Verificar que el recurso existe
|
||||
const resourceQuery = 'SELECT id, name FROM dtic.recursos WHERE id = $1';
|
||||
const resourceResult = await executeQuery(resourceQuery, [id]);
|
||||
|
||||
if (resourceResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Recurso no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
let statusCondition = 'tr.activo = true';
|
||||
if (include_completed === 'true') {
|
||||
statusCondition = 'true'; // Incluir todas las asignaciones
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT
|
||||
tr.id,
|
||||
tr.tarea_id,
|
||||
tr.assigned_at,
|
||||
tr.estimated_hours,
|
||||
tr.actual_hours,
|
||||
tr.notes,
|
||||
tr.activo,
|
||||
t.dtic_id as tarea_dtic_id,
|
||||
t.title as tarea_title,
|
||||
t.status as tarea_status,
|
||||
t.priority as tarea_priority,
|
||||
tec.first_name || ' ' || tec.last_name as tecnico_name
|
||||
FROM dtic.tarea_recursos tr
|
||||
JOIN dtic.tareas t ON t.id = tr.tarea_id
|
||||
LEFT JOIN dtic.tecnicos tec ON tec.id = t.technician_id
|
||||
WHERE tr.recurso_id = $1 AND ${statusCondition}
|
||||
ORDER BY tr.assigned_at DESC
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Tareas que usan el recurso obtenidas exitosamente',
|
||||
data: {
|
||||
resource: resourceResult.rows[0],
|
||||
assignments: result.rows
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo tareas del recurso:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,417 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, query, validationResult } = require('express-validator');
|
||||
const { executeQuery } = require('../database');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Función helper para generar DTIC ID para tareas
|
||||
const generateDTICId = async (prefix = 'TAR') => {
|
||||
// Generar ID simple con formato TAR-XXXX
|
||||
const random = Math.floor(Math.random() * 10000);
|
||||
return `${prefix}-${random.toString().padStart(4, '0')}`;
|
||||
};
|
||||
|
||||
// GET /api/tareas - Obtener lista de tareas
|
||||
router.get('/', [
|
||||
query('page').optional().isInt({ min: 1 }).toInt(),
|
||||
query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
|
||||
query('technician_id').optional().isInt().toInt(),
|
||||
query('status').optional().isIn(['pending', 'in_progress', 'completed', 'cancelled']),
|
||||
query('priority').optional().isIn(['low', 'medium', 'high', 'urgent'])
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 20,
|
||||
technician_id,
|
||||
status,
|
||||
priority
|
||||
} = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
t.id, t.dtic_id, t.title, t.description, t.status, t.priority,
|
||||
t.created_at, t.updated_at, t.due_date, t.completed_at,
|
||||
tec.id as technician_id, tec.first_name, tec.last_name,
|
||||
CONCAT(tec.first_name, ' ', tec.last_name) as technician_name,
|
||||
COALESCE(
|
||||
json_agg(
|
||||
json_build_object(
|
||||
'id', tr.recurso_id,
|
||||
'name', r.name,
|
||||
'category', r.category,
|
||||
'dtic_id', r.dtic_id,
|
||||
'estimated_hours', tr.estimated_hours,
|
||||
'actual_hours', tr.actual_hours,
|
||||
'notes', tr.notes
|
||||
)
|
||||
) FILTER (WHERE tr.id IS NOT NULL AND tr.activo = true),
|
||||
'[]'::json
|
||||
) as assigned_resources
|
||||
FROM dtic.tareas t
|
||||
LEFT JOIN dtic.tecnicos tec ON tec.id = t.technician_id
|
||||
LEFT JOIN dtic.tarea_recursos tr ON tr.tarea_id = t.id AND tr.activo = true
|
||||
LEFT JOIN dtic.recursos r ON r.id = tr.recurso_id
|
||||
WHERE 1=1
|
||||
`;
|
||||
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
|
||||
if (technician_id) {
|
||||
conditions.push("t.technician_id = $" + (params.length + 1));
|
||||
params.push(technician_id);
|
||||
}
|
||||
|
||||
if (status) {
|
||||
conditions.push("t.status = $" + (params.length + 1));
|
||||
params.push(status);
|
||||
}
|
||||
|
||||
if (priority) {
|
||||
conditions.push("t.priority = $" + (params.length + 1));
|
||||
params.push(priority);
|
||||
}
|
||||
|
||||
if (conditions.length > 0) {
|
||||
query += " AND " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
query += " GROUP BY t.id, tec.id, tec.first_name, tec.last_name ORDER BY t.created_at DESC";
|
||||
|
||||
// Paginación
|
||||
const offset = (page - 1) * limit;
|
||||
query += ` LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
|
||||
params.push(limit, offset);
|
||||
|
||||
const result = await executeQuery(query, params);
|
||||
|
||||
// Obtener total para paginación
|
||||
let countQuery = "SELECT COUNT(*) as total FROM dtic.tareas WHERE 1=1";
|
||||
const countParams = conditions.length > 0 ? params.slice(0, -2) : [];
|
||||
|
||||
if (conditions.length > 0) {
|
||||
countQuery += " AND " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
const countResult = await executeQuery(countQuery, countParams);
|
||||
const total = parseInt(countResult.rows[0].total);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Tareas obtenidas exitosamente',
|
||||
data: {
|
||||
tasks: result.rows,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
pages: Math.ceil(total / limit)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo tareas:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/tareas/:id - Obtener tarea específica
|
||||
router.get('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
|
||||
const query = `
|
||||
SELECT
|
||||
t.*,
|
||||
tec.id as technician_id, tec.first_name, tec.last_name,
|
||||
CONCAT(tec.first_name, ' ', tec.last_name) as technician_name,
|
||||
COALESCE(
|
||||
json_agg(
|
||||
json_build_object(
|
||||
'id', tr.recurso_id,
|
||||
'name', r.name,
|
||||
'category', r.category,
|
||||
'dtic_id', r.dtic_id,
|
||||
'estimated_hours', tr.estimated_hours,
|
||||
'actual_hours', tr.actual_hours,
|
||||
'notes', tr.notes
|
||||
)
|
||||
) FILTER (WHERE tr.id IS NOT NULL AND tr.activo = true),
|
||||
'[]'::json
|
||||
) as assigned_resources
|
||||
FROM dtic.tareas t
|
||||
LEFT JOIN dtic.tecnicos tec ON tec.id = t.technician_id
|
||||
LEFT JOIN dtic.tarea_recursos tr ON tr.tarea_id = t.id AND tr.activo = true
|
||||
LEFT JOIN dtic.recursos r ON r.id = tr.recurso_id
|
||||
WHERE t.id = $1
|
||||
GROUP BY t.id, tec.id, tec.first_name, tec.last_name
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tarea no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Tarea obtenida exitosamente',
|
||||
data: { task: result.rows[0] }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo tarea:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/tareas - Crear nueva tarea
|
||||
router.post('/', [
|
||||
body('title').trim().isLength({ min: 3, max: 200 }),
|
||||
body('description').optional().trim().isLength({ max: 1000 }),
|
||||
body('technician_id').optional().isInt({ min: 1 }).toInt(),
|
||||
body('priority').optional().isIn(['low', 'medium', 'high', 'urgent']),
|
||||
body('due_date').optional().isISO8601()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { title, description, technician_id, priority = 'medium', due_date } = req.body;
|
||||
|
||||
// Verificar que el técnico existe si se especifica
|
||||
if (technician_id) {
|
||||
const techQuery = 'SELECT id FROM dtic.tecnicos WHERE id = $1 AND is_active = true';
|
||||
const techResult = await executeQuery(techQuery, [technician_id]);
|
||||
if (techResult.rows.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado o inactivo'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Generar DTIC ID
|
||||
const dticId = await generateDTICId('TAR');
|
||||
|
||||
// Insertar tarea
|
||||
const query = `
|
||||
INSERT INTO dtic.tareas
|
||||
(dtic_id, title, description, technician_id, priority, due_date, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [
|
||||
dticId, title, description, technician_id, priority, due_date, 'pending'
|
||||
]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Tarea creada exitosamente',
|
||||
data: {
|
||||
task_id: result.rows[0].id,
|
||||
dtic_id: dticId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando tarea:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/tareas/:id - Actualizar tarea
|
||||
router.put('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('title').optional().trim().isLength({ min: 3, max: 200 }),
|
||||
body('description').optional().trim().isLength({ max: 1000 }),
|
||||
body('technician_id').optional().isInt({ min: 1 }).toInt(),
|
||||
body('status').optional().isIn(['pending', 'in_progress', 'completed', 'cancelled']),
|
||||
body('priority').optional().isIn(['low', 'medium', 'high', 'urgent']),
|
||||
body('due_date').optional().isISO8601()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { title, description, technician_id, status, priority, due_date } = req.body;
|
||||
|
||||
// Verificar que la tarea existe
|
||||
const existingQuery = 'SELECT * FROM dtic.tareas WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tarea no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar técnico si se está cambiando
|
||||
if (technician_id) {
|
||||
const techQuery = 'SELECT id FROM dtic.tecnicos WHERE id = $1 AND is_active = true';
|
||||
const techResult = await executeQuery(techQuery, [technician_id]);
|
||||
if (techResult.rows.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado o inactivo'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Construir query de actualización
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
|
||||
if (title !== undefined) {
|
||||
updateFields.push(`title = $${params.length + 1}`);
|
||||
params.push(title);
|
||||
}
|
||||
if (description !== undefined) {
|
||||
updateFields.push(`description = $${params.length + 1}`);
|
||||
params.push(description);
|
||||
}
|
||||
if (technician_id !== undefined) {
|
||||
updateFields.push(`technician_id = $${params.length + 1}`);
|
||||
params.push(technician_id);
|
||||
}
|
||||
if (status !== undefined) {
|
||||
updateFields.push(`status = $${params.length + 1}`);
|
||||
params.push(status);
|
||||
// Si se marca como completada, actualizar completed_at
|
||||
if (status === 'completed') {
|
||||
updateFields.push(`completed_at = CURRENT_TIMESTAMP`);
|
||||
}
|
||||
}
|
||||
if (priority !== undefined) {
|
||||
updateFields.push(`priority = $${params.length + 1}`);
|
||||
params.push(priority);
|
||||
}
|
||||
if (due_date !== undefined) {
|
||||
updateFields.push(`due_date = $${params.length + 1}`);
|
||||
params.push(due_date);
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'No se proporcionaron campos para actualizar'
|
||||
});
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const query = `
|
||||
UPDATE dtic.tareas
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
`;
|
||||
|
||||
await executeQuery(query, params);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Tarea actualizada exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error actualizando tarea:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/tareas/:id - Eliminar tarea
|
||||
router.delete('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
|
||||
// Verificar que la tarea existe
|
||||
const existingQuery = 'SELECT * FROM dtic.tareas WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Tarea no encontrada'
|
||||
});
|
||||
}
|
||||
|
||||
// Eliminar tarea
|
||||
await executeQuery('DELETE FROM dtic.tareas WHERE id = $1', [id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Tarea eliminada exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error eliminando tarea:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,562 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, query, validationResult } = require('express-validator');
|
||||
const { pool } = require('../database');
|
||||
const auth = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Middleware de autenticación (temporalmente comentado para desarrollo)
|
||||
// router.use(auth);
|
||||
|
||||
// Función helper para ejecutar queries
|
||||
const executeQuery = async (query, params = []) => {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
const result = await client.query(query, params);
|
||||
return result;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
// Función helper para generar DTIC ID
|
||||
const generateDTICId = async (prefix = 'TEC') => {
|
||||
// Generar ID simple sin función de PostgreSQL por ahora
|
||||
const timestamp = Date.now().toString().slice(-4);
|
||||
const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
|
||||
return `${prefix}-${timestamp}${random}`;
|
||||
};
|
||||
|
||||
// Función helper para validar email único
|
||||
const isEmailUnique = async (email, excludeId = null) => {
|
||||
let query = 'SELECT id FROM dtic.tecnicos WHERE email = $1';
|
||||
const params = [email];
|
||||
|
||||
if (excludeId) {
|
||||
query += ' AND id != $2';
|
||||
params.push(excludeId);
|
||||
}
|
||||
|
||||
const result = await executeQuery(query, params);
|
||||
return result.rows.length === 0;
|
||||
};
|
||||
|
||||
// GET /api/tecnicos - Obtener lista de técnicos con filtros
|
||||
router.get('/', [
|
||||
query('page').optional().isInt({ min: 1 }).toInt(),
|
||||
query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
|
||||
query('search').optional().isString().trim(),
|
||||
query('department').optional().isIn(['dtic', 'sistemas', 'redes', 'seguridad']),
|
||||
query('role').optional().isIn(['admin', 'technician', 'viewer']),
|
||||
query('status').optional().isIn(['active', 'inactive', 'all'])
|
||||
], async (req, res) => {
|
||||
try {
|
||||
// Validar parámetros
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 12,
|
||||
search,
|
||||
department,
|
||||
role,
|
||||
status
|
||||
} = req.query;
|
||||
|
||||
// Construir query base
|
||||
let query = `
|
||||
SELECT
|
||||
tec.id, tec.dtic_id, tec.first_name, tec.last_name,
|
||||
CONCAT(tec.first_name, ' ', tec.last_name) as full_name,
|
||||
tec.email, tec.phone, tec.department, tec.role, tec.is_active,
|
||||
tec.created_at, tec.updated_at,
|
||||
COUNT(t.id) as active_tasks
|
||||
FROM dtic.tecnicos tec
|
||||
LEFT JOIN dtic.tareas t ON t.technician_id = tec.id AND t.status IN ('pending', 'in_progress')
|
||||
WHERE 1=1
|
||||
`;
|
||||
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
|
||||
// Filtros
|
||||
if (search) {
|
||||
conditions.push("(tec.first_name ILIKE $1 OR tec.last_name ILIKE $1 OR tec.email ILIKE $1 OR tec.dtic_id ILIKE $1)");
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
if (department) {
|
||||
conditions.push("tec.department = $" + (params.length + 1));
|
||||
params.push(department);
|
||||
}
|
||||
|
||||
if (role) {
|
||||
conditions.push("tec.role = $" + (params.length + 1));
|
||||
params.push(role);
|
||||
}
|
||||
|
||||
if (status) {
|
||||
if (status === 'active') {
|
||||
conditions.push("tec.is_active = $" + (params.length + 1));
|
||||
params.push(true);
|
||||
} else if (status === 'inactive') {
|
||||
conditions.push("tec.is_active = $" + (params.length + 1));
|
||||
params.push(false);
|
||||
}
|
||||
// 'all' no agrega condición (muestra todos)
|
||||
}
|
||||
// Por defecto mostrar todos los técnicos (activos e inactivos)
|
||||
|
||||
if (conditions.length > 0) {
|
||||
query += " AND " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
query += " GROUP BY tec.id ORDER BY tec.is_active DESC, tec.last_name, tec.first_name";
|
||||
|
||||
// Paginación
|
||||
const offset = (page - 1) * limit;
|
||||
query += ` LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
|
||||
params.push(limit, offset);
|
||||
|
||||
// Ejecutar query principal
|
||||
console.log('[DEBUG] Executing query:', query);
|
||||
console.log('[DEBUG] With params:', params);
|
||||
const result = await executeQuery(query, params);
|
||||
|
||||
// Obtener total para paginación
|
||||
let countQuery = "SELECT COUNT(*) as total FROM dtic.tecnicos tec WHERE 1=1";
|
||||
const countParams = [];
|
||||
|
||||
if (conditions.length > 0) {
|
||||
countQuery += " AND " + conditions.join(" AND ");
|
||||
countParams.push(...params.slice(0, -2));
|
||||
}
|
||||
|
||||
const countResult = await executeQuery(countQuery, countParams);
|
||||
const total = parseInt(countResult.rows[0].total);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Técnicos obtenidos exitosamente',
|
||||
data: {
|
||||
tecnicos: result.rows,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
pages: Math.ceil(total / limit)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo técnicos:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/tecnicos/:id - Obtener técnico específico
|
||||
router.get('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { include_tasks } = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
t.*,
|
||||
COUNT(ts.id) as total_tasks,
|
||||
COUNT(CASE WHEN ts.status = 'completed' THEN 1 END) as completed_tasks,
|
||||
COUNT(CASE WHEN ts.status IN ('pending', 'in_progress') THEN 1 END) as active_tasks
|
||||
FROM dtic.tecnicos t
|
||||
LEFT JOIN dtic.tareas ts ON ts.technician_id = t.id
|
||||
WHERE t.id = $1
|
||||
GROUP BY t.id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const technician = result.rows[0];
|
||||
|
||||
// Incluir tareas recientes si se solicita
|
||||
if (include_tasks === 'true') {
|
||||
const tasksQuery = `
|
||||
SELECT id, dtic_id, title, status, priority, created_at, due_date
|
||||
FROM dtic.tareas
|
||||
WHERE technician_id = $1
|
||||
ORDER BY created_at DESC
|
||||
LIMIT 5
|
||||
`;
|
||||
const tasksResult = await executeQuery(tasksQuery, [id]);
|
||||
technician.recent_tasks = tasksResult.rows;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Técnico obtenido exitosamente',
|
||||
data: { technician }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo técnico:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/tecnicos - Crear nuevo técnico
|
||||
router.post('/', [
|
||||
body('first_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('last_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('email').isEmail().normalizeEmail(),
|
||||
body('department').isIn(['dtic', 'sistemas', 'redes', 'seguridad']),
|
||||
body('role').isIn(['admin', 'technician', 'viewer']),
|
||||
body('phone').optional()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { first_name, last_name, email, department, role, phone } = req.body;
|
||||
|
||||
// Verificar email único
|
||||
if (!(await isEmailUnique(email))) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El email ya está registrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Generar DTIC ID
|
||||
const dticId = await generateDTICId('TEC');
|
||||
|
||||
// Insertar técnico (apellido siempre en mayúsculas)
|
||||
const query = `
|
||||
INSERT INTO dtic.tecnicos
|
||||
(dtic_id, first_name, last_name, email, phone, department, role, is_active)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [
|
||||
dticId, first_name, last_name.toUpperCase(), email, phone, department, role, true
|
||||
]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Técnico creado exitosamente',
|
||||
data: {
|
||||
technician_id: result.rows[0].id,
|
||||
dtic_id: dticId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando técnico:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/tecnicos/:id - Actualizar técnico
|
||||
router.put('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
query('action').optional().isIn(['change_password']),
|
||||
body('first_name').optional().trim().isLength({ min: 2, max: 50 }),
|
||||
body('last_name').optional().trim().isLength({ min: 2, max: 50 }),
|
||||
body('email').optional().isEmail().normalizeEmail(),
|
||||
body('department').optional().isIn(['dtic', 'sistemas', 'redes', 'seguridad']),
|
||||
body('role').optional().isIn(['admin', 'technician', 'viewer']),
|
||||
body('phone').optional(),
|
||||
body('is_active').optional().isBoolean(),
|
||||
body('new_password').optional().isLength({ min: 8 }),
|
||||
body('force_change').optional().isBoolean()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { action } = req.query;
|
||||
const { first_name, last_name, email, department, role, phone, is_active, new_password, force_change } = req.body;
|
||||
|
||||
// Verificar si es cambio de contraseña
|
||||
if (action === 'change_password') {
|
||||
return await changeTechnicianPassword(id, { new_password, force_change }, res);
|
||||
}
|
||||
|
||||
// Verificar que el técnico existe
|
||||
const existingQuery = 'SELECT * FROM dtic.tecnicos WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar email único si se está cambiando
|
||||
if (email && email !== existingResult.rows[0].email) {
|
||||
if (!(await isEmailUnique(email, id))) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El email ya está registrado por otro técnico'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Construir query de actualización
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
|
||||
if (first_name !== undefined) {
|
||||
updateFields.push(`first_name = $${params.length + 1}`);
|
||||
params.push(first_name);
|
||||
}
|
||||
if (last_name !== undefined) {
|
||||
updateFields.push(`last_name = $${params.length + 1}`);
|
||||
params.push(last_name.toUpperCase()); // Siempre convertir apellido a mayúsculas
|
||||
}
|
||||
if (email !== undefined) {
|
||||
updateFields.push(`email = $${params.length + 1}`);
|
||||
params.push(email);
|
||||
}
|
||||
if (department !== undefined) {
|
||||
updateFields.push(`department = $${params.length + 1}`);
|
||||
params.push(department);
|
||||
}
|
||||
if (role !== undefined) {
|
||||
updateFields.push(`role = $${params.length + 1}`);
|
||||
params.push(role);
|
||||
}
|
||||
if (phone !== undefined) {
|
||||
updateFields.push(`phone = $${params.length + 1}`);
|
||||
params.push(phone);
|
||||
}
|
||||
if (is_active !== undefined) {
|
||||
updateFields.push(`is_active = $${params.length + 1}`);
|
||||
params.push(is_active);
|
||||
}
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'No se proporcionaron campos para actualizar'
|
||||
});
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const query = `
|
||||
UPDATE dtic.tecnicos
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
`;
|
||||
|
||||
await executeQuery(query, params);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Técnico actualizado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error actualizando técnico:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/tecnicos/:id - Eliminar técnico
|
||||
router.delete('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
|
||||
// Verificar que el técnico existe
|
||||
const existingQuery = 'SELECT * FROM dtic.tecnicos WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const technician = existingResult.rows[0];
|
||||
|
||||
if (technician.is_active) {
|
||||
// Verificar tareas activas antes de desactivar
|
||||
const tasksQuery = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM dtic.tareas
|
||||
WHERE technician_id = $1 AND status IN ('pending', 'in_progress')
|
||||
`;
|
||||
const tasksResult = await executeQuery(tasksQuery, [id]);
|
||||
|
||||
if (parseInt(tasksResult.rows[0].count) > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'No se puede desactivar el técnico porque tiene tareas activas'
|
||||
});
|
||||
}
|
||||
|
||||
// Desactivar técnico
|
||||
await executeQuery('UPDATE dtic.tecnicos SET is_active = false WHERE id = $1', [id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Técnico desactivado exitosamente'
|
||||
});
|
||||
} else {
|
||||
// Verificar tareas activas antes de eliminar permanentemente
|
||||
const tasksQuery = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM dtic.tareas
|
||||
WHERE technician_id = $1 AND status IN ('pending', 'in_progress')
|
||||
`;
|
||||
const tasksResult = await executeQuery(tasksQuery, [id]);
|
||||
|
||||
if (parseInt(tasksResult.rows[0].count) > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'No se puede eliminar permanentemente el técnico porque tiene tareas activas'
|
||||
});
|
||||
}
|
||||
|
||||
// Eliminar permanentemente
|
||||
await executeQuery('DELETE FROM dtic.tecnicos WHERE id = $1', [id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Técnico eliminado permanentemente del sistema'
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error eliminando técnico:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Función para cambiar contraseña de técnico
|
||||
const changeTechnicianPassword = async (id, { new_password, force_change }, res) => {
|
||||
try {
|
||||
// Verificar que el técnico existe
|
||||
const existingQuery = 'SELECT * FROM dtic.tecnicos WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Técnico no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Validar contraseña
|
||||
if (!new_password || new_password.length < 8) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'La contraseña debe tener al menos 8 caracteres'
|
||||
});
|
||||
}
|
||||
|
||||
// Validar fortaleza de contraseña
|
||||
const hasUpperCase = /[A-Z]/.test(new_password);
|
||||
const hasLowerCase = /[a-z]/.test(new_password);
|
||||
const hasNumbers = /\d/.test(new_password);
|
||||
const hasNonalphas = /[!@#$%^&*()_+\-=\[\]{};\':"\\|,.<>\/?]/.test(new_password);
|
||||
|
||||
if (!(hasUpperCase && hasLowerCase && hasNumbers && hasNonalphas)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'La contraseña debe contener mayúsculas, minúsculas, números y caracteres especiales'
|
||||
});
|
||||
}
|
||||
|
||||
// Hashear nueva contraseña
|
||||
const bcrypt = require('bcryptjs');
|
||||
const hashedPassword = await bcrypt.hash(new_password, 12);
|
||||
|
||||
// Actualizar contraseña
|
||||
const query = 'UPDATE dtic.tecnicos SET password_hash = $1, updated_at = CURRENT_TIMESTAMP WHERE id = $2';
|
||||
await executeQuery(query, [hashedPassword, id]);
|
||||
|
||||
// Log de auditoría
|
||||
console.log(`[AUDIT] Contraseña cambiada para técnico ID: ${id}, force_change: ${force_change || false}`);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Contraseña cambiada exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error cambiando contraseña:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,414 +0,0 @@
|
||||
const express = require('express');
|
||||
const { body, param, query, validationResult } = require('express-validator');
|
||||
const { Pool } = require('pg');
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
});
|
||||
const auth = require('../middleware/auth');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// Middleware de autenticación (temporalmente comentado para desarrollo)
|
||||
// router.use(auth);
|
||||
|
||||
// Función helper para ejecutar queries
|
||||
const executeQuery = async (query, params = []) => {
|
||||
try {
|
||||
const result = await pool.query(query, params);
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Database query error:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
// Función helper para generar DTIC ID para usuarios relacionados
|
||||
const generateDTICId = async (prefix = 'USR') => {
|
||||
const query = `
|
||||
SELECT generate_dtic_id($1) as new_id
|
||||
`;
|
||||
const result = await executeQuery(query, [prefix]);
|
||||
return result.rows[0].new_id;
|
||||
};
|
||||
|
||||
// GET /api/usuarios_relacionados - Obtener lista de usuarios relacionados
|
||||
router.get('/', [
|
||||
query('page').optional().isInt({ min: 1 }).toInt(),
|
||||
query('limit').optional().isInt({ min: 1, max: 100 }).toInt(),
|
||||
query('search').optional().isString().trim(),
|
||||
query('department').optional().isString().trim()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Parámetros inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const {
|
||||
page = 1,
|
||||
limit = 20,
|
||||
search,
|
||||
department
|
||||
} = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
u.id, u.dtic_id, u.first_name, u.last_name,
|
||||
CONCAT(u.first_name, ' ', u.last_name) as full_name,
|
||||
u.email, u.phone, u.department, u.position,
|
||||
u.created_at, u.updated_at,
|
||||
COUNT(DISTINCT ra.recurso_id) as assigned_resources_count
|
||||
FROM dtic.usuarios_relacionados u
|
||||
LEFT JOIN dtic.recurso_asignaciones ra ON ra.user_id = u.id AND ra.activo = true
|
||||
WHERE 1=1
|
||||
`;
|
||||
|
||||
const params = [];
|
||||
const conditions = [];
|
||||
|
||||
// Filtros
|
||||
if (search) {
|
||||
conditions.push("(u.first_name ILIKE $1 OR u.last_name ILIKE $1 OR u.email ILIKE $1 OR u.dtic_id ILIKE $1)");
|
||||
params.push(`%${search}%`);
|
||||
}
|
||||
|
||||
if (department) {
|
||||
conditions.push("u.department ILIKE $" + (params.length + 1));
|
||||
params.push(`%${department}%`);
|
||||
}
|
||||
|
||||
if (conditions.length > 0) {
|
||||
query += " AND " + conditions.join(" AND ");
|
||||
}
|
||||
|
||||
query += " GROUP BY u.id ORDER BY u.last_name, u.first_name";
|
||||
|
||||
// Paginación
|
||||
const offset = (page - 1) * limit;
|
||||
query += ` LIMIT $${params.length + 1} OFFSET $${params.length + 2}`;
|
||||
params.push(limit, offset);
|
||||
|
||||
const result = await executeQuery(query, params);
|
||||
|
||||
// Obtener total para paginación
|
||||
let countQuery = "SELECT COUNT(*) as total FROM dtic.usuarios_relacionados u WHERE 1=1";
|
||||
const countParams = [];
|
||||
|
||||
if (conditions.length > 0) {
|
||||
countQuery += " AND " + conditions.join(" AND ");
|
||||
countParams.push(...params.slice(0, -2));
|
||||
}
|
||||
|
||||
const countResult = await executeQuery(countQuery, countParams);
|
||||
const total = parseInt(countResult.rows[0].total);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Usuarios relacionados obtenidos exitosamente',
|
||||
data: {
|
||||
usuarios: result.rows,
|
||||
pagination: {
|
||||
page,
|
||||
limit,
|
||||
total,
|
||||
pages: Math.ceil(total / limit)
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo usuarios relacionados:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/usuarios_relacionados/:id - Obtener usuario asignado específico
|
||||
router.get('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { include_resources } = req.query;
|
||||
|
||||
let query = `
|
||||
SELECT
|
||||
u.*,
|
||||
COUNT(DISTINCT ra.recurso_id) as total_assigned_resources
|
||||
FROM dtic.usuarios_relacionados u
|
||||
LEFT JOIN dtic.recurso_asignaciones ra ON ra.user_id = u.id AND ra.activo = true
|
||||
WHERE u.id = $1
|
||||
GROUP BY u.id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [id]);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Usuario asignado no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
const usuario = result.rows[0];
|
||||
|
||||
// Obtener recursos relacionados si se solicita
|
||||
if (include_resources === 'true') {
|
||||
const resourcesQuery = `
|
||||
SELECT
|
||||
r.id, r.dtic_id, r.name, r.category, r.status, r.location,
|
||||
ra.assigned_at
|
||||
FROM dtic.recurso_asignaciones ra
|
||||
JOIN dtic.recursos r ON r.id = ra.recurso_id
|
||||
WHERE ra.user_id = $1 AND ra.activo = true
|
||||
ORDER BY ra.assigned_at DESC
|
||||
`;
|
||||
const resourcesResult = await executeQuery(resourcesQuery, [id]);
|
||||
usuario.assigned_resources = resourcesResult.rows;
|
||||
}
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Usuario asignado obtenido exitosamente',
|
||||
data: { usuario }
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error obteniendo usuario asignado:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/usuarios_relacionados - Crear nuevo usuario asignado
|
||||
router.post('/', [
|
||||
body('first_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('last_name').trim().isLength({ min: 2, max: 50 }),
|
||||
body('email').optional().isEmail().normalizeEmail(),
|
||||
body('phone').optional().isMobilePhone('es-AR'),
|
||||
body('department').optional().trim().isLength({ max: 100 }),
|
||||
body('position').optional().trim().isLength({ max: 100 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { first_name, last_name, email, phone, department, position } = req.body;
|
||||
|
||||
// Verificar email único si se proporciona
|
||||
if (email) {
|
||||
const emailCheck = await executeQuery('SELECT id FROM dtic.usuarios_relacionados WHERE email = $1', [email]);
|
||||
if (emailCheck.rows.length > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El email ya está registrado'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Generar DTIC ID
|
||||
const dticId = await generateDTICId('USR');
|
||||
|
||||
// Insertar usuario relacionado
|
||||
const query = `
|
||||
INSERT INTO dtic.usuarios_relacionados
|
||||
(dtic_id, first_name, last_name, email, phone, department, position)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
RETURNING id
|
||||
`;
|
||||
|
||||
const result = await executeQuery(query, [
|
||||
dticId, first_name, last_name.toUpperCase(), email, phone, department, position
|
||||
]);
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Usuario asignado creado exitosamente',
|
||||
data: {
|
||||
usuario_id: result.rows[0].id,
|
||||
dtic_id: dticId
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error creando usuario asignado:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/usuarios_relacionados/:id - Actualizar usuario asignado
|
||||
router.put('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt(),
|
||||
body('first_name').optional().trim().isLength({ min: 2, max: 50 }),
|
||||
body('last_name').optional().trim().isLength({ min: 2, max: 50 }),
|
||||
body('email').optional().isEmail().normalizeEmail(),
|
||||
body('phone').optional().isMobilePhone('es-AR'),
|
||||
body('department').optional().trim().isLength({ max: 100 }),
|
||||
body('position').optional().trim().isLength({ max: 100 })
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos inválidos',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
const { first_name, last_name, email, phone, department, position } = req.body;
|
||||
|
||||
// Verificar que el usuario existe
|
||||
const existingQuery = 'SELECT * FROM dtic.usuarios_relacionados WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Usuario asignado no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar email único si se está cambiando
|
||||
if (email && email !== existingResult.rows[0].email) {
|
||||
const emailCheck = await executeQuery('SELECT id FROM dtic.usuarios_relacionados WHERE email = $1 AND id != $2', [email, id]);
|
||||
if (emailCheck.rows.length > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'El email ya está registrado por otro usuario'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Construir query de actualización
|
||||
const updateFields = [];
|
||||
const params = [];
|
||||
|
||||
const allowedFields = ['first_name', 'last_name', 'email', 'phone', 'department', 'position'];
|
||||
allowedFields.forEach(field => {
|
||||
if (req.body[field] !== undefined) {
|
||||
updateFields.push(`${field} = $${params.length + 1}`);
|
||||
params.push(field === 'last_name' ? req.body[field].toUpperCase() : req.body[field]);
|
||||
}
|
||||
});
|
||||
|
||||
if (updateFields.length === 0) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'No se proporcionaron campos para actualizar'
|
||||
});
|
||||
}
|
||||
|
||||
params.push(id);
|
||||
const query = `
|
||||
UPDATE dtic.usuarios_relacionados
|
||||
SET ${updateFields.join(', ')}
|
||||
WHERE id = $${params.length}
|
||||
`;
|
||||
|
||||
await executeQuery(query, params);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Usuario asignado actualizado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error actualizando usuario asignado:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE /api/usuarios_relacionados/:id - Eliminar usuario asignado
|
||||
router.delete('/:id', [
|
||||
param('id').isInt({ min: 1 }).toInt()
|
||||
], async (req, res) => {
|
||||
try {
|
||||
const errors = validationResult(req);
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'ID inválido',
|
||||
errors: errors.array()
|
||||
});
|
||||
}
|
||||
|
||||
const { id } = req.params;
|
||||
|
||||
// Verificar que el usuario existe
|
||||
const existingQuery = 'SELECT * FROM dtic.usuarios_relacionados WHERE id = $1';
|
||||
const existingResult = await executeQuery(existingQuery, [id]);
|
||||
|
||||
if (existingResult.rows.length === 0) {
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
message: 'Usuario asignado no encontrado'
|
||||
});
|
||||
}
|
||||
|
||||
// Verificar que no tenga recursos relacionados activos
|
||||
const resourcesQuery = `
|
||||
SELECT COUNT(*) as count
|
||||
FROM dtic.recurso_asignaciones
|
||||
WHERE user_id = $1 AND activo = true
|
||||
`;
|
||||
const resourcesResult = await executeQuery(resourcesQuery, [id]);
|
||||
|
||||
if (parseInt(resourcesResult.rows[0].count) > 0) {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
message: 'No se puede eliminar el usuario porque tiene recursos relacionados'
|
||||
});
|
||||
}
|
||||
|
||||
// Eliminar usuario asignado
|
||||
await executeQuery('DELETE FROM dtic.usuarios_relacionados WHERE id = $1', [id]);
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
message: 'Usuario asignado eliminado exitosamente'
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error eliminando usuario asignado:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error interno del servidor'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,97 +0,0 @@
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
const sampleTasks = [
|
||||
{
|
||||
title: 'Revisar configuración de red',
|
||||
description: 'Verificar configuración de switches y routers en sala de servidores',
|
||||
priority: 'high',
|
||||
status: 'pending'
|
||||
},
|
||||
{
|
||||
title: 'Actualizar software antivirus',
|
||||
description: 'Actualizar definiciones de virus en todos los equipos',
|
||||
priority: 'medium',
|
||||
status: 'in_progress'
|
||||
},
|
||||
{
|
||||
title: 'Configurar backup automático',
|
||||
description: 'Implementar sistema de backup diario para bases de datos críticas',
|
||||
priority: 'urgent',
|
||||
status: 'pending'
|
||||
},
|
||||
{
|
||||
title: 'Instalar actualizaciones Windows',
|
||||
description: 'Aplicar parches de seguridad en servidores Windows',
|
||||
priority: 'medium',
|
||||
status: 'completed'
|
||||
},
|
||||
{
|
||||
title: 'Diagnosticar problema de impresora',
|
||||
description: 'Resolver error de conexión en impresora multifunción',
|
||||
priority: 'low',
|
||||
status: 'pending'
|
||||
},
|
||||
{
|
||||
title: 'Configurar VPN para usuarios remotos',
|
||||
description: 'Establecer conexiones seguras para trabajo remoto',
|
||||
priority: 'high',
|
||||
status: 'in_progress'
|
||||
},
|
||||
{
|
||||
title: 'Auditoría de seguridad mensual',
|
||||
description: 'Revisar logs y vulnerabilidades del sistema',
|
||||
priority: 'medium',
|
||||
status: 'pending'
|
||||
},
|
||||
{
|
||||
title: 'Migración de datos a nuevo servidor',
|
||||
description: 'Transferir archivos y configuraciones al servidor actualizado',
|
||||
priority: 'urgent',
|
||||
status: 'pending'
|
||||
}
|
||||
];
|
||||
|
||||
async function insertSampleData() {
|
||||
try {
|
||||
console.log('Cleaning existing sample tasks...');
|
||||
|
||||
// Limpiar tareas existentes que podrían tener IDs incorrectos
|
||||
await executeQuery('DELETE FROM dtic.tareas WHERE dtic_id LIKE \'TAR%\' AND title IN ($1, $2, $3, $4, $5, $6, $7, $8)', [
|
||||
'Revisar configuración de red',
|
||||
'Actualizar software antivirus',
|
||||
'Configurar backup automático',
|
||||
'Instalar actualizaciones Windows',
|
||||
'Diagnosticar problema de impresora',
|
||||
'Configurar VPN para usuarios remotos',
|
||||
'Auditoría de seguridad mensual',
|
||||
'Migración de datos a nuevo servidor'
|
||||
]);
|
||||
|
||||
console.log('Inserting sample tasks with correct DTIC IDs...');
|
||||
|
||||
for (const task of sampleTasks) {
|
||||
const dticId = 'TAR-' + Math.floor(Math.random() * 10000).toString().padStart(4, '0');
|
||||
|
||||
await executeQuery(
|
||||
'INSERT INTO dtic.tareas (dtic_id, title, description, priority, status, created_at) VALUES ($1, $2, $3, $4, $5, CURRENT_TIMESTAMP)',
|
||||
[dticId, task.title, task.description, task.priority, task.status]
|
||||
);
|
||||
|
||||
console.log(`✓ Inserted task: ${task.title} (ID: ${dticId})`);
|
||||
}
|
||||
|
||||
console.log('\n🎉 Sample tasks inserted successfully with correct DTIC IDs!');
|
||||
console.log('You can now view the tasks in the TareasRefactored page.');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error inserting sample data:', error);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run if called directly
|
||||
if (require.main === module) {
|
||||
insertSampleData();
|
||||
}
|
||||
|
||||
module.exports = { insertSampleData, sampleTasks };
|
||||
@@ -1,202 +0,0 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const helmet = require('helmet');
|
||||
const compression = require('compression');
|
||||
const rateLimit = require('express-rate-limit');
|
||||
require('dotenv').config();
|
||||
|
||||
// Configuración de PostgreSQL
|
||||
const { Pool } = require('pg');
|
||||
const pool = new Pool({
|
||||
connectionString: process.env.DATABASE_URL,
|
||||
max: 20,
|
||||
idleTimeoutMillis: 30000,
|
||||
connectionTimeoutMillis: 2000,
|
||||
});
|
||||
|
||||
// Establecer search_path para incluir el esquema dtic
|
||||
pool.on('connect', (client) => {
|
||||
client.query('SET search_path TO dtic, public');
|
||||
});
|
||||
|
||||
// Importar rutas
|
||||
const authRoutes = require('./routes/auth');
|
||||
const tecnicosRoutes = require('./routes/tecnicos');
|
||||
const tareasRoutes = require('./routes/tareas');
|
||||
const recursosRoutes = require('./routes/recursos');
|
||||
const usuariosRelacionadosRoutes = require('./routes/usuarios_relacionados');
|
||||
const tareaRecursosRoutes = require('./routes/tarea-recursos');
|
||||
const systemRoutes = require('./routes/system');
|
||||
|
||||
// Configuración de la aplicación
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
// Middleware de seguridad
|
||||
app.use(helmet({
|
||||
crossOriginResourcePolicy: { policy: "cross-origin" }
|
||||
}));
|
||||
|
||||
// Rate limiting - más permisivo para desarrollo
|
||||
const limiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutos
|
||||
max: 1000, // límite de 1000 requests por windowMs (aumentado para desarrollo)
|
||||
message: 'Demasiadas solicitudes desde esta IP, por favor intenta más tarde.'
|
||||
});
|
||||
app.use('/api/', limiter);
|
||||
|
||||
// Rate limiting más estricto para autenticación
|
||||
const authLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutos
|
||||
max: 5, // límite de 5 requests por windowMs
|
||||
message: 'Demasiados intentos de autenticación, por favor intenta más tarde.'
|
||||
});
|
||||
app.use('/api/auth/login', authLimiter);
|
||||
|
||||
// CORS - Allow all origins for development and remote access
|
||||
app.use(cors({
|
||||
origin: true, // Allow all origins
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
|
||||
}));
|
||||
|
||||
// Compresión
|
||||
app.use(compression());
|
||||
|
||||
// Body parsing with logging
|
||||
app.use(express.json({
|
||||
limit: '10mb',
|
||||
verify: (req, res, buf) => {
|
||||
console.log(`[PAYLOAD SIZE] ${req.method} ${req.path}: ${buf.length} bytes`);
|
||||
}
|
||||
}));
|
||||
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
|
||||
|
||||
// Logging básico
|
||||
app.use((req, res, next) => {
|
||||
console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`);
|
||||
next();
|
||||
});
|
||||
|
||||
// Health check
|
||||
app.get('/health', (req, res) => {
|
||||
res.json({ status: 'OK', timestamp: new Date().toISOString() });
|
||||
});
|
||||
|
||||
// Rutas de la API
|
||||
app.use('/api/auth', authRoutes);
|
||||
app.use('/api/tecnicos', tecnicosRoutes);
|
||||
app.use('/api/tareas', tareasRoutes);
|
||||
app.use('/api/recursos', recursosRoutes);
|
||||
app.use('/api/tarea-recursos', tareaRecursosRoutes); // Rutas para asignaciones tarea-recurso
|
||||
app.use('/api/system', systemRoutes);
|
||||
// Ruta para servir el archivo de configuración YAML
|
||||
app.get('/api/config/entities.yml', (req, res) => {
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
|
||||
// El archivo está montado en /host/_app-npm/frontend/src/config/entities.yml
|
||||
const configPath = path.join('/host', '_app-npm', 'frontend', 'src', 'config', 'entities.yml');
|
||||
|
||||
console.log(`[CONFIG] Intentando leer archivo desde: ${configPath}`);
|
||||
|
||||
fs.readFile(configPath, 'utf8', (err, data) => {
|
||||
if (err) {
|
||||
console.error('Error leyendo archivo de configuración:', err);
|
||||
console.error('Path attempted:', configPath);
|
||||
return res.status(500).json({
|
||||
success: false,
|
||||
message: 'Error al leer el archivo de configuración',
|
||||
details: process.env.NODE_ENV === 'development' ? err.message : undefined
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`[CONFIG] Archivo de configuración leído exitosamente (${data.length} bytes)`);
|
||||
res.setHeader('Content-Type', 'text/yaml');
|
||||
res.send(data);
|
||||
});
|
||||
});
|
||||
app.use('/api/usuarios_relacionados', usuariosRelacionadosRoutes);
|
||||
|
||||
// Manejo de errores 404
|
||||
app.use('/api/*', (req, res) => {
|
||||
res.status(404).json({
|
||||
success: false,
|
||||
message: 'Endpoint no encontrado'
|
||||
});
|
||||
});
|
||||
|
||||
// Middleware de manejo de errores
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('Error:', err);
|
||||
|
||||
// Error de validación
|
||||
if (err.name === 'ValidationError') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Datos de entrada inválidos',
|
||||
errors: err.errors
|
||||
});
|
||||
}
|
||||
|
||||
// Error de base de datos
|
||||
if (err.code && err.code.startsWith('23')) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'Error de integridad de datos'
|
||||
});
|
||||
}
|
||||
|
||||
// Error interno del servidor
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
message: process.env.NODE_ENV === 'production'
|
||||
? 'Error interno del servidor'
|
||||
: err.message
|
||||
});
|
||||
});
|
||||
|
||||
// Función para verificar conexión a la base de datos
|
||||
const testDatabaseConnection = async () => {
|
||||
try {
|
||||
const client = await pool.connect();
|
||||
console.log('✅ Conexión a PostgreSQL exitosa');
|
||||
client.release();
|
||||
} catch (err) {
|
||||
console.error('❌ Error conectando a PostgreSQL:', err);
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
// Iniciar servidor
|
||||
const startServer = async () => {
|
||||
await testDatabaseConnection();
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🚀 Servidor ejecutándose en puerto ${PORT}`);
|
||||
console.log(`📊 Ambiente: ${process.env.NODE_ENV || 'development'}`);
|
||||
});
|
||||
};
|
||||
|
||||
// Manejo de señales para cerrar gracefully
|
||||
process.on('SIGTERM', () => {
|
||||
console.log('SIGTERM recibido, cerrando servidor...');
|
||||
pool.end(() => {
|
||||
console.log('Pool de conexiones cerrado');
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
|
||||
process.on('SIGINT', () => {
|
||||
console.log('SIGINT recibido, cerrando servidor...');
|
||||
pool.end(() => {
|
||||
console.log('Pool de conexiones cerrado');
|
||||
process.exit(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Exportar app para uso en otros módulos si es necesario
|
||||
module.exports = { app, pool };
|
||||
|
||||
startServer();
|
||||
@@ -1,89 +0,0 @@
|
||||
const http = require('http');
|
||||
|
||||
async function testLogin() {
|
||||
return new Promise((resolve, reject) => {
|
||||
console.log('🧪 PROBANDO LOGIN DEL USUARIO');
|
||||
console.log('==============================');
|
||||
|
||||
const postData = JSON.stringify({
|
||||
email: 'rmonla@frlr.utn.edu.ar',
|
||||
password: 'utn123'
|
||||
});
|
||||
|
||||
const options = {
|
||||
hostname: 'localhost',
|
||||
port: 3001,
|
||||
path: '/api/auth/login',
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(postData)
|
||||
}
|
||||
};
|
||||
|
||||
const req = http.request(options, (res) => {
|
||||
let data = '';
|
||||
|
||||
console.log(`Estado HTTP: ${res.statusCode}`);
|
||||
console.log(`Headers:`, JSON.stringify(res.headers, null, 2));
|
||||
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
console.log(`Recibiendo chunk: ${chunk.length} bytes`);
|
||||
});
|
||||
|
||||
res.on('end', () => {
|
||||
console.log(`Datos totales recibidos: ${data.length} bytes`);
|
||||
console.log(`Contenido crudo: '${data}'`);
|
||||
|
||||
if (data.trim() === '') {
|
||||
console.log('❌ RESPUESTA VACÍA - Esto explica el error de JSON.parse');
|
||||
console.log('💡 Posibles causas:');
|
||||
console.log(' - El servidor se cerró la conexión');
|
||||
console.log(' - Error interno del servidor');
|
||||
console.log(' - Problema de CORS');
|
||||
console.log(' - El endpoint no existe');
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const responseData = JSON.parse(data);
|
||||
console.log(`Respuesta exitosa: ${responseData.success}`);
|
||||
|
||||
if (responseData.success) {
|
||||
console.log('✅ LOGIN EXITOSO');
|
||||
console.log(`Token generado: ${responseData.data.token ? 'SÍ' : 'NO'}`);
|
||||
console.log(`Usuario: ${responseData.data.user.first_name} ${responseData.data.user.last_name}`);
|
||||
console.log(`Rol: ${responseData.data.user.role}`);
|
||||
} else {
|
||||
console.log('❌ LOGIN FALLIDO');
|
||||
console.log(`Mensaje: ${responseData.message}`);
|
||||
if (responseData.errors) {
|
||||
console.log('Errores de validación:', responseData.errors);
|
||||
}
|
||||
}
|
||||
resolve();
|
||||
} catch (error) {
|
||||
console.error('❌ Error parseando respuesta JSON:', error.message);
|
||||
console.log('Contenido que causó el error:', data);
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on('error', (error) => {
|
||||
console.error('❌ Error en la petición HTTP:', error.message);
|
||||
resolve();
|
||||
});
|
||||
|
||||
req.write(postData);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
testLogin();
|
||||
}
|
||||
|
||||
module.exports = { testLogin };
|
||||
@@ -1,62 +0,0 @@
|
||||
const { executeQuery } = require('./database');
|
||||
|
||||
// Función para verificar la integridad de los datos
|
||||
async function verifyDataIntegrity() {
|
||||
try {
|
||||
console.log('🔍 Verificando integridad de datos...\n');
|
||||
|
||||
// Verificar recursos
|
||||
const recursos = await executeQuery('SELECT COUNT(*) as total, category, status FROM dtic.recursos GROUP BY category, status ORDER BY category, status');
|
||||
console.log('📦 Recursos por categoría y estado:');
|
||||
recursos.rows.forEach(row => {
|
||||
console.log(` ${row.category} (${row.status}): ${row.total}`);
|
||||
});
|
||||
|
||||
// Verificar usuarios
|
||||
const usuarios = await executeQuery('SELECT COUNT(*) as total FROM dtic.usuarios_relacionados');
|
||||
console.log(`👥 Total de usuarios relacionados: ${usuarios.rows[0].total}`);
|
||||
|
||||
// Verificar tareas
|
||||
const tareas = await executeQuery('SELECT COUNT(*) as total, status, priority FROM dtic.tareas GROUP BY status, priority ORDER BY status, priority');
|
||||
console.log('📋 Tareas por estado y prioridad:');
|
||||
tareas.rows.forEach(row => {
|
||||
console.log(` ${row.status} (${row.priority}): ${row.total}`);
|
||||
});
|
||||
|
||||
// Verificar asignaciones
|
||||
const asignaciones = await executeQuery('SELECT COUNT(*) as total FROM dtic.recurso_asignaciones WHERE activo = true');
|
||||
console.log(`🔗 Asignaciones activas: ${asignaciones.rows[0].total}`);
|
||||
|
||||
// Verificar historial
|
||||
const historial = await executeQuery('SELECT COUNT(*) as total FROM dtic.recurso_historial');
|
||||
console.log(`📜 Registros de historial: ${historial.rows[0].total}`);
|
||||
|
||||
// Mostrar algunos ejemplos
|
||||
console.log('\n📋 Ejemplos de datos:');
|
||||
|
||||
const sampleRecursos = await executeQuery('SELECT dtic_id, name, category FROM dtic.recursos LIMIT 5');
|
||||
console.log('Recursos:');
|
||||
sampleRecursos.rows.forEach(r => console.log(` ${r.dtic_id}: ${r.name} (${r.category})`));
|
||||
|
||||
const sampleUsuarios = await executeQuery('SELECT dtic_id, first_name, last_name, department FROM dtic.usuarios_relacionados LIMIT 5');
|
||||
console.log('Usuarios:');
|
||||
sampleUsuarios.rows.forEach(u => console.log(` ${u.dtic_id}: ${u.first_name} ${u.last_name} (${u.department})`));
|
||||
|
||||
const sampleTareas = await executeQuery('SELECT dtic_id, title, status FROM dtic.tareas LIMIT 5');
|
||||
console.log('Tareas:');
|
||||
sampleTareas.rows.forEach(t => console.log(` ${t.dtic_id}: ${t.title} (${t.status})`));
|
||||
|
||||
console.log('\n✅ Verificación completada exitosamente!');
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Error verificando integridad de datos:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Ejecutar si se llama directamente
|
||||
if (require.main === module) {
|
||||
verifyDataIntegrity();
|
||||
}
|
||||
|
||||
module.exports = { verifyDataIntegrity };
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,64 +0,0 @@
|
||||
# Archivo de override para personalizar configuración por entorno
|
||||
# Este archivo se combina automáticamente con docker-compose.yml
|
||||
|
||||
services:
|
||||
# Configuración específica para desarrollo
|
||||
postgres:
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB:-dtic_bitacoras}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-dtic_user}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-dtic_password}
|
||||
ports:
|
||||
- "${POSTGRES_PORT:-5432}:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./docker/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
# Volumen adicional para backups
|
||||
- ./backups:/backups
|
||||
|
||||
api:
|
||||
environment:
|
||||
NODE_ENV: ${NODE_ENV:-development}
|
||||
DATABASE_URL: postgresql://${POSTGRES_USER:-dtic_user}:${POSTGRES_PASSWORD:-dtic_password}@postgres:5432/${POSTGRES_DB:-dtic_bitacoras}
|
||||
JWT_SECRET: ${JWT_SECRET:-your-super-secret-jwt-key-change-in-production}
|
||||
PORT: ${API_PORT:-3001}
|
||||
ports:
|
||||
- "${API_PORT:-3001}:${API_PORT:-3001}"
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- /app/node_modules
|
||||
- ../:/host
|
||||
# Volumen para logs
|
||||
- ./logs:/app/logs
|
||||
depends_on:
|
||||
- postgres
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:${API_PORT:-3001}/health"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
|
||||
frontend:
|
||||
environment:
|
||||
VITE_API_URL: ${VITE_API_URL:-http://localhost:${API_PORT:-3001}/api}
|
||||
ports:
|
||||
- "${FRONTEND_PORT:-5173}:${FRONTEND_PORT:-5173}"
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
- /app/node_modules
|
||||
depends_on:
|
||||
- api
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
# Redes personalizadas
|
||||
networks:
|
||||
dtic_network:
|
||||
name: ${NETWORK_NAME:-dtic_network}
|
||||
driver: bridge
|
||||
|
||||
# Volúmenes personalizados
|
||||
volumes:
|
||||
postgres_data:
|
||||
name: ${POSTGRES_VOLUME_NAME:-dtic_bitacoras_postgres_data}
|
||||
@@ -1,77 +0,0 @@
|
||||
services:
|
||||
# Base de datos PostgreSQL
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
container_name: dtic_bitacoras_postgres
|
||||
environment:
|
||||
POSTGRES_DB: dtic_bitacoras
|
||||
POSTGRES_USER: dtic_user
|
||||
POSTGRES_PASSWORD: dtic_password
|
||||
ports:
|
||||
- "5432:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./docker/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 1G
|
||||
networks:
|
||||
- dtic_network
|
||||
|
||||
# Backend API Node.js/Express
|
||||
api:
|
||||
build:
|
||||
context: ./backend
|
||||
dockerfile: Dockerfile
|
||||
container_name: dtic_bitacoras_api
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
ports:
|
||||
- "3001:3001"
|
||||
environment:
|
||||
NODE_ENV: development
|
||||
DATABASE_URL: postgresql://dtic_user:dtic_password@postgres:5432/dtic_bitacoras
|
||||
JWT_SECRET: your-super-secret-jwt-key-change-in-production
|
||||
PORT: 3001
|
||||
depends_on:
|
||||
- postgres
|
||||
volumes:
|
||||
- ./backend:/app
|
||||
- /app/node_modules
|
||||
- ../../:/host # Montar el directorio padre del proyecto para acceder a _app-npm
|
||||
- /var/run/docker.sock:/var/run/docker.sock # Montar socket Docker para ejecutar comandos Docker
|
||||
networks:
|
||||
- dtic_network
|
||||
|
||||
# Frontend React/Vite
|
||||
frontend:
|
||||
build:
|
||||
context: ./frontend
|
||||
dockerfile: Dockerfile
|
||||
container_name: dtic_bitacoras_frontend
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
memory: 512M
|
||||
ports:
|
||||
- "5173:5173"
|
||||
depends_on:
|
||||
- api
|
||||
volumes:
|
||||
- ./frontend:/app
|
||||
- /app/node_modules
|
||||
networks:
|
||||
- dtic_network
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
|
||||
|
||||
networks:
|
||||
dtic_network:
|
||||
driver: bridge
|
||||
@@ -1,373 +0,0 @@
|
||||
-- Inicialización de base de datos PostgreSQL para DTIC Bitácoras
|
||||
-- Ejecutado automáticamente al crear el contenedor
|
||||
|
||||
-- Crear esquema principal
|
||||
CREATE SCHEMA IF NOT EXISTS dtic;
|
||||
|
||||
-- Usar el esquema dtic por defecto
|
||||
SET search_path TO dtic;
|
||||
|
||||
-- Tabla de técnicos
|
||||
CREATE TABLE IF NOT EXISTS tecnicos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
dtic_id VARCHAR(20) UNIQUE NOT NULL,
|
||||
first_name VARCHAR(50) NOT NULL,
|
||||
last_name VARCHAR(50) NOT NULL,
|
||||
email VARCHAR(100) UNIQUE NOT NULL,
|
||||
phone VARCHAR(20),
|
||||
department VARCHAR(100) NOT NULL,
|
||||
role VARCHAR(20) NOT NULL CHECK (role IN ('admin', 'technician', 'viewer')),
|
||||
password_hash VARCHAR(255),
|
||||
is_active BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices para búsquedas comunes
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_email ON tecnicos (email);
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_department ON tecnicos (department);
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_role ON tecnicos (role);
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_active ON tecnicos (is_active);
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_dtic_id ON tecnicos (dtic_id);
|
||||
|
||||
-- Tabla de tareas
|
||||
CREATE TABLE IF NOT EXISTS tareas (
|
||||
id SERIAL PRIMARY KEY,
|
||||
dtic_id VARCHAR(20) UNIQUE NOT NULL,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
technician_id INTEGER REFERENCES tecnicos(id) ON DELETE SET NULL,
|
||||
status VARCHAR(20) DEFAULT 'pending' CHECK (status IN ('pending', 'in_progress', 'completed', 'cancelled')),
|
||||
priority VARCHAR(10) DEFAULT 'medium' CHECK (priority IN ('low', 'medium', 'high', 'urgent')),
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
due_date TIMESTAMP WITH TIME ZONE,
|
||||
completed_at TIMESTAMP WITH TIME ZONE
|
||||
);
|
||||
|
||||
-- Índices para tareas
|
||||
CREATE INDEX IF NOT EXISTS idx_tareas_technician ON tareas (technician_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tareas_status ON tareas (status);
|
||||
CREATE INDEX IF NOT EXISTS idx_tareas_priority ON tareas (priority);
|
||||
CREATE INDEX IF NOT EXISTS idx_tareas_due_date ON tareas (due_date);
|
||||
|
||||
-- Tabla de auditoría
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INTEGER REFERENCES tecnicos(id) ON DELETE SET NULL,
|
||||
action VARCHAR(50) NOT NULL,
|
||||
entity_type VARCHAR(50) NOT NULL,
|
||||
entity_id INTEGER,
|
||||
old_values JSONB,
|
||||
new_values JSONB,
|
||||
ip_address INET,
|
||||
user_agent TEXT,
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices para auditoría
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_entity ON audit_log (entity_type, entity_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_audit_created ON audit_log (created_at);
|
||||
|
||||
-- Función para generar DTIC ID
|
||||
CREATE OR REPLACE FUNCTION dtic.generate_dtic_id(prefix TEXT)
|
||||
RETURNS TEXT AS $$
|
||||
DECLARE
|
||||
counter INTEGER;
|
||||
new_id TEXT;
|
||||
BEGIN
|
||||
-- Obtener el último contador para este prefijo desde todas las tablas
|
||||
SELECT COALESCE(MAX(CAST(SUBSTRING(dtic_id FROM LENGTH(prefix) + 2) AS INTEGER)), 0) + 1
|
||||
INTO counter
|
||||
FROM (
|
||||
SELECT dtic_id FROM dtic.tecnicos WHERE dtic_id LIKE prefix || '-%'
|
||||
UNION ALL
|
||||
SELECT dtic_id FROM dtic.tareas WHERE dtic_id LIKE prefix || '-%'
|
||||
UNION ALL
|
||||
SELECT dtic_id FROM dtic.recursos WHERE dtic_id LIKE prefix || '-%'
|
||||
UNION ALL
|
||||
SELECT dtic_id FROM dtic.usuarios_relacionados WHERE dtic_id LIKE prefix || '-%'
|
||||
UNION ALL
|
||||
SELECT dtic_id FROM dtic.tarea_recursos WHERE dtic_id LIKE prefix || '-%'
|
||||
) AS all_ids;
|
||||
|
||||
-- Generar nuevo ID
|
||||
new_id := prefix || '-' || LPAD(counter::TEXT, 4, '0');
|
||||
|
||||
RETURN new_id;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Función para actualizar updated_at automáticamente
|
||||
CREATE OR REPLACE FUNCTION update_updated_at_column()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = CURRENT_TIMESTAMP;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Triggers para actualizar updated_at
|
||||
CREATE TRIGGER update_tecnicos_updated_at
|
||||
BEFORE UPDATE ON tecnicos
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TRIGGER update_tareas_updated_at
|
||||
BEFORE UPDATE ON tareas
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
-- Insertar datos de ejemplo
|
||||
INSERT INTO tecnicos (dtic_id, first_name, last_name, email, password_hash, department, role, is_active) VALUES
|
||||
('TEC-0001', 'Juan', 'PÉREZ', 'juan.perez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'dtic', 'admin', true),
|
||||
('TEC-0002', 'María', 'GONZÁLEZ', 'maria.gonzalez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'sistemas', 'technician', true),
|
||||
('TEC-0003', 'Carlos', 'RODRÍGUEZ', 'carlos.rodriguez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'redes', 'technician', true),
|
||||
('TEC-0004', 'Ana', 'MARTÍNEZ', 'ana.martinez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'seguridad', 'technician', true),
|
||||
('TEC-0005', 'Luis', 'LÓPEZ', 'luis.lopez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'dtic', 'viewer', true),
|
||||
('TEC-0006', 'Laura', 'SÁNCHEZ', 'laura.sanchez@dtic.gob.ar', '$2a$12$LQv3c1yqBWVHxkd0LHAkCOYz6TtxMQJqhN8/LewdBPjYQmHqU9yO', 'sistemas', 'technician', false),
|
||||
('TEC-0007', 'Rodrigo', 'MONLA', 'rmonla@frlr.utn.edu.ar', '$2a$12$T4OKj7qWBnjtYhXGmDibP.WszYyFIF5iKEZW3TDpVE2GI9Pfmu5zS', 'dtic', 'admin', true)
|
||||
ON CONFLICT (dtic_id) DO NOTHING;
|
||||
|
||||
-- Tabla de recursos
|
||||
CREATE TABLE IF NOT EXISTS recursos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
dtic_id VARCHAR(20) UNIQUE NOT NULL,
|
||||
name VARCHAR(200) NOT NULL,
|
||||
description TEXT,
|
||||
category VARCHAR(50) NOT NULL CHECK (category IN ('hardware', 'software', 'network', 'security', 'tools', 'facilities')),
|
||||
status VARCHAR(20) DEFAULT 'available' CHECK (status IN ('available', 'assigned', 'maintenance', 'retired')),
|
||||
location VARCHAR(200),
|
||||
technical_specs JSONB,
|
||||
serial_number VARCHAR(100),
|
||||
model VARCHAR(100),
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices para recursos
|
||||
CREATE INDEX IF NOT EXISTS idx_recursos_dtic_id ON recursos (dtic_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recursos_category ON recursos (category);
|
||||
CREATE INDEX IF NOT EXISTS idx_recursos_status ON recursos (status);
|
||||
CREATE INDEX IF NOT EXISTS idx_recursos_location ON recursos (location);
|
||||
|
||||
-- Tabla de usuarios relacionados (diferentes de técnicos del sistema)
|
||||
CREATE TABLE IF NOT EXISTS usuarios_relacionados (
|
||||
id SERIAL PRIMARY KEY,
|
||||
dtic_id VARCHAR(20) UNIQUE NOT NULL,
|
||||
first_name VARCHAR(50) NOT NULL,
|
||||
last_name VARCHAR(50) NOT NULL,
|
||||
email VARCHAR(100) UNIQUE,
|
||||
phone VARCHAR(20),
|
||||
department VARCHAR(100),
|
||||
position VARCHAR(100),
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices para usuarios relacionados
|
||||
CREATE INDEX IF NOT EXISTS idx_usuarios_relacionados_dtic_id ON usuarios_relacionados (dtic_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_usuarios_relacionados_email ON usuarios_relacionados (email);
|
||||
CREATE INDEX IF NOT EXISTS idx_usuarios_relacionados_department ON usuarios_relacionados (department);
|
||||
|
||||
-- Tabla de asignaciones recurso-usuario (relación muchos a muchos)
|
||||
CREATE TABLE IF NOT EXISTS recurso_asignaciones (
|
||||
id SERIAL PRIMARY KEY,
|
||||
recurso_id INTEGER NOT NULL REFERENCES recursos(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES usuarios_relacionados(id) ON DELETE CASCADE,
|
||||
assigned_by INTEGER REFERENCES tecnicos(id), -- técnico que realizó la asignación
|
||||
assigned_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
unassigned_by INTEGER REFERENCES tecnicos(id), -- técnico que realizó la desasignación
|
||||
unassigned_at TIMESTAMP WITH TIME ZONE,
|
||||
activo BOOLEAN DEFAULT true,
|
||||
|
||||
-- Constraint único para asignaciones activas
|
||||
UNIQUE (recurso_id, user_id)
|
||||
);
|
||||
|
||||
-- Índices para asignaciones de recursos
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_asignaciones_recurso ON recurso_asignaciones (recurso_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_asignaciones_user ON recurso_asignaciones (user_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_asignaciones_activo ON recurso_asignaciones (activo);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_asignaciones_assigned_at ON recurso_asignaciones (assigned_at);
|
||||
|
||||
-- Tabla de asignaciones tarea-recurso (relación muchos a muchos)
|
||||
CREATE TABLE IF NOT EXISTS tarea_recursos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tarea_id INTEGER NOT NULL REFERENCES tareas(id) ON DELETE CASCADE,
|
||||
recurso_id INTEGER NOT NULL REFERENCES recursos(id) ON DELETE CASCADE,
|
||||
assigned_by INTEGER REFERENCES tecnicos(id), -- técnico que realizó la asignación
|
||||
assigned_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||
unassigned_by INTEGER REFERENCES tecnicos(id), -- técnico que realizó la desasignación
|
||||
unassigned_at TIMESTAMP WITH TIME ZONE,
|
||||
activo BOOLEAN DEFAULT true,
|
||||
|
||||
-- Campos adicionales específicos de la asignación
|
||||
estimated_hours DECIMAL(5,2), -- horas estimadas para usar el recurso en esta tarea
|
||||
actual_hours DECIMAL(5,2), -- horas reales utilizadas
|
||||
notes TEXT, -- notas específicas sobre el uso del recurso en esta tarea
|
||||
|
||||
-- Constraint único para asignaciones activas de la misma tarea-recurso
|
||||
UNIQUE (tarea_id, recurso_id, activo)
|
||||
);
|
||||
|
||||
-- Tabla de historial de asignaciones tarea-recurso
|
||||
CREATE TABLE IF NOT EXISTS tarea_recurso_historial (
|
||||
id SERIAL PRIMARY KEY,
|
||||
tarea_recurso_id INTEGER NOT NULL REFERENCES tarea_recursos(id) ON DELETE CASCADE,
|
||||
action VARCHAR(50) NOT NULL, -- 'assigned', 'unassigned', 'updated', 'completed'
|
||||
tecnico_id INTEGER REFERENCES tecnicos(id), -- técnico que realizó la acción
|
||||
old_values JSONB, -- valores anteriores
|
||||
new_values JSONB, -- valores nuevos
|
||||
details TEXT, -- descripción detallada de la acción
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Tabla de historial de recursos
|
||||
CREATE TABLE IF NOT EXISTS recurso_historial (
|
||||
id SERIAL PRIMARY KEY,
|
||||
recurso_id INTEGER NOT NULL REFERENCES recursos(id) ON DELETE CASCADE,
|
||||
action VARCHAR(50) NOT NULL, -- 'assigned', 'unassigned', 'maintenance', 'created', 'updated'
|
||||
usuario_id INTEGER REFERENCES usuarios_relacionados(id), -- usuario asignado (si aplica)
|
||||
tecnico_id INTEGER REFERENCES tecnicos(id), -- técnico que realizó la acción
|
||||
details TEXT, -- descripción detallada de la acción
|
||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices para asignaciones tarea-recurso
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recursos_tarea ON tarea_recursos (tarea_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recursos_recurso ON tarea_recursos (recurso_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recursos_activo ON tarea_recursos (activo);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recursos_assigned_at ON tarea_recursos (assigned_at);
|
||||
|
||||
-- Índices para historial de asignaciones tarea-recurso
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recurso_historial_tarea_recurso ON tarea_recurso_historial (tarea_recurso_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recurso_historial_action ON tarea_recurso_historial (action);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recurso_historial_tecnico ON tarea_recurso_historial (tecnico_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_tarea_recurso_historial_created ON tarea_recurso_historial (created_at);
|
||||
|
||||
-- Índices para historial de recursos
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_historial_recurso ON recurso_historial (recurso_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_historial_action ON recurso_historial (action);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_historial_tecnico ON recurso_historial (tecnico_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_recurso_historial_created ON recurso_historial (created_at);
|
||||
|
||||
-- Triggers para actualizar updated_at
|
||||
CREATE TRIGGER update_recursos_updated_at
|
||||
BEFORE UPDATE ON recursos
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
CREATE TRIGGER update_usuarios_relacionados_updated_at
|
||||
BEFORE UPDATE ON usuarios_relacionados
|
||||
FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
|
||||
|
||||
-- Función para validar asignaciones de recursos a tareas
|
||||
CREATE OR REPLACE FUNCTION validate_tarea_recurso_assignment()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Si es una nueva asignación activa
|
||||
IF NEW.activo = true THEN
|
||||
-- Verificar que el recurso esté disponible (no asignado a otras tareas activas)
|
||||
IF EXISTS (
|
||||
SELECT 1 FROM tarea_recursos tr
|
||||
WHERE tr.recurso_id = NEW.recurso_id
|
||||
AND tr.activo = true
|
||||
AND tr.id != COALESCE(NEW.id, 0)
|
||||
) THEN
|
||||
RAISE EXCEPTION 'El recurso ya está asignado a otra tarea activa';
|
||||
END IF;
|
||||
|
||||
-- Verificar que el recurso esté en estado 'available'
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM recursos r
|
||||
WHERE r.id = NEW.recurso_id
|
||||
AND r.status = 'available'
|
||||
) THEN
|
||||
RAISE EXCEPTION 'El recurso debe estar en estado disponible para ser asignado';
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger para validar asignaciones
|
||||
CREATE TRIGGER validate_tarea_recurso_assignment_trigger
|
||||
BEFORE INSERT OR UPDATE ON tarea_recursos
|
||||
FOR EACH ROW EXECUTE FUNCTION validate_tarea_recurso_assignment();
|
||||
|
||||
-- Función para actualizar estado de recursos basado en asignaciones
|
||||
CREATE OR REPLACE FUNCTION update_recurso_status_from_assignments()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
-- Si se asigna un recurso a una tarea
|
||||
IF (TG_OP = 'INSERT' AND NEW.activo = true) OR (TG_OP = 'UPDATE' AND NEW.activo = true AND OLD.activo = false) THEN
|
||||
-- Cambiar estado del recurso a 'assigned'
|
||||
UPDATE recursos SET status = 'assigned', updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = NEW.recurso_id AND status = 'available';
|
||||
|
||||
-- Si se desasigna un recurso de una tarea
|
||||
ELSIF (TG_OP = 'UPDATE' AND NEW.activo = false AND OLD.activo = true) OR TG_OP = 'DELETE' THEN
|
||||
-- Verificar si el recurso ya no está asignado a ninguna tarea activa
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM tarea_recursos tr
|
||||
WHERE tr.recurso_id = COALESCE(NEW.recurso_id, OLD.recurso_id)
|
||||
AND tr.activo = true
|
||||
) THEN
|
||||
-- Cambiar estado del recurso a 'available'
|
||||
UPDATE recursos SET status = 'available', updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = COALESCE(NEW.recurso_id, OLD.recurso_id) AND status = 'assigned';
|
||||
END IF;
|
||||
END IF;
|
||||
|
||||
RETURN COALESCE(NEW, OLD);
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- Trigger para actualizar estado de recursos
|
||||
CREATE TRIGGER update_recurso_status_from_assignments_trigger
|
||||
AFTER INSERT OR UPDATE OR DELETE ON tarea_recursos
|
||||
FOR EACH ROW EXECUTE FUNCTION update_recurso_status_from_assignments();
|
||||
|
||||
-- Insertar datos de ejemplo para recursos
|
||||
INSERT INTO recursos (dtic_id, name, description, category, status, location, technical_specs, serial_number, model) VALUES
|
||||
('REC-0001', 'Laptop Dell Latitude 5420', 'Laptop para trabajo administrativo', 'hardware', 'available', 'Oficina Principal', '{"cpu": "Intel i5", "ram": "16GB", "storage": "512GB SSD"}', 'DL5420-2025-001', 'Dell Latitude 5420'),
|
||||
('REC-0002', 'Proyector Epson EB-S41', 'Proyector para presentaciones', 'hardware', 'assigned', 'Sala de Reuniones', '{"resolution": "SVGA", "brightness": "3200 lumens"}', 'EP-S41-2025-002', 'Epson EB-S41'),
|
||||
('REC-0003', 'Antivirus Bitdefender Total Security', 'Licencia corporativa de antivirus', 'software', 'available', NULL, '{"licenses": 25, "valid_until": "2025-12-15"}', 'BD-TS-2025-003', 'Bitdefender Total Security'),
|
||||
('REC-0004', 'Router Cisco RV340', 'Router para red corporativa', 'network', 'maintenance', 'Sala de Servidores', '{"ports": "16 Gigabit", "wifi": "Dual Band"}', 'CS-RV340-2025-004', 'Cisco RV340'),
|
||||
('REC-0005', 'Kit de Herramientas de Red', 'Herramientas para mantenimiento de red', 'tools', 'available', 'Depósito Técnico', '{"items": ["Tester", "Cables", "Conectores"]}', 'KT-RD-2025-005', 'Kit Herramientas Red'),
|
||||
('REC-0006', 'Licencia Windows Server 2022', 'Licencia para servidor principal', 'software', 'assigned', 'Sala de Servidores', '{"edition": "Standard", "cores": 16}', 'WS2022-STD-006', 'Windows Server 2022')
|
||||
ON CONFLICT (dtic_id) DO NOTHING;
|
||||
|
||||
-- Insertar datos de ejemplo para usuarios relacionados
|
||||
INSERT INTO usuarios_relacionados (dtic_id, first_name, last_name, email, phone, department, position) VALUES
|
||||
('USR-0001', 'Juan', 'Pérez', 'juan.perez@empresa.com', '+54 11 1234-5678', 'Administración', 'Gerente'),
|
||||
('USR-0002', 'María', 'González', 'maria.gonzalez@empresa.com', '+54 11 2345-6789', 'Recursos Humanos', 'Coordinadora'),
|
||||
('USR-0003', 'Carlos', 'Rodríguez', 'carlos.rodriguez@empresa.com', '+54 11 3456-7890', 'IT', 'Analista'),
|
||||
('USR-0004', 'Ana', 'Martínez', 'ana.martinez@empresa.com', '+54 11 4567-8901', 'Contabilidad', 'Contadora'),
|
||||
('USR-0005', 'Luis', 'López', 'luis.lopez@empresa.com', '+54 11 5678-9012', 'Ventas', 'Vendedor')
|
||||
ON CONFLICT (dtic_id) DO NOTHING;
|
||||
|
||||
-- Insertar asignaciones de ejemplo
|
||||
INSERT INTO recurso_asignaciones (recurso_id, user_id, assigned_by) VALUES
|
||||
(2, 1, 1), -- Proyector asignado a Juan Pérez
|
||||
(6, 3, 2) -- Windows Server asignado a Carlos Rodríguez
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- Crear índices adicionales para búsquedas de texto completo
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_full_name ON tecnicos USING gin (to_tsvector('spanish', first_name || ' ' || last_name));
|
||||
CREATE INDEX IF NOT EXISTS idx_tecnicos_search ON tecnicos USING gin (to_tsvector('spanish', first_name || ' ' || last_name || ' ' || email || ' ' || dtic_id));
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_recursos_name ON recursos USING gin (to_tsvector('spanish', name || ' ' || description || ' ' || dtic_id));
|
||||
CREATE INDEX IF NOT EXISTS idx_usuarios_relacionados_name ON usuarios_relacionados USING gin (to_tsvector('spanish', first_name || ' ' || last_name || ' ' || email || ' ' || dtic_id));
|
||||
|
||||
-- Comentarios en las tablas
|
||||
COMMENT ON TABLE tecnicos IS 'Tabla principal de técnicos del sistema DTIC Bitácoras';
|
||||
COMMENT ON TABLE tareas IS 'Tabla de tareas asignadas a técnicos';
|
||||
COMMENT ON TABLE tarea_recursos IS 'Tabla de relación many-to-many entre tareas y recursos asignados';
|
||||
COMMENT ON TABLE tarea_recurso_historial IS 'Historial de asignaciones y desasignaciones de recursos a tareas';
|
||||
COMMENT ON TABLE audit_log IS 'Registro de auditoría de todas las operaciones del sistema';
|
||||
|
||||
-- Permisos básicos (ajustar según necesidades de seguridad)
|
||||
GRANT USAGE ON SCHEMA dtic TO dtic_user;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA dtic TO dtic_user;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA dtic TO dtic_user;
|
||||
@@ -1,19 +0,0 @@
|
||||
FROM node:18-alpine
|
||||
|
||||
# Establecer directorio de trabajo
|
||||
WORKDIR /app
|
||||
|
||||
# Copiar archivos de configuración de paquetes
|
||||
COPY package*.json ./
|
||||
|
||||
# Instalar dependencias
|
||||
RUN npm install
|
||||
|
||||
# Copiar código fuente
|
||||
COPY . .
|
||||
|
||||
# Exponer puerto
|
||||
EXPOSE 5173
|
||||
|
||||
# Comando para ejecutar la aplicación
|
||||
CMD ["npm", "run", "dev", "--", "--host", "0.0.0.0"]
|
||||
@@ -1,19 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>DTIC Bitácoras</title>
|
||||
<!-- Bootstrap CSS -->
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
<!-- Font Awesome -->
|
||||
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
<!-- Bootstrap JS -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
-2915
File diff suppressed because it is too large
Load Diff
@@ -1,41 +0,0 @@
|
||||
{
|
||||
"name": "dtic-bitacoras-frontend",
|
||||
"private": true,
|
||||
"version": "2.1.2",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc && vite build",
|
||||
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.1.0",
|
||||
"axios": "^1.4.0",
|
||||
"bootstrap": "^5.3.0",
|
||||
"date-fns": "^2.30.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"react": "^18.2.0",
|
||||
"react-bootstrap": "^2.7.4",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-hook-form": "^7.43.9",
|
||||
"react-hot-toast": "^2.4.1",
|
||||
"react-icons": "^4.8.0",
|
||||
"react-router-dom": "^6.8.0",
|
||||
"yup": "^1.0.2",
|
||||
"zustand": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/react": "^18.2.15",
|
||||
"@types/react-dom": "^18.2.7",
|
||||
"@typescript-eslint/eslint-plugin": "^5.59.8",
|
||||
"@typescript-eslint/parser": "^5.59.8",
|
||||
"@vitejs/plugin-react": "^4.0.3",
|
||||
"eslint": "^8.41.0",
|
||||
"eslint-plugin-react-hooks": "^4.6.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.3",
|
||||
"typescript": "^5.0.2",
|
||||
"vite": "^4.3.9"
|
||||
}
|
||||
}
|
||||
@@ -1,452 +0,0 @@
|
||||
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
|
||||
@@ -1,264 +0,0 @@
|
||||
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
|
||||
@@ -1,299 +0,0 @@
|
||||
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
|
||||
@@ -1,174 +0,0 @@
|
||||
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
|
||||
@@ -1,288 +0,0 @@
|
||||
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
|
||||
@@ -1,310 +0,0 @@
|
||||
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
|
||||
@@ -1,27 +0,0 @@
|
||||
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
|
||||
@@ -1,297 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,376 +0,0 @@
|
||||
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 }
|
||||
@@ -1,284 +0,0 @@
|
||||
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
|
||||
@@ -1,497 +0,0 @@
|
||||
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
|
||||
@@ -1,279 +0,0 @@
|
||||
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
|
||||
@@ -1,582 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,596 +0,0 @@
|
||||
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"
|
||||
@@ -1,71 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,199 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,352 +0,0 @@
|
||||
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
|
||||
@@ -1,318 +0,0 @@
|
||||
/* 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);
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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>,
|
||||
)
|
||||
@@ -1,692 +0,0 @@
|
||||
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
|
||||
@@ -1,634 +0,0 @@
|
||||
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
@@ -1,147 +0,0 @@
|
||||
import React from 'react';
|
||||
|
||||
interface Milestone {
|
||||
id: string;
|
||||
title: string;
|
||||
description: string;
|
||||
status: 'completed' | 'in_progress' | 'pending';
|
||||
date?: string;
|
||||
icon: string;
|
||||
}
|
||||
|
||||
const milestones: Milestone[] = [
|
||||
{
|
||||
id: 'DIGI01',
|
||||
title: 'Gestión Clases POSG.EMIA',
|
||||
description: 'Descarga, upload a YouTube y difusión de grabaciones.',
|
||||
status: 'completed',
|
||||
date: '2026-03-02',
|
||||
icon: 'fas fa-video'
|
||||
},
|
||||
{
|
||||
id: 'S01',
|
||||
title: 'Estandarización de Recursos (Raíz)',
|
||||
description: 'Unificación de dtic-NOTAs y dtic-DIGIs en la raíz del proyecto.',
|
||||
status: 'completed',
|
||||
date: '2026-03-03',
|
||||
icon: 'fas fa-folder-tree'
|
||||
},
|
||||
{
|
||||
id: 'S02',
|
||||
title: 'Unificación dtic-BKPs v6.0',
|
||||
description: 'Consolidación de herramientas de backup y jubilación de ns8-bkps.',
|
||||
status: 'completed',
|
||||
date: '2026-03-03',
|
||||
icon: 'fas fa-database'
|
||||
},
|
||||
{
|
||||
id: 'P2601',
|
||||
title: 'Proyecto DASUTEN - VM sql-dasuten',
|
||||
description: 'Instalación de motor SQL, restauración de DB y software de gestión.',
|
||||
status: 'in_progress',
|
||||
icon: 'fas fa-server'
|
||||
},
|
||||
{
|
||||
id: 'P2602',
|
||||
title: 'Proyecto Backups DTIC',
|
||||
description: 'Automatización y hardening de copias de seguridad remotas.',
|
||||
status: 'pending',
|
||||
icon: 'fas fa-shield-halved'
|
||||
}
|
||||
];
|
||||
|
||||
const Estadoproyecto = () => {
|
||||
const getStatusBadge = (status: Milestone['status']) => {
|
||||
switch (status) {
|
||||
case 'completed':
|
||||
return <span className="badge bg-success"><i className="fas fa-check-circle me-1"></i>Completado</span>;
|
||||
case 'in_progress':
|
||||
return <span className="badge bg-primary"><i className="fas fa-spinner fa-spin me-1"></i>En Progreso</span>;
|
||||
default:
|
||||
return <span className="badge bg-secondary"><i className="fas fa-clock me-1"></i>Pendiente</span>;
|
||||
}
|
||||
};
|
||||
|
||||
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">Hoja de ruta y seguimiento de hitos del DTIC</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="row">
|
||||
{/* Resumen de Progreso */}
|
||||
<div className="col-lg-4 mb-4">
|
||||
<div className="card h-100">
|
||||
<div className="card-header">
|
||||
<i className="fas fa-tachometer-alt me-2"></i>Resumen General
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="mb-4">
|
||||
<label className="form-label d-flex justify-content-between">
|
||||
<span>Progreso de Etapa Actual</span>
|
||||
<span>65%</span>
|
||||
</label>
|
||||
<div className="progress" style={{ height: '10px' }}>
|
||||
<div className="progress-bar bg-primary" role="progressbar" style={{ width: '65%' }}></div>
|
||||
</div>
|
||||
</div>
|
||||
<ul className="list-group list-group-flush">
|
||||
<li className="list-group-item d-flex justify-content-between align-items-center bg-transparent">
|
||||
Hitos Completados
|
||||
<span className="badge bg-success rounded-pill">3</span>
|
||||
</li>
|
||||
<li className="list-group-item d-flex justify-content-between align-items-center bg-transparent">
|
||||
En Ejecución (P2601)
|
||||
<span className="badge bg-primary rounded-pill">1</span>
|
||||
</li>
|
||||
<li className="list-group-item d-flex justify-content-between align-items-center bg-transparent">
|
||||
Próximos (P2602)
|
||||
<span className="badge bg-secondary rounded-pill">1</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Timeline de Hitos */}
|
||||
<div className="col-lg-8">
|
||||
<div className="card">
|
||||
<div className="card-header">
|
||||
<i className="fas fa-list-check me-2"></i>Línea de Tiempo de Hitos
|
||||
</div>
|
||||
<div className="card-body">
|
||||
<div className="timeline">
|
||||
{milestones.map((m) => (
|
||||
<div key={m.id} className={`mb-4 p-3 border-start border-4 ${m.status === 'completed' ? 'border-success' : m.status === 'in_progress' ? 'border-primary' : 'border-secondary'} bg-light rounded-end`}>
|
||||
<div className="d-flex justify-content-between align-items-start">
|
||||
<div>
|
||||
<h5 className="mb-1">
|
||||
<i className={`${m.icon} me-2 text-muted`}></i>
|
||||
{m.id}: {m.title}
|
||||
</h5>
|
||||
<p className="mb-1 text-secondary">{m.description}</p>
|
||||
{m.date && <small className="text-muted"><i className="fas fa-calendar-alt me-1"></i>{m.date}</small>}
|
||||
</div>
|
||||
{getStatusBadge(m.status)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Estadoproyecto;
|
||||
@@ -1,139 +0,0 @@
|
||||
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
|
||||
@@ -1,658 +0,0 @@
|
||||
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
|
||||
@@ -1,722 +0,0 @@
|
||||
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
|
||||
@@ -1,135 +0,0 @@
|
||||
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,
|
||||
}),
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -1,268 +0,0 @@
|
||||
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'
|
||||
}
|
||||
)
|
||||
)
|
||||
@@ -1,112 +0,0 @@
|
||||
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
|
||||
}
|
||||
@@ -1,275 +0,0 @@
|
||||
// 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)
|
||||
@@ -1,25 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"skipLibCheck": true,
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"allowSyntheticDefaultImports": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
|
||||
const packageJson = JSON.parse(fs.readFileSync(path.resolve(process.cwd(), 'package.json'), 'utf-8'))
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
define: {
|
||||
'import.meta.env.VERSION': JSON.stringify(packageJson.version)
|
||||
},
|
||||
plugins: [react()],
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://api:3001',
|
||||
changeOrigin: true,
|
||||
secure: false,
|
||||
configure: (proxy, options) => {
|
||||
proxy.on('error', (err, req, res) => {
|
||||
console.log('Proxy error:', err);
|
||||
});
|
||||
proxy.on('proxyReq', (proxyReq, req, res) => {
|
||||
console.log('Proxy request:', req.method, req.url);
|
||||
});
|
||||
proxy.on('proxyRes', (proxyRes, req, res) => {
|
||||
console.log('Proxy response:', proxyRes.statusCode, req.url);
|
||||
});
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist',
|
||||
sourcemap: true,
|
||||
},
|
||||
})
|
||||
@@ -1,20 +1,7 @@
|
||||
title: NS8 Dashboard
|
||||
background:
|
||||
image: https://cdnb.artstation.com/p/assets/images/images/006/897/659/large/mikael-gustafsson-wallpaper-mikael-gustafsson.jpg
|
||||
blur: sm
|
||||
saturate: 100
|
||||
brightness: 50
|
||||
opacity: 100
|
||||
---
|
||||
# For configuration options and examples, please see:
|
||||
# https://gethomepage.dev/configs/settings/
|
||||
|
||||
theme: dark
|
||||
color: slate
|
||||
|
||||
useEqualHeights: true
|
||||
|
||||
layout:
|
||||
Infraestructura Virtual:
|
||||
columns: 2
|
||||
Gestión de Servicios:
|
||||
columns: 1
|
||||
Aplicaciones y Herramientas:
|
||||
columns: 2
|
||||
providers:
|
||||
openweathermap: openweathermapapikey
|
||||
weatherapi: weatherapiapikey
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Archivo: apps.conf
|
||||
# Ubicación original centralizada: /home/rmonla/Documentos/GitHub/dtic-srv-NS8/servicios/nginx/conf.d/apps.conf
|
||||
# Este bloque de NGINX maneja el servicio de APPs (TinyFileManager)
|
||||
|
||||
location /apps/ {
|
||||
client_max_body_size 20G;
|
||||
proxy_pass http://127.0.0.1:8082/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -1,17 +1,26 @@
|
||||
server {
|
||||
listen 80;
|
||||
server_name bitacoras.midominio.com; # <--- CAMBIAR POR DOMINIO REAL
|
||||
# Archivo: bitacoras.conf
|
||||
# Ubicación original centralizada: /home/rmonla/Documentos/GitHub/dtic-srv-NS8/servicios/nginx/conf.d/bitacoras.conf
|
||||
# Este bloque de NGINX maneja todos los endpoints de dtic-BITACORAs
|
||||
|
||||
# Frontend
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:5173;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
}
|
||||
|
||||
# Backend API (Opcional: usar /api o subdominio api.bitacoras...)
|
||||
location /api/ {
|
||||
proxy_pass http://127.0.0.1:3001/;
|
||||
proxy_set_header Host $host;
|
||||
}
|
||||
# P2603 - dtic-BITACORAs API
|
||||
location /bitacoras/api/ {
|
||||
proxy_pass http://127.0.0.1:3002/api/;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
# P2603 - dtic-BITACORAs Frontend
|
||||
location /bitacoras/ {
|
||||
proxy_pass http://127.0.0.1:5174/bitacoras/;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# Archivo: homepage.conf
|
||||
# Ubicación original centralizada: /home/rmonla/Documentos/GitHub/dtic-srv-NS8/servicios/nginx/conf.d/homepage.conf
|
||||
# Este bloque de NGINX maneja el sitio principal (Homepage)
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:3001;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# Soporte para WebSockets si es necesario por Homepage
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
EXPOSE 3001
|
||||
CMD ["npm", "run", "dev"]
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "dtic-bitacoras-api",
|
||||
"version": "1.0.0",
|
||||
"description": "API REST para dtic-BITACORAs",
|
||||
"main": "src/server.js",
|
||||
"scripts": {
|
||||
"start": "node src/server.js",
|
||||
"dev": "nodemon src/server.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"cors": "^2.8.5",
|
||||
"express": "^4.18.2",
|
||||
"helmet": "^7.1.0",
|
||||
"pg": "^8.11.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"nodemon": "^3.0.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
module.exports = (pool) => {
|
||||
const router = require('express').Router();
|
||||
|
||||
// GET /api/bitacoras — Listar bitácoras (opcionalmente por fecha)
|
||||
router.get('/', async (req, res) => {
|
||||
const { fecha } = req.query;
|
||||
if (fecha) {
|
||||
const { rows } = await pool.query('SELECT * FROM bitacoras.bitacoras WHERE fecha = $1', [fecha]);
|
||||
if (rows.length === 0) {
|
||||
// Auto-crear bitácora del día
|
||||
const insert = await pool.query(
|
||||
'INSERT INTO bitacoras.bitacoras (fecha) VALUES ($1) RETURNING *', [fecha]
|
||||
);
|
||||
return res.json(insert.rows[0]);
|
||||
}
|
||||
return res.json(rows[0]);
|
||||
}
|
||||
const { rows } = await pool.query('SELECT * FROM bitacoras.bitacoras ORDER BY fecha DESC LIMIT 30');
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// GET /api/bitacoras/:fecha/completa — Bitácora completa con entradas agrupadas por nodo
|
||||
router.get('/:fecha/completa', async (req, res) => {
|
||||
const { fecha } = req.params;
|
||||
|
||||
// Obtener o crear bitácora
|
||||
let bitacora;
|
||||
const bResult = await pool.query('SELECT * FROM bitacoras.bitacoras WHERE fecha = $1', [fecha]);
|
||||
if (bResult.rows.length === 0) {
|
||||
const insert = await pool.query('INSERT INTO bitacoras.bitacoras (fecha) VALUES ($1) RETURNING *', [fecha]);
|
||||
bitacora = insert.rows[0];
|
||||
} else {
|
||||
bitacora = bResult.rows[0];
|
||||
}
|
||||
|
||||
// Obtener entradas con datos del nodo
|
||||
const { rows: entradas } = await pool.query(`
|
||||
SELECT e.*, n.nombre as nodo_nombre, n.ip as nodo_ip
|
||||
FROM bitacoras.entradas e
|
||||
LEFT JOIN bitacoras.nodos n ON e.nodo_id = n.id
|
||||
WHERE e.bitacora_id = $1
|
||||
ORDER BY e.inicio DESC
|
||||
`, [bitacora.id]);
|
||||
|
||||
// Agrupar por nodo
|
||||
const porNodo = {};
|
||||
entradas.forEach(e => {
|
||||
const nodo = e.nodo_nombre || 'sin-nodo';
|
||||
if (!porNodo[nodo]) porNodo[nodo] = { nodo: nodo, ip: e.nodo_ip, entradas: [] };
|
||||
porNodo[nodo].entradas.push(e);
|
||||
});
|
||||
|
||||
res.json({ ...bitacora, nodos: Object.values(porNodo) });
|
||||
});
|
||||
|
||||
// GET /api/bitacoras/:fecha/export — Exportar a Markdown
|
||||
router.get('/:fecha/export', async (req, res) => {
|
||||
const { fecha } = req.params;
|
||||
const bResult = await pool.query('SELECT * FROM bitacoras.bitacoras WHERE fecha = $1', [fecha]);
|
||||
if (bResult.rows.length === 0) return res.status(404).json({ error: 'Bitácora no encontrada' });
|
||||
|
||||
const bitacora = bResult.rows[0];
|
||||
const { rows: entradas } = await pool.query(`
|
||||
SELECT e.*, n.nombre as nodo_nombre
|
||||
FROM bitacoras.entradas e
|
||||
LEFT JOIN bitacoras.nodos n ON e.nodo_id = n.id
|
||||
WHERE e.bitacora_id = $1
|
||||
ORDER BY n.nombre, e.inicio DESC
|
||||
`, [bitacora.id]);
|
||||
|
||||
// Generar Markdown compatible con ADN
|
||||
const [y, m, d] = fecha.split('-');
|
||||
let md = `# Bitácora de Operaciones - ${d}/${m}/${y}\n\n`;
|
||||
md += `## 📂 Actividades Detalladas\n\n`;
|
||||
|
||||
const porNodo = {};
|
||||
entradas.forEach(e => {
|
||||
const nodo = e.nodo_nombre || 'sin-nodo';
|
||||
if (!porNodo[nodo]) porNodo[nodo] = [];
|
||||
porNodo[nodo].push(e);
|
||||
});
|
||||
|
||||
Object.entries(porNodo).forEach(([nodo, entries]) => {
|
||||
md += `### ${nodo}\n\n`;
|
||||
md += `| I | F | Descripción | E |\n`;
|
||||
md += `| :--- | :--- | :--- | :--- |\n`;
|
||||
entries.forEach(e => {
|
||||
const inicio = e.inicio ? e.inicio.substring(0, 5) : '-';
|
||||
const fin = e.fin ? e.fin.substring(0, 5) : '-';
|
||||
const ia = e.es_ia ? '(IA) ' : '';
|
||||
const estado = `[${e.modo}] ${e.estado}`;
|
||||
md += `| ${inicio} | ${fin} | ${ia}${e.descripcion} | ${estado} |\n`;
|
||||
});
|
||||
md += '\n';
|
||||
});
|
||||
|
||||
res.set('Content-Type', 'text/markdown');
|
||||
res.send(md);
|
||||
});
|
||||
|
||||
// PUT /api/bitacoras/:id — Actualizar resumen de bitácora
|
||||
router.put('/:id', async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { resumen } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
'UPDATE bitacoras.bitacoras SET resumen=$1 WHERE id=$2 RETURNING *',
|
||||
[resumen, id]
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).json({ error: 'Bitácora no encontrada' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
// DELETE /api/bitacoras/:id — Eliminar bitácora y sus entradas
|
||||
router.delete('/:id', async (req, res) => {
|
||||
await pool.query('DELETE FROM bitacoras.entradas WHERE bitacora_id = $1', [req.params.id]);
|
||||
const { rowCount } = await pool.query('DELETE FROM bitacoras.bitacoras WHERE id = $1', [req.params.id]);
|
||||
if (rowCount === 0) return res.status(404).json({ error: 'Bitácora no encontrada' });
|
||||
res.json({ message: 'Bitácora eliminada' });
|
||||
});
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
module.exports = (pool) => {
|
||||
const router = require('express').Router();
|
||||
|
||||
// GET /api/entradas — Listar entradas (filtro por bitacora_id o nodo_id)
|
||||
router.get('/', async (req, res) => {
|
||||
const { bitacora_id, nodo_id } = req.query;
|
||||
let query = 'SELECT e.*, n.nombre as nodo_nombre FROM bitacoras.entradas e LEFT JOIN bitacoras.nodos n ON e.nodo_id = n.id WHERE 1=1';
|
||||
const params = [];
|
||||
if (bitacora_id) { params.push(bitacora_id); query += ` AND e.bitacora_id = $${params.length}`; }
|
||||
if (nodo_id) { params.push(nodo_id); query += ` AND e.nodo_id = $${params.length}`; }
|
||||
query += ' ORDER BY e.inicio DESC';
|
||||
const { rows } = await pool.query(query, params);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// POST /api/entradas — Crear entrada
|
||||
router.post('/', async (req, res) => {
|
||||
const { inicio, fin, descripcion, estado, modo, es_ia, bitacora_id, nodo_id } = req.body;
|
||||
const { rows } = await pool.query(`
|
||||
INSERT INTO bitacoras.entradas (inicio, fin, descripcion, estado, modo, es_ia, bitacora_id, nodo_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING *
|
||||
`, [inicio, fin || null, descripcion, estado || '⏳', modo || 'P', es_ia || false, bitacora_id, nodo_id]);
|
||||
res.status(201).json(rows[0]);
|
||||
});
|
||||
|
||||
// PUT /api/entradas/:id — Actualizar entrada
|
||||
router.put('/:id', async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { inicio, fin, descripcion, estado, modo, es_ia } = req.body;
|
||||
const { rows } = await pool.query(`
|
||||
UPDATE bitacoras.entradas SET inicio=$1, fin=$2, descripcion=$3, estado=$4, modo=$5, es_ia=$6
|
||||
WHERE id=$7 RETURNING *
|
||||
`, [inicio, fin, descripcion, estado, modo, es_ia, id]);
|
||||
if (rows.length === 0) return res.status(404).json({ error: 'Entrada no encontrada' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
// DELETE /api/entradas/:id — Eliminar entrada
|
||||
router.delete('/:id', async (req, res) => {
|
||||
const { rowCount } = await pool.query('DELETE FROM bitacoras.entradas WHERE id = $1', [req.params.id]);
|
||||
if (rowCount === 0) return res.status(404).json({ error: 'Entrada no encontrada' });
|
||||
res.json({ message: 'Entrada eliminada' });
|
||||
});
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
module.exports = (pool) => {
|
||||
const router = require('express').Router();
|
||||
|
||||
// GET /api/nodos — Listar todos los nodos
|
||||
router.get('/', async (req, res) => {
|
||||
const { rows } = await pool.query('SELECT * FROM bitacoras.nodos WHERE activo = true ORDER BY nombre');
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// POST /api/nodos — Crear nodo
|
||||
router.post('/', async (req, res) => {
|
||||
const { nombre, ip, tipo, descripcion } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
'INSERT INTO bitacoras.nodos (nombre, ip, tipo, descripcion) VALUES ($1, $2, $3, $4) RETURNING *',
|
||||
[nombre, ip, tipo, descripcion]
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
});
|
||||
|
||||
// PUT /api/nodos/:id — Actualizar nodo
|
||||
router.put('/:id', async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { nombre, ip, tipo, descripcion, activo } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
'UPDATE bitacoras.nodos SET nombre=$1, ip=$2, tipo=$3, descripcion=$4, activo=$5 WHERE id=$6 RETURNING *',
|
||||
[nombre, ip, tipo, descripcion, activo, id]
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).json({ error: 'Nodo no encontrado' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
// DELETE /api/nodos/:id — Eliminar nodo (lógico o físico si no tiene entradas asociadas)
|
||||
router.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
const { rowCount } = await pool.query('DELETE FROM bitacoras.nodos WHERE id = $1', [req.params.id]);
|
||||
if (rowCount === 0) return res.status(404).json({ error: 'Nodo no encontrado' });
|
||||
res.json({ message: 'Nodo eliminado' });
|
||||
} catch (err) {
|
||||
// Si hay foreign key violation, podemos marcarlo como inactivo
|
||||
if (err.code === '23503') {
|
||||
await pool.query('UPDATE bitacoras.nodos SET activo=false WHERE id = $1', [req.params.id]);
|
||||
return res.json({ message: 'Nodo marcado como inactivo por tener entradas asociadas' });
|
||||
}
|
||||
res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,118 @@
|
||||
module.exports = (pool) => {
|
||||
const router = require('express').Router();
|
||||
|
||||
// GET /api/proyectos — Listar proyectos
|
||||
router.get('/', async (req, res) => {
|
||||
const { rows } = await pool.query('SELECT * FROM bitacoras.proyectos ORDER BY codigo');
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
// GET /api/proyectos/:codigo — Detalle con fases, hitos y métricas
|
||||
router.get('/:codigo', async (req, res) => {
|
||||
const { codigo } = req.params;
|
||||
|
||||
const pResult = await pool.query('SELECT * FROM bitacoras.proyectos WHERE codigo = $1', [codigo]);
|
||||
if (pResult.rows.length === 0) return res.status(404).json({ error: 'Proyecto no encontrado' });
|
||||
const proyecto = pResult.rows[0];
|
||||
|
||||
// Fases con hitos y nodo
|
||||
const { rows: fases } = await pool.query(`
|
||||
SELECT f.*, json_agg(
|
||||
json_build_object(
|
||||
'id', h.id,
|
||||
'id_hito', h.id_hito,
|
||||
'titulo', h.titulo,
|
||||
'descripcion', h.descripcion,
|
||||
'estado', h.estado,
|
||||
'fecha', h.fecha,
|
||||
'horas_presencial', h.horas_presencial,
|
||||
'horas_remoto', h.horas_remoto,
|
||||
'nodo_nombre', n.nombre,
|
||||
'nodo_ip', n.ip
|
||||
) ORDER BY h.fecha NULLS LAST, h.id
|
||||
) FILTER (WHERE h.id IS NOT NULL) AS hitos
|
||||
FROM bitacoras.fases f
|
||||
LEFT JOIN bitacoras.hitos h ON h.fase_id = f.id
|
||||
LEFT JOIN bitacoras.nodos n ON h.nodo_id = n.id
|
||||
WHERE f.proyecto_id = $1
|
||||
GROUP BY f.id
|
||||
ORDER BY f.numero
|
||||
`, [proyecto.id]);
|
||||
|
||||
// Métricas globales
|
||||
const { rows: [metricas] } = await pool.query(`
|
||||
SELECT
|
||||
COUNT(*) FILTER (WHERE h.estado = '✅') AS hitos_completados,
|
||||
COUNT(*) FILTER (WHERE h.estado != '✅') AS hitos_pendientes,
|
||||
COUNT(*) AS hitos_total,
|
||||
COALESCE(SUM(h.horas_presencial), 0) AS total_presencial,
|
||||
COALESCE(SUM(h.horas_remoto), 0) AS total_remoto,
|
||||
COALESCE(SUM(h.horas_presencial + h.horas_remoto), 0) AS total_horas
|
||||
FROM bitacoras.hitos h
|
||||
JOIN bitacoras.fases f ON h.fase_id = f.id
|
||||
WHERE f.proyecto_id = $1
|
||||
`, [proyecto.id]);
|
||||
|
||||
// Nodos únicos involucrados
|
||||
const { rows: nodos } = await pool.query(`
|
||||
SELECT DISTINCT n.id, n.nombre, n.ip, n.tipo, n.descripcion
|
||||
FROM bitacoras.hitos h
|
||||
JOIN bitacoras.fases f ON h.fase_id = f.id
|
||||
JOIN bitacoras.nodos n ON h.nodo_id = n.id
|
||||
WHERE f.proyecto_id = $1
|
||||
ORDER BY n.nombre
|
||||
`, [proyecto.id]);
|
||||
|
||||
res.json({ ...proyecto, fases, metricas, nodos });
|
||||
});
|
||||
|
||||
// POST /api/proyectos/:codigo/hitos — Crear hito
|
||||
router.post('/:codigo/hitos', async (req, res) => {
|
||||
const { codigo } = req.params;
|
||||
const { fase_numero, id_hito, titulo, descripcion, estado, fecha, horas_presencial, horas_remoto, nodo_nombre } = req.body;
|
||||
|
||||
const pResult = await pool.query('SELECT id FROM bitacoras.proyectos WHERE codigo = $1', [codigo]);
|
||||
if (pResult.rows.length === 0) return res.status(404).json({ error: 'Proyecto no encontrado' });
|
||||
|
||||
const fResult = await pool.query(
|
||||
'SELECT id FROM bitacoras.fases WHERE proyecto_id = $1 AND numero = $2',
|
||||
[pResult.rows[0].id, fase_numero]
|
||||
);
|
||||
if (fResult.rows.length === 0) return res.status(404).json({ error: 'Fase no encontrada' });
|
||||
|
||||
let nodo_id = null;
|
||||
if (nodo_nombre) {
|
||||
const nResult = await pool.query('SELECT id FROM bitacoras.nodos WHERE nombre = $1', [nodo_nombre]);
|
||||
if (nResult.rows.length > 0) nodo_id = nResult.rows[0].id;
|
||||
}
|
||||
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO bitacoras.hitos (fase_id, id_hito, titulo, descripcion, estado, fecha, horas_presencial, horas_remoto, nodo_id)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING *`,
|
||||
[fResult.rows[0].id, id_hito, titulo, descripcion || '', estado || '⏳', fecha || null,
|
||||
horas_presencial || 0, horas_remoto || 0, nodo_id]
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
});
|
||||
|
||||
// PUT /api/proyectos/hitos/:id — Actualizar hito
|
||||
router.put('/hitos/:id', async (req, res) => {
|
||||
const { id } = req.params;
|
||||
const { titulo, descripcion, estado, fecha, horas_presencial, horas_remoto } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE bitacoras.hitos SET
|
||||
titulo = COALESCE($1, titulo),
|
||||
descripcion = COALESCE($2, descripcion),
|
||||
estado = COALESCE($3, estado),
|
||||
fecha = COALESCE($4, fecha),
|
||||
horas_presencial = COALESCE($5, horas_presencial),
|
||||
horas_remoto = COALESCE($6, horas_remoto)
|
||||
WHERE id = $7 RETURNING *`,
|
||||
[titulo, descripcion, estado, fecha, horas_presencial, horas_remoto, id]
|
||||
);
|
||||
if (rows.length === 0) return res.status(404).json({ error: 'Hito no encontrado' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
return router;
|
||||
};
|
||||
@@ -0,0 +1,41 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const helmet = require('helmet');
|
||||
const { Pool } = require('pg');
|
||||
|
||||
const app = express();
|
||||
const PORT = process.env.PORT || 3001;
|
||||
|
||||
// Middleware
|
||||
app.use(helmet());
|
||||
app.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
|
||||
app.use(express.json());
|
||||
|
||||
// Database pool
|
||||
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
||||
|
||||
// Health check
|
||||
app.get('/health', async (req, res) => {
|
||||
try {
|
||||
await pool.query('SELECT 1');
|
||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
||||
} catch (err) {
|
||||
res.status(500).json({ status: 'error', message: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// Routes
|
||||
app.use('/api/nodos', require('./routes/nodos')(pool));
|
||||
app.use('/api/bitacoras', require('./routes/bitacoras')(pool));
|
||||
app.use('/api/entradas', require('./routes/entradas')(pool));
|
||||
app.use('/api/proyectos', require('./routes/proyectos')(pool));
|
||||
|
||||
// Error handler
|
||||
app.use((err, req, res, next) => {
|
||||
console.error('Error:', err.message);
|
||||
res.status(500).json({ error: err.message });
|
||||
});
|
||||
|
||||
app.listen(PORT, () => {
|
||||
console.log(`🔐 dtic-BITACORAs API corriendo en puerto ${PORT}`);
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:15-alpine
|
||||
environment:
|
||||
POSTGRES_USER: dtic_user
|
||||
POSTGRES_PASSWORD: dtic_pass_2026
|
||||
POSTGRES_DB: dtic_bitacoras
|
||||
ports:
|
||||
- "5433:5432"
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
- ./docker/init.sql:/docker-entrypoint-initdb.d/init.sql
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U dtic_user -d dtic_bitacoras"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
api:
|
||||
build: ./backend
|
||||
ports:
|
||||
- "3002:3001"
|
||||
environment:
|
||||
NODE_ENV: development
|
||||
PORT: 3001
|
||||
DATABASE_URL: postgres://dtic_user:dtic_pass_2026@postgres:5432/dtic_bitacoras
|
||||
JWT_SECRET: dtic_bitacoras_secret_2026
|
||||
CORS_ORIGIN: "*"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ./backend/src:/app/src
|
||||
|
||||
frontend:
|
||||
build: ./frontend
|
||||
ports:
|
||||
- "5174:5173"
|
||||
environment:
|
||||
VITE_API_URL: /bitacoras/api
|
||||
depends_on:
|
||||
- api
|
||||
volumes:
|
||||
- ./frontend/src:/app/src
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,91 @@
|
||||
-- dtic-BITACORAs - Esquema de Base de Datos
|
||||
-- Formato I-F-D-E (Inicio, Fin, Descripción, Estado)
|
||||
|
||||
CREATE SCHEMA IF NOT EXISTS bitacoras;
|
||||
|
||||
-- Nodos del sistema (servidores, VMs, PCs)
|
||||
CREATE TABLE bitacoras.nodos (
|
||||
id SERIAL PRIMARY KEY,
|
||||
nombre VARCHAR(50) NOT NULL UNIQUE,
|
||||
ip VARCHAR(45),
|
||||
tipo VARCHAR(20) DEFAULT 'servidor',
|
||||
descripcion TEXT,
|
||||
activo BOOLEAN DEFAULT true,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Bitácoras diarias
|
||||
CREATE TABLE bitacoras.bitacoras (
|
||||
id SERIAL PRIMARY KEY,
|
||||
fecha DATE NOT NULL UNIQUE,
|
||||
resumen TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Temas (agrupadores de entradas por nodo)
|
||||
CREATE TABLE bitacoras.temas (
|
||||
id SERIAL PRIMARY KEY,
|
||||
id_tema VARCHAR(20) NOT NULL,
|
||||
titulo VARCHAR(200) NOT NULL,
|
||||
estado VARCHAR(10) DEFAULT '⏳',
|
||||
descripcion TEXT,
|
||||
bitacora_id INTEGER REFERENCES bitacoras.bitacoras(id) ON DELETE CASCADE,
|
||||
nodo_id INTEGER REFERENCES bitacoras.nodos(id),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Entradas cronológicas (formato I-F-D-E)
|
||||
CREATE TABLE bitacoras.entradas (
|
||||
id SERIAL PRIMARY KEY,
|
||||
inicio TIME NOT NULL,
|
||||
fin TIME,
|
||||
descripcion TEXT NOT NULL,
|
||||
estado VARCHAR(10) DEFAULT '⏳',
|
||||
modo CHAR(1) DEFAULT 'P' CHECK (modo IN ('P', 'R')),
|
||||
es_ia BOOLEAN DEFAULT false,
|
||||
tema_id INTEGER REFERENCES bitacoras.temas(id) ON DELETE CASCADE,
|
||||
bitacora_id INTEGER REFERENCES bitacoras.bitacoras(id) ON DELETE CASCADE,
|
||||
nodo_id INTEGER REFERENCES bitacoras.nodos(id),
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
-- Índices
|
||||
CREATE INDEX idx_bitacoras_fecha ON bitacoras.bitacoras(fecha);
|
||||
CREATE INDEX idx_entradas_bitacora ON bitacoras.entradas(bitacora_id);
|
||||
CREATE INDEX idx_entradas_nodo ON bitacoras.entradas(nodo_id);
|
||||
CREATE INDEX idx_temas_bitacora ON bitacoras.temas(bitacora_id);
|
||||
|
||||
-- Trigger para updated_at
|
||||
CREATE OR REPLACE FUNCTION bitacoras.update_timestamp()
|
||||
RETURNS TRIGGER AS $$
|
||||
BEGIN
|
||||
NEW.updated_at = CURRENT_TIMESTAMP;
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
CREATE TRIGGER trg_nodos_updated BEFORE UPDATE ON bitacoras.nodos
|
||||
FOR EACH ROW EXECUTE FUNCTION bitacoras.update_timestamp();
|
||||
CREATE TRIGGER trg_bitacoras_updated BEFORE UPDATE ON bitacoras.bitacoras
|
||||
FOR EACH ROW EXECUTE FUNCTION bitacoras.update_timestamp();
|
||||
CREATE TRIGGER trg_temas_updated BEFORE UPDATE ON bitacoras.temas
|
||||
FOR EACH ROW EXECUTE FUNCTION bitacoras.update_timestamp();
|
||||
CREATE TRIGGER trg_entradas_updated BEFORE UPDATE ON bitacoras.entradas
|
||||
FOR EACH ROW EXECUTE FUNCTION bitacoras.update_timestamp();
|
||||
|
||||
-- Datos semilla: Nodos del proyecto
|
||||
INSERT INTO bitacoras.nodos (nombre, ip, tipo, descripcion) VALUES
|
||||
('srv-ns8', '10.0.10.8', 'servidor', 'Nodo central de gestión, GIT y Dashboard'),
|
||||
('srv-dasu', '10.0.10.205', 'hipervisor', 'Hipervisor Proxmox VE (DASUTEN)'),
|
||||
('dc-dasuten', '10.0.100.10', 'vm', 'Controlador de Dominio AD DS + DNS'),
|
||||
('sql-dasuten', '10.0.100.11', 'vm', 'Motor SQL Server 2019 Core'),
|
||||
('pcv-dasu0', '10.0.100.12', 'vm', 'VM de pruebas Win 10 LTSC'),
|
||||
('pc-dasu0', NULL, 'pc', 'PC física cliente oficina DASUTeN'),
|
||||
('srv-pmox1', '10.0.10.201', 'hipervisor', 'Pool master Proxmox'),
|
||||
('srv-pmox2', '10.0.10.202', 'hipervisor', 'Nodo Proxmox secundario'),
|
||||
('srv-pmox3', '10.0.10.203', 'hipervisor', 'Nodo Proxmox terciario (64GB RAM)'),
|
||||
('srv-xen1', '10.0.10.23', 'hipervisor', 'Citrix XenServer 7.0 (Legacy)');
|
||||
@@ -0,0 +1,7 @@
|
||||
FROM node:18-alpine
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm install
|
||||
COPY . .
|
||||
EXPOSE 5173
|
||||
CMD ["npm", "run", "dev"]
|
||||
@@ -0,0 +1,16 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="es">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="description" content="dtic-BITACORAs - Sistema de Bitácoras de Operaciones DTIC UTNLR" />
|
||||
<title>dtic-BITACORAs | DTIC UTNLR</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
|
||||
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "dtic-bitacoras-frontend",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host",
|
||||
"build": "tsc && vite build",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "^18.2.43",
|
||||
"@types/react-dom": "^18.2.17",
|
||||
"@vitejs/plugin-react": "^4.2.1",
|
||||
"typescript": "^5.2.2",
|
||||
"vite": "^5.1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,528 @@
|
||||
/// <reference types="vite/client" />
|
||||
import React, { useState, useEffect, useCallback } from 'react';
|
||||
import ProyectoDashboard from './pages/ProyectoDashboard';
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/bitacoras/api';
|
||||
|
||||
interface Entrada {
|
||||
id: number;
|
||||
inicio: string;
|
||||
fin: string | null;
|
||||
descripcion: string;
|
||||
estado: string;
|
||||
modo: string;
|
||||
es_ia: boolean;
|
||||
nodo_nombre: string;
|
||||
nodo_ip: string;
|
||||
}
|
||||
|
||||
interface NodoGroup {
|
||||
nodo: string;
|
||||
ip: string;
|
||||
entradas: Entrada[];
|
||||
}
|
||||
|
||||
interface Bitacora {
|
||||
id: number;
|
||||
fecha: string;
|
||||
resumen: string;
|
||||
nodos: NodoGroup[];
|
||||
}
|
||||
|
||||
interface Nodo {
|
||||
id: number;
|
||||
nombre: string;
|
||||
ip: string;
|
||||
tipo: string;
|
||||
descripcion: string;
|
||||
activo: boolean;
|
||||
}
|
||||
|
||||
// ===== MODAL DE CONFIRMACIÓN =====
|
||||
function ConfirmModal({ show, title, message, onConfirm, onCancel }: {
|
||||
show: boolean; title: string; message: string;
|
||||
onConfirm: () => void; onCancel: () => void;
|
||||
}) {
|
||||
if (!show) return null;
|
||||
return (
|
||||
<div className="modal-overlay" onClick={onCancel}>
|
||||
<div className="modal-box" onClick={e => e.stopPropagation()}>
|
||||
<div className="modal-header"><i className="fas fa-exclamation-triangle"></i> {title}</div>
|
||||
<p className="modal-body">{message}</p>
|
||||
<div className="modal-actions">
|
||||
<button className="btn btn-sm" onClick={onCancel} style={{ background: 'var(--bg-card)', border: '1px solid var(--border)', color: 'var(--text)' }}>Cancelar</button>
|
||||
<button className="btn btn-sm btn-danger" onClick={onConfirm}><i className="fas fa-trash-alt"></i> Eliminar</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ===== TABS =====
|
||||
type Tab = 'bitacora' | 'nodos' | 'proyecto';
|
||||
|
||||
function getInitialTab(): Tab {
|
||||
const path = window.location.pathname.toLowerCase();
|
||||
if (path.includes('/p2601')) return 'proyecto';
|
||||
if (path.includes('/nodos')) return 'nodos';
|
||||
return 'bitacora';
|
||||
}
|
||||
|
||||
function App() {
|
||||
const [tab, setTab] = useState<Tab>(getInitialTab());
|
||||
|
||||
const changeTab = (t: Tab) => {
|
||||
setTab(t);
|
||||
const base = '/bitacoras/';
|
||||
// Asegurar que las rutas incluyan el prefijo correcto para el ruteo de NGINX
|
||||
const paths: Record<Tab, string> = {
|
||||
bitacora: base,
|
||||
nodos: base + 'nodos',
|
||||
proyecto: base + 'p2601'
|
||||
};
|
||||
window.history.replaceState(null, '', paths[t]);
|
||||
};
|
||||
const [fecha, setFecha] = useState(new Date().toISOString().split('T')[0]);
|
||||
const [bitacora, setBitacora] = useState<Bitacora | null>(null);
|
||||
const [nodos, setNodos] = useState<Nodo[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Form: nueva entrada
|
||||
const [newInicio, setNewInicio] = useState('');
|
||||
const [newFin, setNewFin] = useState('');
|
||||
const [newDesc, setNewDesc] = useState('');
|
||||
const [newEstado, setNewEstado] = useState('⏳');
|
||||
const [newModo, setNewModo] = useState('P');
|
||||
const [newNodoId, setNewNodoId] = useState('');
|
||||
const [newEsIa, setNewEsIa] = useState(false);
|
||||
|
||||
// Edit: entrada en edición
|
||||
const [editId, setEditId] = useState<number | null>(null);
|
||||
const [editInicio, setEditInicio] = useState('');
|
||||
const [editFin, setEditFin] = useState('');
|
||||
const [editDesc, setEditDesc] = useState('');
|
||||
const [editEstado, setEditEstado] = useState('');
|
||||
const [editModo, setEditModo] = useState('');
|
||||
const [editEsIa, setEditEsIa] = useState(false);
|
||||
|
||||
// Confirm delete
|
||||
const [confirmDelete, setConfirmDelete] = useState<{ type: string; id: number; name: string } | null>(null);
|
||||
|
||||
// Nodo form
|
||||
const [nodoFormVisible, setNodoFormVisible] = useState(false);
|
||||
const [editNodoId, setEditNodoId] = useState<number | null>(null);
|
||||
const [nodoNombre, setNodoNombre] = useState('');
|
||||
const [nodoIp, setNodoIp] = useState('');
|
||||
const [nodoTipo, setNodoTipo] = useState('servidor');
|
||||
const [nodoDesc, setNodoDesc] = useState('');
|
||||
|
||||
// === FETCH ===
|
||||
const fetchBitacora = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/bitacoras/${fecha}/completa`);
|
||||
const data = await res.json();
|
||||
setBitacora(data);
|
||||
} catch (err) { console.error('Error:', err); }
|
||||
setLoading(false);
|
||||
}, [fecha]);
|
||||
|
||||
const fetchNodos = async () => {
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/nodos`);
|
||||
setNodos(await res.json());
|
||||
} catch (err) { console.error('Error:', err); }
|
||||
};
|
||||
|
||||
useEffect(() => { fetchBitacora(); }, [fetchBitacora]);
|
||||
useEffect(() => { fetchNodos(); }, []);
|
||||
|
||||
// === ENTRADAS CRUD ===
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!bitacora || !newDesc || !newInicio || !newNodoId) return;
|
||||
try {
|
||||
await fetch(`${API_URL}/entradas`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
inicio: newInicio, fin: newFin || null, descripcion: newDesc,
|
||||
estado: newEstado, modo: newModo, es_ia: newEsIa,
|
||||
bitacora_id: bitacora.id, nodo_id: parseInt(newNodoId)
|
||||
})
|
||||
});
|
||||
setNewDesc(''); setNewInicio(''); setNewFin('');
|
||||
fetchBitacora();
|
||||
} catch (err) { console.error('Error:', err); }
|
||||
};
|
||||
|
||||
const startEdit = (e: Entrada) => {
|
||||
setEditId(e.id);
|
||||
setEditInicio(e.inicio?.substring(0, 5) || '');
|
||||
setEditFin(e.fin ? e.fin.substring(0, 5) : '');
|
||||
setEditDesc(e.descripcion);
|
||||
setEditEstado(e.estado);
|
||||
setEditModo(e.modo);
|
||||
setEditEsIa(e.es_ia);
|
||||
};
|
||||
|
||||
const cancelEdit = () => setEditId(null);
|
||||
|
||||
const saveEdit = async () => {
|
||||
if (!editId) return;
|
||||
await fetch(`${API_URL}/entradas/${editId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
inicio: editInicio, fin: editFin || null, descripcion: editDesc,
|
||||
estado: editEstado, modo: editModo, es_ia: editEsIa,
|
||||
})
|
||||
});
|
||||
setEditId(null);
|
||||
fetchBitacora();
|
||||
};
|
||||
|
||||
const requestDeleteEntrada = (id: number, desc: string) => {
|
||||
setConfirmDelete({ type: 'entrada', id, name: desc.substring(0, 50) + '...' });
|
||||
};
|
||||
|
||||
const executeDelete = async () => {
|
||||
if (!confirmDelete) return;
|
||||
const { type, id } = confirmDelete;
|
||||
if (type === 'entrada') {
|
||||
await fetch(`${API_URL}/entradas/${id}`, { method: 'DELETE' });
|
||||
fetchBitacora();
|
||||
} else if (type === 'nodo') {
|
||||
await fetch(`${API_URL}/nodos/${id}`, { method: 'DELETE' });
|
||||
fetchNodos();
|
||||
}
|
||||
setConfirmDelete(null);
|
||||
};
|
||||
|
||||
// === NODOS CRUD ===
|
||||
const resetNodoForm = () => {
|
||||
setEditNodoId(null); setNodoNombre(''); setNodoIp(''); setNodoTipo('servidor'); setNodoDesc('');
|
||||
setNodoFormVisible(false);
|
||||
};
|
||||
|
||||
const openNodoForm = (nodo?: Nodo) => {
|
||||
if (nodo) {
|
||||
setEditNodoId(nodo.id); setNodoNombre(nodo.nombre); setNodoIp(nodo.ip || '');
|
||||
setNodoTipo(nodo.tipo || 'servidor'); setNodoDesc(nodo.descripcion || '');
|
||||
} else {
|
||||
setEditNodoId(null); setNodoNombre(''); setNodoIp(''); setNodoTipo('servidor'); setNodoDesc('');
|
||||
}
|
||||
setNodoFormVisible(true);
|
||||
};
|
||||
|
||||
const saveNodo = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!nodoNombre) return;
|
||||
if (editNodoId) {
|
||||
const existing = nodos.find(n => n.id === editNodoId);
|
||||
await fetch(`${API_URL}/nodos/${editNodoId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ nombre: nodoNombre, ip: nodoIp, tipo: nodoTipo, descripcion: nodoDesc, activo: existing?.activo ?? true })
|
||||
});
|
||||
} else {
|
||||
await fetch(`${API_URL}/nodos`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ nombre: nodoNombre, ip: nodoIp, tipo: nodoTipo, descripcion: nodoDesc })
|
||||
});
|
||||
}
|
||||
resetNodoForm();
|
||||
fetchNodos();
|
||||
};
|
||||
|
||||
const requestDeleteNodo = (id: number, nombre: string) => {
|
||||
setConfirmDelete({ type: 'nodo', id, name: nombre });
|
||||
};
|
||||
|
||||
// === STATS ===
|
||||
const totalEntradas = bitacora?.nodos?.reduce((sum, n) => sum + n.entradas.length, 0) || 0;
|
||||
const totalNodos = bitacora?.nodos?.length || 0;
|
||||
|
||||
return (
|
||||
<div className="app">
|
||||
{/* Modal de confirmación */}
|
||||
<ConfirmModal
|
||||
show={!!confirmDelete}
|
||||
title="Confirmar eliminación"
|
||||
message={`¿Estás seguro que querés eliminar "${confirmDelete?.name}"? Esta acción no se puede deshacer.`}
|
||||
onConfirm={executeDelete}
|
||||
onCancel={() => setConfirmDelete(null)}
|
||||
/>
|
||||
|
||||
<nav className="navbar">
|
||||
<div className="navbar-brand">
|
||||
<i className="fas fa-book-open"></i>
|
||||
dtic-BITACORAs
|
||||
<span className="badge badge-gradient">v1.1</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', gap: '0.5rem' }}>
|
||||
<button
|
||||
className={`btn btn-sm ${tab === 'bitacora' ? 'btn-primary' : ''}`}
|
||||
onClick={() => changeTab('bitacora')}
|
||||
style={tab !== 'bitacora' ? { background: 'var(--bg-card)', color: 'var(--text)', border: '1px solid var(--border)' } : {}}
|
||||
><i className="fas fa-book"></i> Bitácora</button>
|
||||
<button
|
||||
className={`btn btn-sm ${tab === 'nodos' ? 'btn-primary' : ''}`}
|
||||
onClick={() => changeTab('nodos')}
|
||||
style={tab !== 'nodos' ? { background: 'var(--bg-card)', color: 'var(--text)', border: '1px solid var(--border)' } : {}}
|
||||
><i className="fas fa-server"></i> Nodos</button>
|
||||
<button
|
||||
className={`btn btn-sm ${tab === 'proyecto' ? 'btn-primary' : ''}`}
|
||||
onClick={() => changeTab('proyecto')}
|
||||
style={tab !== 'proyecto' ? { background: 'var(--bg-card)', color: 'var(--text)', border: '1px solid var(--border)' } : {}}
|
||||
><i className="fas fa-project-diagram"></i> P2601</button>
|
||||
{tab === 'bitacora' && (
|
||||
<a href={`${API_URL}/bitacoras/${fecha}/export`} target="_blank" rel="noopener"
|
||||
className="btn btn-sm btn-primary">
|
||||
<i className="fas fa-file-export"></i> Exportar MD
|
||||
</a>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
|
||||
<main className="main">
|
||||
{/* =================== TAB BITÁCORA =================== */}
|
||||
{tab === 'bitacora' && (
|
||||
<>
|
||||
{/* Date Selector */}
|
||||
<div className="date-selector">
|
||||
<button className="btn btn-sm btn-primary" onClick={() => {
|
||||
const d = new Date(fecha); d.setDate(d.getDate() - 1); setFecha(d.toISOString().split('T')[0]);
|
||||
}}><i className="fas fa-chevron-left"></i></button>
|
||||
<input type="date" value={fecha} onChange={e => setFecha(e.target.value)} />
|
||||
<button className="btn btn-sm btn-primary" onClick={() => {
|
||||
const d = new Date(fecha); d.setDate(d.getDate() + 1); setFecha(d.toISOString().split('T')[0]);
|
||||
}}><i className="fas fa-chevron-right"></i></button>
|
||||
<button className="btn btn-sm" onClick={() => setFecha(new Date().toISOString().split('T')[0])}
|
||||
style={{ background: 'var(--bg-card)', color: 'var(--text-secondary)', border: '1px solid var(--border)' }}>
|
||||
<i className="fas fa-calendar-day"></i> Hoy
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Stats */}
|
||||
<div className="stats-bar">
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{totalEntradas}</div>
|
||||
<div className="stat-label">Entradas</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{totalNodos}</div>
|
||||
<div className="stat-label">Nodos Activos</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{bitacora?.nodos?.reduce((s, n) => s + n.entradas.filter(e => e.estado === '✅').length, 0) || 0}</div>
|
||||
<div className="stat-label">Completadas</div>
|
||||
</div>
|
||||
<div className="stat-card">
|
||||
<div className="stat-value">{bitacora?.nodos?.reduce((s, n) => s + n.entradas.filter(e => e.estado === '⏳').length, 0) || 0}</div>
|
||||
<div className="stat-label">En Proceso</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* New Entry Form */}
|
||||
<div className="card" style={{ marginBottom: '2rem' }}>
|
||||
<div className="card-header"><i className="fas fa-plus-circle"></i> Nueva Entrada</div>
|
||||
<form className="form-inline" onSubmit={handleSubmit}>
|
||||
<input type="time" className="input-time" value={newInicio} onChange={e => setNewInicio(e.target.value)} placeholder="I" required />
|
||||
<input type="time" className="input-time" value={newFin} onChange={e => setNewFin(e.target.value)} placeholder="F" />
|
||||
<input type="text" className="input-desc" value={newDesc} onChange={e => setNewDesc(e.target.value)} placeholder="Descripción..." required />
|
||||
<select value={newNodoId} onChange={e => setNewNodoId(e.target.value)} required>
|
||||
<option value="">Nodo...</option>
|
||||
{nodos.map(n => <option key={n.id} value={n.id}>{n.nombre}</option>)}
|
||||
</select>
|
||||
<select value={newEstado} onChange={e => setNewEstado(e.target.value)}>
|
||||
<option value="⏳">⏳</option><option value="✅">✅</option>
|
||||
<option value="⚠️">⚠️</option><option value="❌">❌</option><option value="👁️">👁️</option>
|
||||
</select>
|
||||
<select value={newModo} onChange={e => setNewModo(e.target.value)}>
|
||||
<option value="P">[P] Presencial</option><option value="R">[R] Remoto</option>
|
||||
</select>
|
||||
<label style={{ display: 'flex', alignItems: 'center', gap: '0.3rem', color: 'var(--text-secondary)', fontSize: '0.85rem' }}>
|
||||
<input type="checkbox" checked={newEsIa} onChange={e => setNewEsIa(e.target.checked)} /> IA
|
||||
</label>
|
||||
<button type="submit" className="btn btn-primary"><i className="fas fa-save"></i> Guardar</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
{/* Loading */}
|
||||
{loading && <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--text-muted)' }}><i className="fas fa-spinner fa-spin fa-2x"></i></div>}
|
||||
|
||||
{/* Entries by Node */}
|
||||
{bitacora?.nodos?.map((nodoGroup, idx) => (
|
||||
<div key={idx} className="nodo-section card" style={{ marginBottom: '1.5rem' }}>
|
||||
<div className="nodo-title">
|
||||
<i className="fas fa-server"></i>
|
||||
{nodoGroup.nodo}
|
||||
{nodoGroup.ip && <span className="nodo-ip">({nodoGroup.ip})</span>}
|
||||
<span className="badge badge-gradient" style={{ marginLeft: 'auto' }}>{nodoGroup.entradas.length}</span>
|
||||
</div>
|
||||
<table className="table-ifde">
|
||||
<thead>
|
||||
<tr>
|
||||
<th className="col-time">I</th>
|
||||
<th className="col-time">F</th>
|
||||
<th>Descripción</th>
|
||||
<th className="col-status">E</th>
|
||||
<th style={{ width: '80px' }}>Acc.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{nodoGroup.entradas.map(e => (
|
||||
editId === e.id ? (
|
||||
/* ==== FILA EN EDICIÓN ==== */
|
||||
<tr key={e.id} style={{ background: 'rgba(102, 126, 234, 0.1)' }}>
|
||||
<td><input type="time" value={editInicio} onChange={ev => setEditInicio(ev.target.value)} className="edit-input" /></td>
|
||||
<td><input type="time" value={editFin} onChange={ev => setEditFin(ev.target.value)} className="edit-input" /></td>
|
||||
<td>
|
||||
<input type="text" value={editDesc} onChange={ev => setEditDesc(ev.target.value)} className="edit-input" style={{ width: '100%' }} />
|
||||
<div style={{ display: 'flex', gap: '0.3rem', marginTop: '0.3rem', alignItems: 'center' }}>
|
||||
<select value={editEstado} onChange={ev => setEditEstado(ev.target.value)} className="edit-input">
|
||||
<option value="⏳">⏳</option><option value="✅">✅</option>
|
||||
<option value="⚠️">⚠️</option><option value="❌">❌</option><option value="👁️">👁️</option>
|
||||
</select>
|
||||
<select value={editModo} onChange={ev => setEditModo(ev.target.value)} className="edit-input">
|
||||
<option value="P">[P]</option><option value="R">[R]</option>
|
||||
</select>
|
||||
<label style={{ fontSize: '0.75rem', color: 'var(--text-secondary)', display: 'flex', alignItems: 'center', gap: '0.2rem' }}>
|
||||
<input type="checkbox" checked={editEsIa} onChange={ev => setEditEsIa(ev.target.checked)} /> IA
|
||||
</label>
|
||||
</div>
|
||||
</td>
|
||||
<td></td>
|
||||
<td>
|
||||
<div style={{ display: 'flex', gap: '0.2rem' }}>
|
||||
<button className="btn btn-sm btn-success" onClick={saveEdit} title="Guardar"><i className="fas fa-check"></i></button>
|
||||
<button className="btn btn-sm" onClick={cancelEdit} title="Cancelar" style={{ background: 'var(--bg-card)', color: 'var(--text-muted)' }}><i className="fas fa-times"></i></button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
/* ==== FILA NORMAL ==== */
|
||||
<tr key={e.id}>
|
||||
<td className="col-time">{e.inicio?.substring(0, 5)}</td>
|
||||
<td className="col-time">{e.fin ? e.fin.substring(0, 5) : '—'}</td>
|
||||
<td className="col-desc">
|
||||
{e.es_ia && <span className="ia-tag">IA</span>}
|
||||
{e.descripcion}
|
||||
</td>
|
||||
<td className="col-status">[{e.modo}] {e.estado}</td>
|
||||
<td>
|
||||
<div style={{ display: 'flex', gap: '0.2rem' }}>
|
||||
<button className="btn btn-sm" onClick={() => startEdit(e)} title="Editar"
|
||||
style={{ background: 'var(--info)', color: 'white' }}>
|
||||
<i className="fas fa-pen"></i>
|
||||
</button>
|
||||
<button className="btn btn-sm btn-danger" onClick={() => requestDeleteEntrada(e.id, e.descripcion)} title="Eliminar">
|
||||
<i className="fas fa-trash-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
)
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{!loading && totalEntradas === 0 && (
|
||||
<div style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>
|
||||
<i className="fas fa-inbox fa-3x" style={{ marginBottom: '1rem', display: 'block' }}></i>
|
||||
Sin entradas para esta fecha. ¡Creá la primera!
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* =================== TAB NODOS =================== */}
|
||||
{tab === 'nodos' && (
|
||||
<>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '1.5rem' }}>
|
||||
<h2 style={{ fontSize: '1.3rem', fontWeight: 600 }}><i className="fas fa-server" style={{ color: 'var(--primary)', marginRight: '0.5rem' }}></i>Gestión de Nodos</h2>
|
||||
<button className="btn btn-primary" onClick={() => openNodoForm()}>
|
||||
<i className="fas fa-plus"></i> Nuevo Nodo
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Nodo Form */}
|
||||
{nodoFormVisible && (
|
||||
<div className="card" style={{ marginBottom: '1.5rem' }}>
|
||||
<div className="card-header">
|
||||
<i className={editNodoId ? 'fas fa-pen' : 'fas fa-plus-circle'}></i>
|
||||
{editNodoId ? 'Editar Nodo' : 'Nuevo Nodo'}
|
||||
</div>
|
||||
<form className="form-inline" onSubmit={saveNodo}>
|
||||
<input type="text" value={nodoNombre} onChange={e => setNodoNombre(e.target.value)} placeholder="Nombre (ej: srv-ns8)" required style={{ minWidth: '150px' }} />
|
||||
<input type="text" value={nodoIp} onChange={e => setNodoIp(e.target.value)} placeholder="IP (ej: 10.0.10.200)" style={{ minWidth: '130px' }} />
|
||||
<select value={nodoTipo} onChange={e => setNodoTipo(e.target.value)}>
|
||||
<option value="servidor">Servidor</option>
|
||||
<option value="vm">VM</option>
|
||||
<option value="pc">PC</option>
|
||||
<option value="switch">Switch</option>
|
||||
<option value="otro">Otro</option>
|
||||
</select>
|
||||
<input type="text" className="input-desc" value={nodoDesc} onChange={e => setNodoDesc(e.target.value)} placeholder="Descripción..." />
|
||||
<button type="submit" className="btn btn-success"><i className="fas fa-save"></i> {editNodoId ? 'Actualizar' : 'Crear'}</button>
|
||||
<button type="button" className="btn btn-sm" onClick={resetNodoForm} style={{ background: 'var(--bg-card)', color: 'var(--text-muted)', border: '1px solid var(--border)' }}>
|
||||
<i className="fas fa-times"></i> Cancelar
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Nodos Table */}
|
||||
<div className="card">
|
||||
<table className="table-ifde">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>ID</th>
|
||||
<th>Nombre</th>
|
||||
<th>IP</th>
|
||||
<th>Tipo</th>
|
||||
<th>Descripción</th>
|
||||
<th style={{ width: '80px' }}>Acc.</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{nodos.map(n => (
|
||||
<tr key={n.id}>
|
||||
<td style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}>{n.id}</td>
|
||||
<td style={{ fontWeight: 600 }}>{n.nombre}</td>
|
||||
<td style={{ fontFamily: 'monospace', color: 'var(--text-secondary)' }}>{n.ip || '—'}</td>
|
||||
<td><span className="badge" style={{ background: 'rgba(102, 126, 234, 0.15)', color: 'var(--primary)' }}>{n.tipo || 'N/A'}</span></td>
|
||||
<td style={{ color: 'var(--text-secondary)', fontSize: '0.85rem' }}>{n.descripcion || '—'}</td>
|
||||
<td>
|
||||
<div style={{ display: 'flex', gap: '0.2rem' }}>
|
||||
<button className="btn btn-sm" onClick={() => openNodoForm(n)} title="Editar"
|
||||
style={{ background: 'var(--info)', color: 'white' }}>
|
||||
<i className="fas fa-pen"></i>
|
||||
</button>
|
||||
<button className="btn btn-sm btn-danger" onClick={() => requestDeleteNodo(n.id, n.nombre)} title="Eliminar">
|
||||
<i className="fas fa-trash-alt"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* =================== TAB PROYECTO =================== */}
|
||||
{tab === 'proyecto' && (
|
||||
<ProyectoDashboard codigo="P2601" />
|
||||
)}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
@@ -0,0 +1,468 @@
|
||||
/* dtic-BITACORAs — Estética del Dashboard P2601 */
|
||||
|
||||
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
|
||||
|
||||
:root {
|
||||
--primary: #667eea;
|
||||
--secondary: #764ba2;
|
||||
--gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
||||
--success: #10b981;
|
||||
--warning: #f59e0b;
|
||||
--danger: #ef4444;
|
||||
--info: #3b82f6;
|
||||
--bg: #0f172a;
|
||||
--bg-card: #1e293b;
|
||||
--bg-card-hover: #334155;
|
||||
--bg-input: #1e293b;
|
||||
--text: #f1f5f9;
|
||||
--text-secondary: #94a3b8;
|
||||
--text-muted: #64748b;
|
||||
--border: #334155;
|
||||
--radius: 12px;
|
||||
--shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
|
||||
--transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
/* Layout */
|
||||
.app {
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
background: rgba(15, 23, 42, 0.8);
|
||||
backdrop-filter: blur(20px);
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 1rem 2rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 100;
|
||||
}
|
||||
|
||||
.navbar-brand {
|
||||
font-size: 1.4rem;
|
||||
font-weight: 700;
|
||||
background: var(--gradient);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.navbar-brand i {
|
||||
-webkit-text-fill-color: initial;
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border-radius: 20px;
|
||||
font-size: 0.7rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
.badge-gradient {
|
||||
background: var(--gradient);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Main content */
|
||||
.main {
|
||||
flex: 1;
|
||||
padding: 2rem;
|
||||
max-width: 1400px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
/* Cards */
|
||||
.card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1.5rem;
|
||||
transition: var(--transition);
|
||||
animation: fadeIn 0.5s ease-out;
|
||||
}
|
||||
|
||||
.card:hover {
|
||||
transform: translateY(-2px);
|
||||
box-shadow: var(--shadow);
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.card-header {
|
||||
background: var(--gradient);
|
||||
color: white;
|
||||
padding: 1rem 1.5rem;
|
||||
border-radius: var(--radius) var(--radius) 0 0;
|
||||
margin: -1.5rem -1.5rem 1.5rem;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
/* Table I-F-D-E */
|
||||
.table-ifde {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.table-ifde th {
|
||||
background: rgba(102, 126, 234, 0.15);
|
||||
color: var(--primary);
|
||||
padding: 0.75rem 1rem;
|
||||
text-align: left;
|
||||
font-weight: 600;
|
||||
font-size: 0.8rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.table-ifde td {
|
||||
padding: 0.75rem 1rem;
|
||||
border-bottom: 1px solid var(--border);
|
||||
vertical-align: top;
|
||||
}
|
||||
|
||||
.table-ifde tr:hover td {
|
||||
background: rgba(102, 126, 234, 0.05);
|
||||
}
|
||||
|
||||
.table-ifde .col-time {
|
||||
width: 60px;
|
||||
font-family: 'JetBrains Mono', monospace;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.table-ifde .col-status {
|
||||
width: 80px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.table-ifde .col-desc {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.table-ifde .ia-tag {
|
||||
background: rgba(102, 126, 234, 0.2);
|
||||
color: var(--primary);
|
||||
padding: 0.1rem 0.4rem;
|
||||
border-radius: 4px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
margin-right: 0.3rem;
|
||||
}
|
||||
|
||||
/* Nodo section */
|
||||
.nodo-section {
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.nodo-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
font-size: 1.1rem;
|
||||
font-weight: 600;
|
||||
margin-bottom: 1rem;
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 2px solid var(--border);
|
||||
}
|
||||
|
||||
.nodo-title i {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
.nodo-ip {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
/* Form inline */
|
||||
.form-inline {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
align-items: center;
|
||||
padding: 1rem;
|
||||
background: rgba(102, 126, 234, 0.05);
|
||||
border-radius: var(--radius);
|
||||
margin-top: 1rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.form-inline input,
|
||||
.form-inline select {
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
padding: 0.5rem 0.75rem;
|
||||
border-radius: 8px;
|
||||
font-size: 0.85rem;
|
||||
font-family: inherit;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.form-inline input:focus,
|
||||
.form-inline select:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
|
||||
}
|
||||
|
||||
.form-inline .input-time {
|
||||
width: 80px;
|
||||
}
|
||||
|
||||
.form-inline .input-desc {
|
||||
flex: 1;
|
||||
min-width: 200px;
|
||||
}
|
||||
|
||||
/* Buttons */
|
||||
.btn {
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: 8px;
|
||||
border: none;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: var(--transition);
|
||||
font-size: 0.85rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.btn:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-primary {
|
||||
background: var(--gradient);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-primary:hover {
|
||||
box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
|
||||
}
|
||||
|
||||
.btn-sm {
|
||||
padding: 0.3rem 0.6rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
|
||||
.btn-danger {
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
}
|
||||
|
||||
.btn-success {
|
||||
background: var(--success);
|
||||
color: white;
|
||||
}
|
||||
|
||||
/* Date selector */
|
||||
.date-selector {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
}
|
||||
|
||||
.date-selector input[type="date"] {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
padding: 0.6rem 1rem;
|
||||
border-radius: 8px;
|
||||
font-size: 1rem;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.date-selector input[type="date"]:focus {
|
||||
outline: none;
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
/* Stats bar */
|
||||
.stats-bar {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
margin-bottom: 2rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.stat-card {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 1rem 1.5rem;
|
||||
flex: 1;
|
||||
min-width: 150px;
|
||||
text-align: center;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.stat-card:hover {
|
||||
border-color: var(--primary);
|
||||
}
|
||||
|
||||
.stat-value {
|
||||
font-size: 2rem;
|
||||
font-weight: 700;
|
||||
background: var(--gradient);
|
||||
-webkit-background-clip: text;
|
||||
-webkit-text-fill-color: transparent;
|
||||
}
|
||||
|
||||
.stat-label {
|
||||
font-size: 0.8rem;
|
||||
color: var(--text-muted);
|
||||
margin-top: 0.3rem;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
}
|
||||
|
||||
/* Animations */
|
||||
@keyframes fadeIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(10px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Scrollbar */
|
||||
::-webkit-scrollbar {
|
||||
width: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-track {
|
||||
background: var(--bg);
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: var(--border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: var(--text-muted);
|
||||
}
|
||||
|
||||
/* Responsive */
|
||||
@media (max-width: 768px) {
|
||||
.main {
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.navbar {
|
||||
padding: 0.75rem 1rem;
|
||||
}
|
||||
|
||||
.stats-bar {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.form-inline {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.form-inline .input-desc {
|
||||
min-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* Modal de confirmación */
|
||||
.modal-overlay {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0, 0, 0, 0.6);
|
||||
backdrop-filter: blur(4px);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 1000;
|
||||
animation: fadeIn 0.2s ease-out;
|
||||
}
|
||||
|
||||
.modal-box {
|
||||
background: var(--bg-card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
padding: 0;
|
||||
max-width: 420px;
|
||||
width: 90%;
|
||||
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
|
||||
animation: fadeIn 0.3s ease-out;
|
||||
}
|
||||
|
||||
.modal-header {
|
||||
background: var(--danger);
|
||||
color: white;
|
||||
padding: 1rem 1.5rem;
|
||||
border-radius: var(--radius) var(--radius) 0 0;
|
||||
font-weight: 600;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.modal-body {
|
||||
padding: 1.5rem;
|
||||
color: var(--text-secondary);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.modal-actions {
|
||||
padding: 0 1.5rem 1.5rem;
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
/* Campos de edición inline */
|
||||
.edit-input {
|
||||
background: var(--bg-input);
|
||||
border: 1px solid var(--primary);
|
||||
color: var(--text);
|
||||
padding: 0.35rem 0.5rem;
|
||||
border-radius: 6px;
|
||||
font-size: 0.8rem;
|
||||
font-family: inherit;
|
||||
transition: var(--transition);
|
||||
}
|
||||
|
||||
.edit-input:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.2);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom/client';
|
||||
import App from './App';
|
||||
import './index.css';
|
||||
|
||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>
|
||||
);
|
||||
@@ -0,0 +1,645 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
|
||||
const API_URL = import.meta.env.VITE_API_URL || '/bitacoras/api';
|
||||
|
||||
interface Hito {
|
||||
id: number;
|
||||
id_hito: string;
|
||||
titulo: string;
|
||||
descripcion: string;
|
||||
estado: string;
|
||||
fecha: string | null;
|
||||
horas_presencial: number;
|
||||
horas_remoto: number;
|
||||
nodo_nombre: string;
|
||||
nodo_ip: string;
|
||||
}
|
||||
|
||||
interface Fase {
|
||||
id: number;
|
||||
numero: number;
|
||||
nombre: string;
|
||||
estado: string;
|
||||
descripcion: string;
|
||||
fecha_inicio: string | null;
|
||||
fecha_fin: string | null;
|
||||
hitos: Hito[] | null;
|
||||
}
|
||||
|
||||
interface NodoInfo {
|
||||
id: number;
|
||||
nombre: string;
|
||||
ip: string;
|
||||
tipo: string;
|
||||
descripcion: string;
|
||||
}
|
||||
|
||||
interface Metricas {
|
||||
hitos_completados: string;
|
||||
hitos_pendientes: string;
|
||||
hitos_total: string;
|
||||
total_presencial: string;
|
||||
total_remoto: string;
|
||||
total_horas: string;
|
||||
}
|
||||
|
||||
interface Proyecto {
|
||||
id: number;
|
||||
codigo: string;
|
||||
nombre: string;
|
||||
estado: string;
|
||||
descripcion: string;
|
||||
fases: Fase[];
|
||||
metricas: Metricas;
|
||||
nodos: NodoInfo[];
|
||||
}
|
||||
|
||||
type Vista = 'gerencial' | 'tecnica';
|
||||
|
||||
/* ═══════════ DONUT CHART SVG ═══════════ */
|
||||
function DonutChart({ segments, size = 140, strokeWidth = 18, centerLabel, centerValue, centerColor }: {
|
||||
segments: { value: number; color: string; label: string }[];
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
centerLabel?: string;
|
||||
centerValue?: string;
|
||||
centerColor?: string;
|
||||
}) {
|
||||
const radius = (size - strokeWidth) / 2;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const total = segments.reduce((s, seg) => s + seg.value, 0);
|
||||
let offset = 0;
|
||||
|
||||
return (
|
||||
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '0.5rem' }}>
|
||||
<svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
|
||||
{/* Fondo gris */}
|
||||
<circle cx={size / 2} cy={size / 2} r={radius}
|
||||
fill="none" stroke="rgba(255,255,255,0.05)" strokeWidth={strokeWidth} />
|
||||
{/* Segmentos */}
|
||||
{total > 0 && segments.map((seg, i) => {
|
||||
const segLen = (seg.value / total) * circumference;
|
||||
const el = (
|
||||
<circle key={i} cx={size / 2} cy={size / 2} r={radius}
|
||||
fill="none" stroke={seg.color} strokeWidth={strokeWidth}
|
||||
strokeDasharray={`${segLen} ${circumference - segLen}`}
|
||||
strokeDashoffset={-offset}
|
||||
strokeLinecap="round"
|
||||
style={{ transition: 'stroke-dasharray 0.6s ease, stroke-dashoffset 0.6s ease' }}
|
||||
/>
|
||||
);
|
||||
offset += segLen;
|
||||
return el;
|
||||
})}
|
||||
{/* Texto central */}
|
||||
{centerValue && (
|
||||
<g style={{ transform: 'rotate(90deg)', transformOrigin: 'center' }}>
|
||||
<text x={size / 2} y={size / 2 - 4} textAnchor="middle" dominantBaseline="middle"
|
||||
fill={centerColor || '#fff'} fontSize="1.6rem" fontWeight="700">{centerValue}</text>
|
||||
{centerLabel && (
|
||||
<text x={size / 2} y={size / 2 + 16} textAnchor="middle" dominantBaseline="middle"
|
||||
fill="var(--text-muted)" fontSize="0.6rem" style={{ textTransform: 'uppercase', letterSpacing: '0.05em' }}>{centerLabel}</text>
|
||||
)}
|
||||
</g>
|
||||
)}
|
||||
</svg>
|
||||
{/* Leyenda */}
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem 1rem', justifyContent: 'center' }}>
|
||||
{segments.filter(s => s.value > 0).map((seg, i) => (
|
||||
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: '4px', fontSize: '0.7rem', color: 'var(--text-muted)' }}>
|
||||
<span style={{ width: 8, height: 8, borderRadius: '50%', background: seg.color, flexShrink: 0 }}></span>
|
||||
{seg.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ═══════════ CONTENIDO ENRIQUECIDO POR FASE ═══════════ */
|
||||
const faseDetalles: Record<number, { objetivo: string; desarrollo: string; logros: string }> = {
|
||||
1: {
|
||||
objetivo: 'Preparar el equipo central que alojará todos los servicios de DASUTeN, garantizando que opere de forma independiente a los sistemas de la Facultad.',
|
||||
desarrollo: 'Se instaló y configuró el servidor dedicado en la oficina de DASUTeN, creando un entorno de trabajo completamente separado de la red universitaria para mayor seguridad y control.',
|
||||
logros: 'Servidor propio operativo y listo para funcionar. Entorno aislado que brinda independencia total respecto a los sistemas de la Facultad.'
|
||||
},
|
||||
2: {
|
||||
objetivo: 'Establecer un sistema centralizado de identificación de usuarios y permisos de acceso, propio de la oficina DASUTeN.',
|
||||
desarrollo: 'Se configuró un servicio de gestión de identidades que permite controlar quién accede a cada equipo y recurso dentro de la red de DASUTeN.',
|
||||
logros: 'Sistema de usuarios operativo. Cada persona accede con credenciales propias. Se simplifica la administración de permisos y la seguridad de acceso.'
|
||||
},
|
||||
3: {
|
||||
objetivo: 'Instalar el sistema de base de datos necesario y recuperar toda la información del sistema DASUTeN desde el respaldo existente.',
|
||||
desarrollo: 'Se preparó un entorno dedicado para la base de datos, se transfirió el respaldo completo (~9 GB de información) y se restauró verificando su integridad.',
|
||||
logros: 'Toda la información de gestión de DASUTeN fue recuperada exitosamente. La base de datos está operativa y accesible desde la red interna.'
|
||||
},
|
||||
4: {
|
||||
objetivo: 'Habilitar la administración remota segura de todos los equipos y generar respaldos de seguridad como punto de recuperación.',
|
||||
desarrollo: 'Se activó el acceso remoto seguro en todos los equipos y se generaron copias de respaldo completas para poder restaurar el sistema ante cualquier eventualidad.',
|
||||
logros: 'Posibilidad de gestionar todos los equipos sin necesidad de presencia física. Respaldos de seguridad disponibles ante cualquier imprevisto.'
|
||||
},
|
||||
5: {
|
||||
objetivo: 'Analizar la aplicación de gestión DASUTeN y ponerla en funcionamiento sobre la nueva infraestructura virtual.',
|
||||
desarrollo: 'Configuración de Kermet.ini, instalación de componentes de sistema, fuentes y apertura de firewall SQL. Pruebas de conectividad exitosas.',
|
||||
logros: 'Despliegue operativo verificado con login exitoso. Validación presencial (UAT) realizada con Andrea Almirón satisfactoriamente.'
|
||||
},
|
||||
6: {
|
||||
objetivo: '🚀 Poner en funcionamiento el servidor físico en la oficina, integrar clientes al dominio y configurar políticas de seguridad.',
|
||||
desarrollo: 'Traslado físico del servidor Proxmox, unión de la PC pc-dasu0 al dominio dasuten.utnlr y despliegue de GPOs de seguridad.',
|
||||
logros: 'Hitos pendientes: Instalación física, AD-Join, GPO de seguridad y mapeo de unidades de red.'
|
||||
}
|
||||
};
|
||||
|
||||
/* ═══════════ MAIN COMPONENT ═══════════ */
|
||||
export default function ProyectoDashboard({ codigo = 'P2601' }: { codigo?: string }) {
|
||||
const [proyecto, setProyecto] = useState<Proyecto | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [vista, setVista] = useState<Vista>('gerencial');
|
||||
const [expandedFases, setExpandedFases] = useState<Set<number>>(new Set());
|
||||
const [expandedGerFases, setExpandedGerFases] = useState<Set<number>>(new Set());
|
||||
const [descExpanded, setDescExpanded] = useState(false);
|
||||
|
||||
useEffect(() => { fetchProyecto(); }, [codigo]);
|
||||
|
||||
const fetchProyecto = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await fetch(`${API_URL}/proyectos/${codigo}`);
|
||||
if (!res.ok) throw new Error('Proyecto no encontrado');
|
||||
const data = await res.json();
|
||||
setProyecto(data);
|
||||
setExpandedFases(new Set(data.fases.map((f: Fase) => f.id)));
|
||||
} catch (e: any) {
|
||||
setError(e.message);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleFase = (id: number) => {
|
||||
setExpandedFases(prev => {
|
||||
const next = new Set(prev);
|
||||
next.has(id) ? next.delete(id) : next.add(id);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const toggleGerFase = (num: number) => {
|
||||
setExpandedGerFases(prev => {
|
||||
const next = new Set(prev);
|
||||
next.has(num) ? next.delete(num) : next.add(num);
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
if (loading) return <div style={{ textAlign: 'center', padding: '3rem', color: 'var(--text-muted)' }}>Cargando proyecto...</div>;
|
||||
if (error || !proyecto) return <div style={{ textAlign: 'center', padding: '3rem', color: '#ef4444' }}>Error: {error}</div>;
|
||||
|
||||
const m = proyecto.metricas;
|
||||
const totalH = parseFloat(m.total_horas);
|
||||
const completados = parseInt(m.hitos_completados);
|
||||
const pendientes = parseInt(m.hitos_pendientes);
|
||||
const totalHitos = parseInt(m.hitos_total);
|
||||
const progreso = totalHitos > 0 ? Math.round((completados / totalHitos) * 100) : 0;
|
||||
const hrsP = parseFloat(m.total_presencial);
|
||||
const hrsR = parseFloat(m.total_remoto);
|
||||
|
||||
const fasesCompletas = proyecto.fases.filter(f => f.estado === '✅').length;
|
||||
const fasesEnCurso = proyecto.fases.filter(f => f.estado === '⏳').length;
|
||||
const fasesPendientes = proyecto.fases.filter(f => f.estado !== '✅' && f.estado !== '⏳').length;
|
||||
|
||||
const estadoIcon = (estado: string) => {
|
||||
if (estado === '✅') return '✅';
|
||||
if (estado === '⏳') return '⏳';
|
||||
if (estado === '📋') return '📋';
|
||||
return estado;
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="proyecto-dashboard">
|
||||
{/* Header */}
|
||||
<div style={{ textAlign: 'center', marginBottom: '1.5rem' }}>
|
||||
<div style={{
|
||||
display: 'inline-block', padding: '3px 12px', borderRadius: '999px',
|
||||
background: 'rgba(56,189,248,0.12)', color: '#38bdf8',
|
||||
fontSize: '0.72rem', fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase',
|
||||
marginBottom: '0.5rem'
|
||||
}}>{proyecto.codigo}</div>
|
||||
<h2 style={{ fontSize: '1.5rem', fontWeight: 700, margin: '0.3rem 0' }}>
|
||||
{proyecto.nombre}
|
||||
</h2>
|
||||
<p style={{ color: 'var(--text-muted)', fontSize: '0.85rem', maxWidth: '600px', margin: '0 auto 0.8rem' }}>
|
||||
{proyecto.descripcion}
|
||||
</p>
|
||||
|
||||
{/* Toggle vista */}
|
||||
<div style={{
|
||||
display: 'inline-flex', borderRadius: '8px', overflow: 'hidden',
|
||||
border: '1px solid var(--border)', background: 'rgba(255,255,255,0.03)'
|
||||
}}>
|
||||
<button
|
||||
onClick={() => setVista('gerencial')}
|
||||
style={{
|
||||
padding: '6px 16px', fontSize: '0.75rem', fontWeight: 600, border: 'none', cursor: 'pointer',
|
||||
background: vista === 'gerencial' ? 'linear-gradient(135deg, #38bdf8, #818cf8)' : 'transparent',
|
||||
color: vista === 'gerencial' ? '#fff' : 'var(--text-muted)', transition: 'all 0.2s ease'
|
||||
}}
|
||||
><i className="fas fa-chart-pie" style={{ marginRight: '5px' }}></i>Resumen</button>
|
||||
<button
|
||||
onClick={() => setVista('tecnica')}
|
||||
style={{
|
||||
padding: '6px 16px', fontSize: '0.75rem', fontWeight: 600, border: 'none', cursor: 'pointer',
|
||||
background: vista === 'tecnica' ? 'linear-gradient(135deg, #38bdf8, #818cf8)' : 'transparent',
|
||||
color: vista === 'tecnica' ? '#fff' : 'var(--text-muted)', transition: 'all 0.2s ease'
|
||||
}}
|
||||
><i className="fas fa-list-alt" style={{ marginRight: '5px' }}></i>Detalle Técnico</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ═══════════ VISTA GERENCIAL ═══════════ */}
|
||||
{vista === 'gerencial' && (
|
||||
<>
|
||||
{/* Descripción del Proyecto — desplegable */}
|
||||
<div className="card" style={{ padding: 0, overflow: 'hidden', marginBottom: '1.5rem' }}>
|
||||
<div
|
||||
onClick={() => setDescExpanded(prev => !prev)}
|
||||
style={{
|
||||
padding: '0.8rem 1rem', cursor: 'pointer', display: 'flex',
|
||||
alignItems: 'center', justifyContent: 'space-between',
|
||||
userSelect: 'none'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
|
||||
<span style={{ fontSize: '1.1rem' }}>📋</span>
|
||||
<span style={{ fontWeight: 600, fontSize: '0.88rem' }}>Descripción del Proyecto</span>
|
||||
</div>
|
||||
<span style={{ fontSize: '0.8rem', color: 'var(--text-muted)', transition: 'transform 0.2s' }}>
|
||||
{descExpanded ? '▾' : '▸'}
|
||||
</span>
|
||||
</div>
|
||||
{descExpanded && (
|
||||
<div style={{ padding: '0 1rem 1rem', lineHeight: 1.6, fontSize: '0.82rem', color: 'var(--text)' }}>
|
||||
<p style={{ margin: '0 0 0.8rem' }}>
|
||||
<strong>DASUTeN</strong> es la obra social que brinda cobertura a empleados, docentes y alumnos de la
|
||||
Universidad Tecnológica Nacional. Su oficina en la Facultad Regional La Rioja depende
|
||||
operativamente de la <strong>sede central en Buenos Aires</strong>.
|
||||
</p>
|
||||
<p style={{ margin: '0 0 0.8rem' }}>
|
||||
Este proyecto tiene como objetivo <strong>dotar a la oficina DASUTeN de su propia infraestructura
|
||||
tecnológica independiente</strong>, operando bajo un entorno virtualizado (Proxmox) con acceso remoto seguro vía Tailscale.
|
||||
</p>
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)',
|
||||
gap: '1.2rem', marginTop: '1rem'
|
||||
}}>
|
||||
<div>
|
||||
<div style={subheadStyle}>🎯 Objetivos y Alcance</div>
|
||||
<ul style={listStyle}>
|
||||
<li>Sistema de gestión operando desde servidor propio</li>
|
||||
<li>Independencia total de los equipos de la Facultad</li>
|
||||
<li>Oficina autosuficiente con su propia red y respaldos</li>
|
||||
<li>Servidor dedicado en oficina DASUTeN</li>
|
||||
<li>Red interna propia y segura</li>
|
||||
<li>Computadora de escritorio como acceso al sistema</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div>
|
||||
<div style={subheadStyle}>👥 Responsables y Beneficiarios</div>
|
||||
<ul style={listStyle}>
|
||||
<li><strong>Ejecución:</strong> Lic. Ricardo Monla</li>
|
||||
<li><strong>Supervisión:</strong> Dirección de TIC</li>
|
||||
</ul>
|
||||
<div style={{ fontSize: '0.7rem', color: '#38bdf8', fontWeight: 600, marginTop: '0.4rem', marginBottom: '0.2rem' }}>Usuarios directos:</div>
|
||||
<ul style={listStyle}>
|
||||
<li>Andrea Almirón — Administrativa DASUTeN</li>
|
||||
<li>Romina Molina — Administrativa</li>
|
||||
<li>Dra. Eugenia Riveros — Auditora Médica</li>
|
||||
</ul>
|
||||
<div style={{ fontSize: '0.7rem', color: '#38bdf8', fontWeight: 600, marginTop: '0.4rem', marginBottom: '0.2rem' }}>Beneficiarios indirectos:</div>
|
||||
<ul style={listStyle}>
|
||||
<li>Personal Docente</li>
|
||||
<li>Personal No Docente</li>
|
||||
<li>Alumnos</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Gráficos de torta */}
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
|
||||
gap: '1.2rem', marginBottom: '1.8rem'
|
||||
}}>
|
||||
{/* Donut: Estado de Fases */}
|
||||
<div className="card" style={{ padding: '1.2rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
|
||||
<div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.6rem', fontWeight: 600 }}>
|
||||
Estado de Fases
|
||||
</div>
|
||||
<DonutChart
|
||||
segments={[
|
||||
{ value: fasesCompletas, color: '#22c55e', label: `${fasesCompletas} Completas` },
|
||||
{ value: fasesEnCurso, color: '#eab308', label: `${fasesEnCurso} En curso` },
|
||||
{ value: fasesPendientes, color: '#64748b', label: `${fasesPendientes} Pendientes` },
|
||||
]}
|
||||
centerValue={`${fasesCompletas + fasesEnCurso}/${proyecto.fases.length}`}
|
||||
centerLabel="fases"
|
||||
centerColor="#22c55e"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Donut: Avance Global */}
|
||||
<div className="card" style={{ padding: '1.2rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
|
||||
<div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.6rem', fontWeight: 600 }}>
|
||||
Avance de Hitos
|
||||
</div>
|
||||
<DonutChart
|
||||
segments={[
|
||||
{ value: completados, color: '#22c55e', label: `${completados} Completados` },
|
||||
{ value: pendientes, color: '#eab308', label: `${pendientes} Pendientes` },
|
||||
]}
|
||||
centerValue={`${progreso}%`}
|
||||
centerLabel="avance"
|
||||
centerColor="#22c55e"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Donut: Distribución de Horas */}
|
||||
<div className="card" style={{ padding: '1.2rem', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
|
||||
<div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: '0.6rem', fontWeight: 600 }}>
|
||||
Distribución de Horas
|
||||
</div>
|
||||
<DonutChart
|
||||
segments={[
|
||||
{ value: hrsP, color: '#f97316', label: `${hrsP.toFixed(1)}h Presencial` },
|
||||
{ value: hrsR, color: '#a78bfa', label: `${hrsR.toFixed(1)}h Remoto` },
|
||||
]}
|
||||
centerValue={`${totalH.toFixed(0)}h`}
|
||||
centerLabel="total"
|
||||
centerColor="#38bdf8"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Fases con descripciones expandibles */}
|
||||
<SectionTitle title="📊 Fases del Proyecto" />
|
||||
{proyecto.fases.map(fase => {
|
||||
const hitos = fase.hitos || [];
|
||||
const faseCompletos = hitos.filter(h => h.estado === '✅').length;
|
||||
const faseProgreso = hitos.length > 0 ? Math.round((faseCompletos / hitos.length) * 100) : 0;
|
||||
const hrsTotal = hitos.reduce((s, h) => s + h.horas_presencial + h.horas_remoto, 0);
|
||||
const isExpanded = expandedGerFases.has(fase.numero);
|
||||
const detalle = faseDetalles[fase.numero];
|
||||
|
||||
return (
|
||||
<div key={fase.id} className="card" style={{
|
||||
marginBottom: '0.6rem', padding: 0, overflow: 'hidden', position: 'relative'
|
||||
}}>
|
||||
{/* Barra de progreso de fondo */}
|
||||
<div style={{
|
||||
position: 'absolute', top: 0, left: 0, bottom: 0, width: `${faseProgreso}%`,
|
||||
background: fase.estado === '✅' ? 'rgba(34,197,94,0.06)' : 'rgba(56,189,248,0.04)',
|
||||
transition: 'width 0.4s', pointerEvents: 'none'
|
||||
}} />
|
||||
|
||||
{/* Header clickeable */}
|
||||
<div
|
||||
onClick={() => toggleGerFase(fase.numero)}
|
||||
style={{
|
||||
position: 'relative', display: 'flex', justifyContent: 'space-between',
|
||||
alignItems: 'center', padding: '0.8rem 1rem', cursor: 'pointer'
|
||||
}}
|
||||
>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.7rem' }}>
|
||||
<span style={{
|
||||
fontSize: '1.3rem', width: '36px', height: '36px', display: 'flex',
|
||||
alignItems: 'center', justifyContent: 'center', borderRadius: '8px',
|
||||
background: fase.estado === '✅' ? 'rgba(34,197,94,0.12)' :
|
||||
fase.estado === '⏳' ? 'rgba(234,179,8,0.12)' : 'rgba(255,255,255,0.05)'
|
||||
}}>{estadoIcon(fase.estado)}</span>
|
||||
<div>
|
||||
<div style={{ fontWeight: 600, fontSize: '0.88rem' }}>
|
||||
F{fase.numero} · {fase.nombre}
|
||||
</div>
|
||||
{!isExpanded && fase.descripcion && (
|
||||
<div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '2px' }}>
|
||||
{fase.descripcion}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '1rem', flexShrink: 0 }}>
|
||||
{hrsTotal > 0 && (
|
||||
<span style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>{hrsTotal.toFixed(1)}h</span>
|
||||
)}
|
||||
<div style={{
|
||||
minWidth: '52px', textAlign: 'right', fontWeight: 700, fontSize: '0.85rem',
|
||||
color: faseProgreso === 100 ? '#22c55e' : faseProgreso > 0 ? '#38bdf8' : 'var(--text-muted)'
|
||||
}}>{faseProgreso}%</div>
|
||||
<span style={{ color: 'var(--text-muted)', fontSize: '0.8rem' }}>{isExpanded ? '▾' : '▸'}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Detalle expandible */}
|
||||
{isExpanded && detalle && (
|
||||
<div style={{
|
||||
position: 'relative', borderTop: '1px solid var(--border)',
|
||||
padding: '0.8rem 1rem',
|
||||
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))', gap: '0.8rem'
|
||||
}}>
|
||||
<FaseDetailCol icon="🎯" title="Objetivo" text={detalle.objetivo} />
|
||||
<FaseDetailCol icon="⚙️" title="Desarrollo" text={detalle.desarrollo} />
|
||||
<FaseDetailCol icon="✨" title="Logros" text={detalle.logros} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
|
||||
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ═══════════ VISTA TÉCNICA ═══════════ */}
|
||||
{vista === 'tecnica' && (
|
||||
<>
|
||||
{/* Métricas numéricas */}
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(130px, 1fr))',
|
||||
gap: '0.8rem', marginBottom: '1.5rem'
|
||||
}}>
|
||||
<MetricCard label="Fases" value={`${fasesCompletas + fasesEnCurso}/${proyecto.fases.length}`} color="#38bdf8" />
|
||||
<MetricCard label="Hitos Comp." value={m.hitos_completados} color="#22c55e" />
|
||||
<MetricCard label="Hitos Pend." value={m.hitos_pendientes} color="#eab308" />
|
||||
<MetricCard label="Hrs Físicas" value={`${hrsP.toFixed(1)}h`} color="#f97316" />
|
||||
<MetricCard label="Esfuerzo Total" value={`${totalH.toFixed(1)}h`} color="#a78bfa" />
|
||||
</div>
|
||||
|
||||
{/* Barra progreso */}
|
||||
<div style={{ marginBottom: '1.5rem' }}>
|
||||
<div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '0.85rem', marginBottom: '0.3rem' }}>
|
||||
<span style={{ fontWeight: 600 }}>Avance Global</span>
|
||||
<span style={{ color: '#38bdf8', fontWeight: 600 }}>{progreso}%</span>
|
||||
</div>
|
||||
<div style={{
|
||||
width: '100%', height: '10px', background: 'rgba(255,255,255,0.06)',
|
||||
borderRadius: '999px', overflow: 'hidden'
|
||||
}}>
|
||||
<div style={{
|
||||
width: `${progreso}%`, height: '100%', borderRadius: '999px',
|
||||
background: 'linear-gradient(90deg, #38bdf8, #818cf8)', transition: 'width 0.6s ease'
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Nodos */}
|
||||
<SectionTitle title="🖧 Nodos del Proyecto" />
|
||||
<div style={{
|
||||
display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(160px, 1fr))',
|
||||
gap: '0.7rem', marginBottom: '1.5rem'
|
||||
}}>
|
||||
{proyecto.nodos.map(n => (
|
||||
<div key={n.id} className="card" style={{ padding: '0.8rem' }}>
|
||||
<div style={{ fontWeight: 700, fontSize: '0.85rem', marginBottom: '0.3rem' }}>{n.nombre}</div>
|
||||
<div style={{ fontSize: '0.75rem', color: 'var(--text-muted)' }}>
|
||||
{n.ip && <><code style={codeStyle}>{n.ip}</code><br /></>}
|
||||
{n.descripcion}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Fases detalladas */}
|
||||
<SectionTitle title="📋 Fases del Proyecto" />
|
||||
{proyecto.fases.map(fase => {
|
||||
const hitos = fase.hitos || [];
|
||||
const faseCompletos = hitos.filter(h => h.estado === '✅').length;
|
||||
const faseProgreso = hitos.length > 0 ? Math.round((faseCompletos / hitos.length) * 100) : 0;
|
||||
const fasHrsP = hitos.reduce((s, h) => s + h.horas_presencial, 0);
|
||||
const fasHrsR = hitos.reduce((s, h) => s + h.horas_remoto, 0);
|
||||
const expanded = expandedFases.has(fase.id);
|
||||
|
||||
return (
|
||||
<div key={fase.id} className="card" style={{ marginBottom: '0.8rem', padding: 0, overflow: 'hidden' }}>
|
||||
<div onClick={() => toggleFase(fase.id)} style={{
|
||||
padding: '0.8rem 1rem', cursor: 'pointer', display: 'flex',
|
||||
justifyContent: 'space-between', alignItems: 'center',
|
||||
borderBottom: expanded ? '1px solid var(--border)' : 'none'
|
||||
}}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.6rem' }}>
|
||||
<span style={{ fontSize: '0.7rem', color: '#38bdf8', fontWeight: 700 }}>F{fase.numero}</span>
|
||||
<span style={{ fontWeight: 600, fontSize: '0.9rem' }}>{fase.nombre}</span>
|
||||
<span style={{ fontSize: '0.8rem' }}>{estadoIcon(fase.estado)}</span>
|
||||
</div>
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '0.8rem', fontSize: '0.72rem', color: 'var(--text-muted)' }}>
|
||||
{fasHrsP > 0 && <span style={{ color: '#f97316' }}>🏢 {fasHrsP.toFixed(1)}h</span>}
|
||||
{fasHrsR > 0 && <span style={{ color: '#a78bfa' }}>💻 {fasHrsR.toFixed(1)}h</span>}
|
||||
<span style={{ color: '#38bdf8' }}>{faseProgreso}%</span>
|
||||
<span>{expanded ? '▾' : '▸'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style={{ height: '3px', background: 'rgba(255,255,255,0.03)' }}>
|
||||
<div style={{
|
||||
width: `${faseProgreso}%`, height: '100%',
|
||||
background: fase.estado === '✅' ? '#22c55e' : 'linear-gradient(90deg, #38bdf8, #818cf8)',
|
||||
transition: 'width 0.4s'
|
||||
}} />
|
||||
</div>
|
||||
{expanded && hitos.length > 0 && (
|
||||
<div style={{ padding: '0.5rem 1rem 0.8rem' }}>
|
||||
<table className="table-ifde" style={{ fontSize: '0.8rem' }}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style={{ width: '55px' }}>ID</th>
|
||||
<th>Hito</th>
|
||||
<th style={{ width: '75px' }}>Fecha</th>
|
||||
<th style={{ width: '60px' }}>🏢</th>
|
||||
<th style={{ width: '60px' }}>💻</th>
|
||||
<th style={{ width: '80px' }}>Nodo</th>
|
||||
<th style={{ width: '35px' }}>E</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{hitos.map(h => (
|
||||
<tr key={h.id}>
|
||||
<td><code style={{ fontSize: '0.72rem', color: '#38bdf8' }}>{h.id_hito}</code></td>
|
||||
<td>
|
||||
<strong>{h.titulo}</strong>
|
||||
{h.descripcion && <div style={{ fontSize: '0.72rem', color: 'var(--text-muted)', marginTop: '2px' }}>{h.descripcion}</div>}
|
||||
</td>
|
||||
<td style={{ fontSize: '0.72rem', color: 'var(--text-muted)' }}>
|
||||
{h.fecha ? new Date(h.fecha + 'T12:00:00').toLocaleDateString('es-AR', { day: '2-digit', month: '2-digit' }) : '—'}
|
||||
</td>
|
||||
<td style={{ textAlign: 'center', color: h.horas_presencial > 0 ? '#f97316' : 'var(--text-muted)' }}>
|
||||
{h.horas_presencial > 0 ? `${h.horas_presencial}h` : '—'}
|
||||
</td>
|
||||
<td style={{ textAlign: 'center', color: h.horas_remoto > 0 ? '#a78bfa' : 'var(--text-muted)' }}>
|
||||
{h.horas_remoto > 0 ? `${h.horas_remoto}h` : '—'}
|
||||
</td>
|
||||
<td style={{ fontSize: '0.72rem' }}>{h.nodo_nombre || '—'}</td>
|
||||
<td style={{ textAlign: 'center' }}>{estadoIcon(h.estado)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
|
||||
<div style={{ textAlign: 'center', color: 'var(--text-muted)', fontSize: '0.7rem', marginTop: '1.5rem', paddingTop: '0.8rem', borderTop: '1px solid var(--border)' }}>
|
||||
P2601 — Infraestructura DASUTEN · UTN FRLR · Dashboard integrado en dtic-BITACORAs
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/* ═══ Estilos compartidos ═══ */
|
||||
const codeStyle: React.CSSProperties = {
|
||||
background: 'rgba(255,255,255,0.06)', padding: '1px 4px', borderRadius: '3px', fontSize: '0.72rem'
|
||||
};
|
||||
const subheadStyle: React.CSSProperties = {
|
||||
fontSize: '0.75rem', fontWeight: 600, marginBottom: '0.4rem', color: '#38bdf8'
|
||||
};
|
||||
const listStyle: React.CSSProperties = {
|
||||
margin: 0, paddingLeft: '1.1rem', fontSize: '0.78rem', color: 'var(--text-muted)', lineHeight: 1.7
|
||||
};
|
||||
|
||||
/* ═══ Sub-componentes ═══ */
|
||||
function MetricCard({ label, value, color }: { label: string; value: string; color: string }) {
|
||||
return (
|
||||
<div className="card" style={{ padding: '0.9rem', textAlign: 'center' }}>
|
||||
<div style={{ fontSize: '1.5rem', fontWeight: 700, color, lineHeight: 1 }}>{value}</div>
|
||||
<div style={{ fontSize: '0.68rem', color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em', marginTop: '0.3rem' }}>{label}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SectionTitle({ title }: { title: string }) {
|
||||
return (
|
||||
<div style={{
|
||||
fontSize: '0.78rem', textTransform: 'uppercase', letterSpacing: '0.06em',
|
||||
color: 'var(--text-muted)', fontWeight: 600, marginBottom: '0.8rem',
|
||||
paddingBottom: '0.4rem', borderBottom: '1px solid var(--border)'
|
||||
}}>{title}</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FaseDetailCol({ icon, title, text }: { icon: string; title: string; text: string }) {
|
||||
return (
|
||||
<div>
|
||||
<div style={{ fontSize: '0.75rem', fontWeight: 600, color: '#38bdf8', marginBottom: '0.3rem' }}>
|
||||
{icon} {title}
|
||||
</div>
|
||||
<div style={{ fontSize: '0.76rem', color: 'var(--text-muted)', lineHeight: 1.5 }}>
|
||||
{text}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": [
|
||||
"ES2020",
|
||||
"DOM",
|
||||
"DOM.Iterable"
|
||||
],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": false,
|
||||
"noUnusedParameters": false,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "./tsconfig.node.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user