fix(optimizer): allow bedelia and operators access to ai room reservation optimizer v3.4.5
This commit is contained in:
@@ -11,6 +11,18 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
|
|||||||
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
||||||
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
||||||
|
|
||||||
|
## [3.4.5] - 2026-10-08
|
||||||
|
### Corregido & Mejorado (Optimizador de Aulas por Inteligencia Artificial - IA)
|
||||||
|
- **Corrección de Permisos RBAC para Bedelía y Operadores en el Optimizador Genético:**
|
||||||
|
- Resolución del bloqueo que devolvía `403 Forbidden` a usuarios con rol `Bedelia`, `Docente` o Administradores con roles formateados en minúsculas en los endpoints `/api/genetic/commissions`, `/api/genetic/algorithm-status`, `/api/genetic/preview-optimization`, `/api/genetic/optimize` y `/api/genetic/apply-optimization`.
|
||||||
|
- Creación del helper de verificación de permisos `check_optimizer_permission(user, requires_write)` en `backend/app/routes/genetic_algorithm.py` admitiendo a Administradores, Bedelía, Docentes y permisos RBAC personalizados.
|
||||||
|
- **Enriquecimiento del Listado de Comisiones para Asignación Áulica:**
|
||||||
|
- `GET /api/genetic/commissions` ahora expone `subject_name`, `subject_code`, `career_name`, `schedule` y `shift` para cada comisión activa.
|
||||||
|
- **Rediseño e Internacionalización de la Interfaz del Optimizador:**
|
||||||
|
- `frontend/views/genetic_optimizer.html`: Interfaz traducida integralmente a español institucional ("Optimizador Inteligente de Asignación de Aulas (IA)"), tarjetas interactivas de comisiones con badges de código, asignatura, carrera, turno, horario y aforo, buscador en vivo multi-criterio y manejo de errores visible.
|
||||||
|
- `frontend/public/js/genetic-algorithm.js`: Traducción de alertas, modales y tablas de resultados ("Resultados de la Optimización", "Previsualización", confirmación de aplicación directa a Bedelía).
|
||||||
|
- Protección de la ruta web `/genetic_optimizer` con `requireAuth` e inyección de datos de sesión en `frontend/src/app.js`.
|
||||||
|
|
||||||
## [3.4.4] - 2026-10-07
|
## [3.4.4] - 2026-10-07
|
||||||
### Añadido & Mejorado (Dashboard Operativo de Bedelía y Admin)
|
### Añadido & Mejorado (Dashboard Operativo de Bedelía y Admin)
|
||||||
- **Filtro Temporal "Mañana" en Switchers de Período y Cartelera:**
|
- **Filtro Temporal "Mañana" en Switchers de Período y Cartelera:**
|
||||||
|
|||||||
@@ -132,6 +132,22 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
|||||||
- Versión incrementada a `v3.4.4` en Frontend y Backend.
|
- Versión incrementada a `v3.4.4` en Frontend y Backend.
|
||||||
- Despliegue al servidor institucional `10.0.0.217` (`https://eduspace.oemspot.com.ar`) y verificación en caliente.
|
- Despliegue al servidor institucional `10.0.0.217` (`https://eduspace.oemspot.com.ar`) y verificación en caliente.
|
||||||
|
|
||||||
|
- **Sprint Optimizador de Aulas IA: Corrección de Permisos y Carga de Comisiones (v3.4.5)**:
|
||||||
|
- **Problema Reportado**: AI Room Reservation Optimizer no mostraba comisiones y los indicadores de Available Classrooms, Active Commissions y Existing Reservations quedaban en `--`.
|
||||||
|
- **Causa Raíz Identificada**:
|
||||||
|
- En `backend/app/routes/genetic_algorithm.py` las rutas `@genetic_bp.route('/commissions')`, `/algorithm-status`, `/preview-optimization`, `/optimize` y `/apply-optimization` exigían de forma estricta `g.jwt_user.role in ['ADMIN', 'teacher']` o `g.jwt_user.role in ['ADMIN']`.
|
||||||
|
- Al ingresar como Bedelía (`role == 'Bedelia'`), Docentes o Administradores con rol en minúsculas, el backend devolvía `403 Forbidden`, bloqueando la llamada AJAX y dejando la interfaz vacía con `--`.
|
||||||
|
- En el Frontend BFF, la ruta `/genetic_optimizer` no requería `requireAuth` ni pasaba datos de sesión de usuario a la plantilla.
|
||||||
|
- **Solución Implementada**:
|
||||||
|
- Creación del helper `check_optimizer_permission(user, requires_write)` en `backend/app/routes/genetic_algorithm.py` habilitando acceso a `admin`, `administrador`, `bedelia`, `docente`/`teacher` y permisos RBAC en 'optimizer'.
|
||||||
|
- `GET /api/genetic/commissions` ahora enriquece los objetos con `subject_name`, `subject_code`, `career_name`, `schedule` y `shift`.
|
||||||
|
- `frontend/views/genetic_optimizer.html`: Traducido íntegramente a español institucional ("Optimizador Inteligente de Asignación de Aulas (IA)"), tarjetas de comisiones con badges, buscador en vivo multi-criterio y manejo de errores visual.
|
||||||
|
- `frontend/public/js/genetic-algorithm.js`: Traducción de alertas, modales y tablas de resultados.
|
||||||
|
- `frontend/src/app.js`: Protección con `requireAuth` e inyección de sesión a la vista.
|
||||||
|
- **Bump Semántico y Despliegue Obligatorio (Principio 9)**:
|
||||||
|
- Versión incrementada a `v3.4.5` en Frontend y Backend.
|
||||||
|
- Despliegue inmediato al servidor institucional `10.0.0.217` y verificación en caliente HTTP 200.
|
||||||
|
|
||||||
## Próximos pasos
|
## Próximos pasos
|
||||||
1. Continuar con los objetivos de la Fase 6 del Roadmap institucional (Docker-compose productivo, Nginx con SSL y automatización de workers continuos Moodle).
|
1. Continuar con los objetivos de la Fase 6 del Roadmap institucional (Docker-compose productivo, Nginx con SSL y automatización de workers continuos Moodle).
|
||||||
2. Monitoreo continuo de la experiencia de usuario en Bedelía, Cartelera del Día y Sincronización Académica.
|
2. Monitoreo continuo de la experiencia de usuario en Bedelía, Cartelera del Día y Sincronización Académica.
|
||||||
+2
-2
@@ -2,8 +2,8 @@
|
|||||||
## Gestión de Espacios Áulicos, Asignación de Comisiones y Operatoria de Bedelía
|
## Gestión de Espacios Áulicos, Asignación de Comisiones y Operatoria de Bedelía
|
||||||
|
|
||||||
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
|
**Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA)
|
||||||
**Versión:** 3.4.4 (Dashboard Bedelía: Filtro Temporal "Mañana" en Switchers y Cartelera Operativa)
|
**Versión:** 3.4.5 (Optimizador de Aulas IA: Corrección de Permisos Bedelía, Carga de Comisiones e Interfaz en Español)
|
||||||
**Fecha de Actualización:** 07 de Octubre de 2026
|
**Fecha de Actualización:** 08 de Octubre de 2026
|
||||||
**Rama Base:** `dev`
|
**Rama Base:** `dev`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _
|
|||||||
from config.config import Config
|
from config.config import Config
|
||||||
|
|
||||||
# Initialize extensions
|
# Initialize extensions
|
||||||
__version__ = "3.4.4"
|
__version__ = "3.4.5"
|
||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
migrate = Migrate()
|
migrate = Migrate()
|
||||||
cors = CORS()
|
cors = CORS()
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ OPENAPI_SPEC = {
|
|||||||
"info": {
|
"info": {
|
||||||
"title": "Edu-Space REST API",
|
"title": "Edu-Space REST API",
|
||||||
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
"description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.",
|
||||||
"version": "3.4.4"
|
"version": "3.4.5"
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -8,6 +8,33 @@ from app.utils.jwt_decorators import jwt_required
|
|||||||
genetic_bp = Blueprint('genetic_algorithm', __name__, url_prefix='/api/genetic')
|
genetic_bp = Blueprint('genetic_algorithm', __name__, url_prefix='/api/genetic')
|
||||||
|
|
||||||
|
|
||||||
|
def check_optimizer_permission(user, requires_write=False):
|
||||||
|
"""
|
||||||
|
Verifica si el usuario tiene permiso para consultar o ejecutar el optimizador de reservas.
|
||||||
|
Permitido para Administradores, Bedelía, Docentes o usuarios con permisos RBAC en 'optimizer'.
|
||||||
|
"""
|
||||||
|
if not user:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# 1. Administrador (método o rol)
|
||||||
|
if hasattr(user, 'is_admin') and user.is_admin():
|
||||||
|
return True
|
||||||
|
|
||||||
|
role = (getattr(user, 'role', '') or '').strip().lower()
|
||||||
|
if role in ['admin', 'administrador', 'bedelia']:
|
||||||
|
return True
|
||||||
|
if role in ['docente', 'teacher']:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# 2. RBAC granular
|
||||||
|
if hasattr(user, 'has_permission'):
|
||||||
|
if requires_write:
|
||||||
|
return user.has_permission('optimizer', 'read_write')
|
||||||
|
return user.has_permission('optimizer', 'read') or user.has_permission('optimizer', 'read_write')
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
@genetic_bp.route('/optimize', methods=['POST'])
|
@genetic_bp.route('/optimize', methods=['POST'])
|
||||||
@jwt_required
|
@jwt_required
|
||||||
def optimize_reservations():
|
def optimize_reservations():
|
||||||
@@ -39,8 +66,8 @@ def optimize_reservations():
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
return jsonify({'error': 'Invalid end_date format. Use ISO format.'}), 400
|
return jsonify({'error': 'Invalid end_date format. Use ISO format.'}), 400
|
||||||
|
|
||||||
# Check if user has permission (admin, teacher or RBAC optimizer write)
|
# Check if user has permission (admin, bedelia, teacher or RBAC optimizer write)
|
||||||
if not (g.jwt_user.is_admin() or g.jwt_user.has_permission('optimizer', 'read_write') or g.jwt_user.role in ['ADMIN', 'teacher']):
|
if not check_optimizer_permission(g.jwt_user, requires_write=True):
|
||||||
return jsonify({'error': 'Insufficient permissions to optimize reservations'}), 403
|
return jsonify({'error': 'Insufficient permissions to optimize reservations'}), 403
|
||||||
|
|
||||||
# Initialize optimizer and run optimization
|
# Initialize optimizer and run optimization
|
||||||
@@ -84,7 +111,7 @@ def apply_optimization():
|
|||||||
return jsonify({'error': 'reservations must be a list'}), 400
|
return jsonify({'error': 'reservations must be a list'}), 400
|
||||||
|
|
||||||
# Check if user has permission
|
# Check if user has permission
|
||||||
if not (g.jwt_user.is_admin() or g.jwt_user.has_permission('optimizer', 'read_write') or g.jwt_user.role in ['ADMIN', 'teacher']):
|
if not check_optimizer_permission(g.jwt_user, requires_write=True):
|
||||||
return jsonify({'error': 'Insufficient permissions to apply reservations'}), 403
|
return jsonify({'error': 'Insufficient permissions to apply reservations'}), 403
|
||||||
|
|
||||||
# Initialize optimizer and apply reservations
|
# Initialize optimizer and apply reservations
|
||||||
@@ -124,7 +151,7 @@ def preview_optimization():
|
|||||||
return jsonify({'error': 'commission_ids must be a non-empty list'}), 400
|
return jsonify({'error': 'commission_ids must be a non-empty list'}), 400
|
||||||
|
|
||||||
# Check if user has permission
|
# Check if user has permission
|
||||||
if g.jwt_user.role not in ['ADMIN', 'teacher']:
|
if not check_optimizer_permission(g.jwt_user, requires_write=False):
|
||||||
return jsonify({'error': 'Insufficient permissions to preview optimization'}), 403
|
return jsonify({'error': 'Insufficient permissions to preview optimization'}), 403
|
||||||
|
|
||||||
# Initialize optimizer and run optimization
|
# Initialize optimizer and run optimization
|
||||||
@@ -171,7 +198,7 @@ def get_commissions():
|
|||||||
"""Get available commissions for optimization"""
|
"""Get available commissions for optimization"""
|
||||||
try:
|
try:
|
||||||
# Check if user has permission
|
# Check if user has permission
|
||||||
if g.jwt_user.role not in ['ADMIN', 'teacher']:
|
if not check_optimizer_permission(g.jwt_user, requires_write=False):
|
||||||
return jsonify({'error': 'Insufficient permissions'}), 403
|
return jsonify({'error': 'Insufficient permissions'}), 403
|
||||||
|
|
||||||
from app.models.subject import Commission, Subject
|
from app.models.subject import Commission, Subject
|
||||||
@@ -183,6 +210,8 @@ def get_commissions():
|
|||||||
for commission in commissions:
|
for commission in commissions:
|
||||||
commission_dict = commission.to_dict()
|
commission_dict = commission.to_dict()
|
||||||
commission_dict['get_full_code'] = commission.get_full_code()
|
commission_dict['get_full_code'] = commission.get_full_code()
|
||||||
|
commission_dict['subject_name'] = commission.subject.name if commission.subject else 'Sin Asignatura'
|
||||||
|
commission_dict['subject_code'] = commission.subject.code if commission.subject else ''
|
||||||
commissions_data.append(commission_dict)
|
commissions_data.append(commission_dict)
|
||||||
|
|
||||||
return jsonify({
|
return jsonify({
|
||||||
@@ -201,7 +230,7 @@ def get_algorithm_status():
|
|||||||
"""Get genetic algorithm configuration status"""
|
"""Get genetic algorithm configuration status"""
|
||||||
try:
|
try:
|
||||||
# Check if user has permission
|
# Check if user has permission
|
||||||
if g.jwt_user.role not in ['ADMIN']:
|
if not check_optimizer_permission(g.jwt_user, requires_write=False):
|
||||||
return jsonify({'error': 'Insufficient permissions'}), 403
|
return jsonify({'error': 'Insufficient permissions'}), 403
|
||||||
|
|
||||||
# Get system status
|
# Get system status
|
||||||
@@ -249,7 +278,7 @@ genetic_web_bp = Blueprint('genetic_algorithm_web', __name__)
|
|||||||
@jwt_required
|
@jwt_required
|
||||||
def genetic_optimizer():
|
def genetic_optimizer():
|
||||||
"""Render the genetic algorithm optimizer interface"""
|
"""Render the genetic algorithm optimizer interface"""
|
||||||
if not (g.jwt_user.has_permission('optimizer', 'read') or (g.jwt_user.role and g.jwt_user.role.upper() == 'ADMIN')):
|
if not check_optimizer_permission(g.jwt_user, requires_write=False):
|
||||||
return render_template('auth/403.html'), 403
|
return render_template('auth/403.html'), 403
|
||||||
|
|
||||||
return render_template('genetic_optimizer.html')
|
return render_template('genetic_optimizer.html')
|
||||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="edu-space-admin",
|
name="edu-space-admin",
|
||||||
version="3.4.4",
|
version="3.4.5",
|
||||||
description="Administrative interface for Edu-Space Classroom Management System",
|
description="Administrative interface for Edu-Space Classroom Management System",
|
||||||
author="Edu-Space Development Team",
|
author="Edu-Space Development Team",
|
||||||
author_email="admin@edu-space.com",
|
author_email="admin@edu-space.com",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "3.4.4",
|
"version": "3.4.5",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -143,7 +143,7 @@ class GeneticAlgorithmManager {
|
|||||||
const commissionIds = this.getSelectedCommissionIds();
|
const commissionIds = this.getSelectedCommissionIds();
|
||||||
|
|
||||||
if (commissionIds.length === 0) {
|
if (commissionIds.length === 0) {
|
||||||
this.showAlert('Please select at least one commission to optimize.', 'warning');
|
this.showAlert('Por favor seleccione al menos una comisión para optimizar.', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -153,12 +153,12 @@ class GeneticAlgorithmManager {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
this.displayOptimizationResults(result.data);
|
this.displayOptimizationResults(result.data);
|
||||||
this.showAlert('Optimization completed successfully!', 'success');
|
this.showAlert('¡Optimización de reservas completada con éxito!', 'success');
|
||||||
} else {
|
} else {
|
||||||
this.showAlert('Optimization failed: ' + (result.error || 'Unknown error'), 'danger');
|
this.showAlert('Fallo en la optimización: ' + (result.error || 'Error desconocido'), 'danger');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showAlert('Error during optimization: ' + error.message, 'danger');
|
this.showAlert('Error durante la optimización: ' + error.message, 'danger');
|
||||||
} finally {
|
} finally {
|
||||||
this.showLoading(false);
|
this.showLoading(false);
|
||||||
}
|
}
|
||||||
@@ -169,7 +169,7 @@ class GeneticAlgorithmManager {
|
|||||||
const commissionIds = this.getSelectedCommissionIds();
|
const commissionIds = this.getSelectedCommissionIds();
|
||||||
|
|
||||||
if (commissionIds.length === 0) {
|
if (commissionIds.length === 0) {
|
||||||
this.showAlert('Please select at least one commission to preview.', 'warning');
|
this.showAlert('Por favor seleccione al menos una comisión para previsualizar.', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,12 +179,12 @@ class GeneticAlgorithmManager {
|
|||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
this.displayPreviewResults(result.data);
|
this.displayPreviewResults(result.data);
|
||||||
this.showAlert('Preview generated successfully!', 'success');
|
this.showAlert('¡Previsualización generada con éxito!', 'success');
|
||||||
} else {
|
} else {
|
||||||
this.showAlert('Preview failed: ' + (result.error || 'Unknown error'), 'danger');
|
this.showAlert('Fallo en la previsualización: ' + (result.error || 'Error desconocido'), 'danger');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showAlert('Error during preview: ' + error.message, 'danger');
|
this.showAlert('Error durante la previsualización: ' + error.message, 'danger');
|
||||||
} finally {
|
} finally {
|
||||||
this.showLoading(false);
|
this.showLoading(false);
|
||||||
}
|
}
|
||||||
@@ -195,11 +195,11 @@ class GeneticAlgorithmManager {
|
|||||||
const pendingReservations = this.getPendingReservations();
|
const pendingReservations = this.getPendingReservations();
|
||||||
|
|
||||||
if (!pendingReservations || pendingReservations.length === 0) {
|
if (!pendingReservations || pendingReservations.length === 0) {
|
||||||
this.showAlert('No pending reservations to apply.', 'warning');
|
this.showAlert('No hay reservas optimizadas pendientes de aplicar.', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!confirm('Are you sure you want to apply these reservations? This will create actual reservation records.')) {
|
if (!confirm('¿Está seguro de que desea aplicar estas asignaciones optimizadas? Se crearán las reservas definitivas en el sistema.')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -208,15 +208,15 @@ class GeneticAlgorithmManager {
|
|||||||
const result = await this.applyOptimization(pendingReservations);
|
const result = await this.applyOptimization(pendingReservations);
|
||||||
|
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
this.showAlert(`Successfully applied ${result.data.applied_count} reservations!`, 'success');
|
this.showAlert(`¡Se aplicaron con éxito ${result.data.applied_count} reservas en Bedelía!`, 'success');
|
||||||
this.clearPendingReservations();
|
this.clearPendingReservations();
|
||||||
// Redirect to reservations page
|
// Redirigir al listado de reservas
|
||||||
window.location.href = '/schedule';
|
window.location.href = '/schedule/list_reservations';
|
||||||
} else {
|
} else {
|
||||||
this.showAlert('Failed to apply reservations: ' + (result.error || 'Unknown error'), 'danger');
|
this.showAlert('Fallo al aplicar reservas: ' + (result.error || 'Error desconocido'), 'danger');
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.showAlert('Error applying reservations: ' + error.message, 'danger');
|
this.showAlert('Error al aplicar reservas: ' + error.message, 'danger');
|
||||||
} finally {
|
} finally {
|
||||||
this.showLoading(false);
|
this.showLoading(false);
|
||||||
}
|
}
|
||||||
@@ -252,47 +252,53 @@ class GeneticAlgorithmManager {
|
|||||||
const scorePercentage = (data.fitness_score * 100).toFixed(1);
|
const scorePercentage = (data.fitness_score * 100).toFixed(1);
|
||||||
|
|
||||||
resultsContainer.innerHTML = `
|
resultsContainer.innerHTML = `
|
||||||
<div class="card">
|
<div class="card border-0 shadow-sm mb-4">
|
||||||
<div class="card-header bg-success text-white">
|
<div class="card-header bg-success text-white py-3">
|
||||||
<h5 class="mb-0">Optimization Results</h5>
|
<h5 class="mb-0 h6 fw-bold"><i class="bi bi-check-circle-fill me-2"></i>Resultados de la Optimización</h5>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body p-4">
|
||||||
<div class="row mb-3">
|
<div class="row g-3 mb-4 text-center">
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="text-center">
|
<div class="p-3 rounded bg-primary bg-opacity-10 border border-primary-subtle">
|
||||||
<h4 class="text-primary">${data.assigned_reservations}</h4>
|
<h3 class="fw-bold text-primary mb-1">${data.assigned_reservations}</h3>
|
||||||
<p class="mb-0">Reservations Assigned</p>
|
<p class="mb-0 text-muted small fw-semibold">Reservas Asignadas</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="text-center">
|
<div class="p-3 rounded bg-info bg-opacity-10 border border-info-subtle">
|
||||||
<h4 class="text-info">${scorePercentage}%</h4>
|
<h3 class="fw-bold text-info mb-1">${scorePercentage}%</h3>
|
||||||
<p class="mb-0">Fitness Score</p>
|
<p class="mb-0 text-muted small fw-semibold">Puntaje de Aptitud (Fitness)</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-4">
|
<div class="col-md-4">
|
||||||
<div class="text-center">
|
<div class="p-3 rounded bg-warning bg-opacity-10 border border-warning-subtle">
|
||||||
<h4 class="text-warning">${data.total_requests}</h4>
|
<h3 class="fw-bold text-warning mb-1">${data.total_requests}</h3>
|
||||||
<p class="mb-0">Total Requests</p>
|
<p class="mb-0 text-muted small fw-semibold">Total de Solicitudes</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
${data.conflicts.length > 0 ? `
|
${data.conflicts.length > 0 ? `
|
||||||
<div class="alert alert-warning">
|
<div class="alert alert-warning d-flex align-items-center">
|
||||||
<strong>Warning:</strong> ${data.conflicts.length} potential conflicts detected.
|
<i class="bi bi-exclamation-triangle-fill fs-5 me-2"></i>
|
||||||
|
<div><strong>Atención:</strong> Se detectaron ${data.conflicts.length} conflictos potenciales no resueltos.</div>
|
||||||
</div>
|
</div>
|
||||||
` : ''}
|
` : `
|
||||||
|
<div class="alert alert-success d-flex align-items-center">
|
||||||
|
<i class="bi bi-check-circle-fill fs-5 me-2"></i>
|
||||||
|
<div><strong>Excelente:</strong> ¡0 conflictos detectados! Todas las asignaciones cumplen aforo y disponibilidad.</div>
|
||||||
|
</div>
|
||||||
|
`}
|
||||||
|
|
||||||
<div class="d-flex gap-2">
|
<div class="d-flex gap-2 flex-wrap">
|
||||||
<button class="btn btn-primary" onclick="geneticManager.viewReservationDetails()">
|
<button class="btn btn-outline-primary" onclick="geneticManager.viewReservationDetails()">
|
||||||
View Details
|
<i class="bi bi-eye me-1"></i>Ver Detalle de Reservas
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-success" onclick="geneticManager.handleApplyOptimization()">
|
<button class="btn btn-success fw-bold px-4" onclick="geneticManager.handleApplyOptimization()">
|
||||||
Apply Reservations
|
<i class="bi bi-check-circle me-1"></i>Aplicar Reservas en Bedelía
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-secondary" onclick="geneticManager.clearResults()">
|
<button class="btn btn-outline-secondary" onclick="geneticManager.clearResults()">
|
||||||
Clear
|
<i class="bi bi-trash me-1"></i>Limpiar
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -306,30 +312,30 @@ class GeneticAlgorithmManager {
|
|||||||
|
|
||||||
const commissionsHtml = data.commission_details.map(commission => `
|
const commissionsHtml = data.commission_details.map(commission => `
|
||||||
<tr>
|
<tr>
|
||||||
<td>${commission.code}</td>
|
<td class="font-monospace fw-bold text-primary">${commission.code}</td>
|
||||||
<td>${commission.name}</td>
|
<td>${commission.name}</td>
|
||||||
<td>${commission.current_students}/${commission.max_students}</td>
|
<td><span class="badge bg-secondary">${commission.current_students || 0}/${commission.max_students}</span></td>
|
||||||
</tr>
|
</tr>
|
||||||
`).join('');
|
`).join('');
|
||||||
|
|
||||||
const optimization = data.optimization_result;
|
const optimization = data.optimization_result;
|
||||||
|
|
||||||
previewContainer.innerHTML = `
|
previewContainer.innerHTML = `
|
||||||
<div class="card">
|
<div class="card border-0 shadow-sm mb-4">
|
||||||
<div class="card-header bg-info text-white">
|
<div class="card-header bg-info text-white py-3">
|
||||||
<h5 class="mb-0">Optimization Preview</h5>
|
<h5 class="mb-0 h6 fw-bold"><i class="bi bi-eye-fill me-2"></i>Previsualización de la Optimización</h5>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
<div class="card-body p-4">
|
||||||
<div class="row mb-4">
|
<div class="row g-4 mb-4">
|
||||||
<div class="col-md-6">
|
<div class="col-md-7">
|
||||||
<h6>Commissions to Optimize</h6>
|
<h6 class="fw-bold text-muted text-uppercase small mb-2">Comisiones a Optimizar</h6>
|
||||||
<div class="table-responsive">
|
<div class="table-responsive border rounded">
|
||||||
<table class="table table-sm">
|
<table class="table table-hover table-sm mb-0">
|
||||||
<thead>
|
<thead class="table-light">
|
||||||
<tr>
|
<tr>
|
||||||
<th>Code</th>
|
<th>Código</th>
|
||||||
<th>Name</th>
|
<th>Asignatura</th>
|
||||||
<th>Students</th>
|
<th>Estudiantes</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
@@ -338,20 +344,20 @@ class GeneticAlgorithmManager {
|
|||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-md-6">
|
<div class="col-md-5">
|
||||||
<h6>Expected Results</h6>
|
<h6 class="fw-bold text-muted text-uppercase small mb-2">Resultados Estimados</h6>
|
||||||
<ul class="list-group">
|
<ul class="list-group shadow-sm">
|
||||||
<li class="list-group-item d-flex justify-content-between">
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
||||||
<span>Reservations Created:</span>
|
<span>Reservas Creadas:</span>
|
||||||
<strong>${optimization.assigned_reservations}</strong>
|
<strong class="text-primary font-monospace fs-6">${optimization.assigned_reservations}</strong>
|
||||||
</li>
|
</li>
|
||||||
<li class="list-group-item d-flex justify-content-between">
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
||||||
<span>Fitness Score:</span>
|
<span>Puntaje de Aptitud:</span>
|
||||||
<strong>${(optimization.fitness_score * 100).toFixed(1)}%</strong>
|
<strong class="text-info font-monospace fs-6">${(optimization.fitness_score * 100).toFixed(1)}%</strong>
|
||||||
</li>
|
</li>
|
||||||
<li class="list-group-item d-flex justify-content-between">
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
||||||
<span>Conflicts:</span>
|
<span>Conflictos:</span>
|
||||||
<strong class="${optimization.conflicts.length > 0 ? 'text-danger' : 'text-success'}">
|
<strong class="font-monospace fs-6 ${optimization.conflicts.length > 0 ? 'text-danger' : 'text-success'}">
|
||||||
${optimization.conflicts.length}
|
${optimization.conflicts.length}
|
||||||
</strong>
|
</strong>
|
||||||
</li>
|
</li>
|
||||||
@@ -361,10 +367,10 @@ class GeneticAlgorithmManager {
|
|||||||
|
|
||||||
<div class="d-flex gap-2">
|
<div class="d-flex gap-2">
|
||||||
<button class="btn btn-primary" onclick="geneticManager.handleOptimizeReservations()">
|
<button class="btn btn-primary" onclick="geneticManager.handleOptimizeReservations()">
|
||||||
Run Full Optimization
|
<i class="bi bi-play-circle me-1"></i>Ejecutar Optimización Completa
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-secondary" onclick="geneticManager.clearPreview()">
|
<button class="btn btn-outline-secondary" onclick="geneticManager.clearPreview()">
|
||||||
Close Preview
|
<i class="bi bi-x-circle me-1"></i>Cerrar Previsualización
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -375,7 +381,7 @@ class GeneticAlgorithmManager {
|
|||||||
viewReservationDetails() {
|
viewReservationDetails() {
|
||||||
const reservations = this.getPendingReservations();
|
const reservations = this.getPendingReservations();
|
||||||
if (!reservations || reservations.length === 0) {
|
if (!reservations || reservations.length === 0) {
|
||||||
this.showAlert('No reservation details available.', 'info');
|
this.showAlert('No hay detalles de reserva disponibles.', 'info');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,11 +389,11 @@ class GeneticAlgorithmManager {
|
|||||||
const detailsHtml = reservations.map((res, index) => `
|
const detailsHtml = reservations.map((res, index) => `
|
||||||
<tr>
|
<tr>
|
||||||
<td>${index + 1}</td>
|
<td>${index + 1}</td>
|
||||||
<td>${res.purpose}</td>
|
<td>${res.purpose || 'Cursada Académica'}</td>
|
||||||
<td>Classroom ${res.classroom_id}</td>
|
<td><span class="badge bg-primary">Aula ID ${res.classroom_id}</span></td>
|
||||||
<td>${new Date(res.start_time).toLocaleString()}</td>
|
<td class="small font-monospace">${new Date(res.start_time).toLocaleString('es-AR')}</td>
|
||||||
<td>${new Date(res.end_time).toLocaleString()}</td>
|
<td class="small font-monospace">${new Date(res.end_time).toLocaleString('es-AR')}</td>
|
||||||
<td>${res.expected_attendees}</td>
|
<td><span class="badge bg-secondary">${res.expected_attendees || 0}</span></td>
|
||||||
</tr>
|
</tr>
|
||||||
`).join('');
|
`).join('');
|
||||||
|
|
||||||
@@ -395,15 +401,15 @@ class GeneticAlgorithmManager {
|
|||||||
if (modal) {
|
if (modal) {
|
||||||
modal.querySelector('.modal-body').innerHTML = `
|
modal.querySelector('.modal-body').innerHTML = `
|
||||||
<div class="table-responsive">
|
<div class="table-responsive">
|
||||||
<table class="table">
|
<table class="table table-hover table-sm">
|
||||||
<thead>
|
<thead class="table-light">
|
||||||
<tr>
|
<tr>
|
||||||
<th>#</th>
|
<th>#</th>
|
||||||
<th>Purpose</th>
|
<th>Propósito</th>
|
||||||
<th>Classroom</th>
|
<th>Aula Asignada</th>
|
||||||
<th>Start Time</th>
|
<th>Inicio</th>
|
||||||
<th>End Time</th>
|
<th>Fin</th>
|
||||||
<th>Attendees</th>
|
<th>Asistentes</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
|
|||||||
+13
-7
@@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Versiones institucionales del sistema
|
// Versiones institucionales del sistema
|
||||||
const APP_VERSION = '3.4.4';
|
const APP_VERSION = '3.4.5';
|
||||||
const FRONTEND_VERSION = '3.4.4';
|
const FRONTEND_VERSION = '3.4.5';
|
||||||
const BACKEND_VERSION = '3.4.4';
|
const BACKEND_VERSION = '3.4.5';
|
||||||
|
|
||||||
env.addGlobal('app_version', APP_VERSION);
|
env.addGlobal('app_version', APP_VERSION);
|
||||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||||
@@ -352,16 +352,22 @@ app.get(['/main/dashboard', '/main'], (req, res) => {
|
|||||||
res.redirect('/dashboard' + query);
|
res.redirect('/dashboard' + query);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const { requireAuth } = require('./middlewares/authMiddleware');
|
||||||
|
|
||||||
// Módulo Predictivo y Optimizador
|
// Módulo Predictivo y Optimizador
|
||||||
app.get('/predictive', (req, res) => {
|
app.get('/predictive', requireAuth, (req, res) => {
|
||||||
res.render('predictive/index', {
|
res.render('predictive/index', {
|
||||||
title: 'Dashboard Predictivo - Edu-Space Admin'
|
title: 'Dashboard Predictivo - Edu-Space Admin',
|
||||||
|
user: req.user,
|
||||||
|
user_role: (req.user?.role || 'admin').toLowerCase()
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
app.get(['/genetic_optimizer', '/genetic_algorithm_web/genetic_optimizer'], (req, res) => {
|
app.get(['/genetic_optimizer', '/genetic_algorithm_web/genetic_optimizer'], requireAuth, (req, res) => {
|
||||||
res.render('genetic_optimizer', {
|
res.render('genetic_optimizer', {
|
||||||
title: 'Optimizador de Aulas (IA) - Edu-Space Admin'
|
title: 'Optimizador de Aulas (IA) - Edu-Space Admin',
|
||||||
|
user: req.user,
|
||||||
|
user_role: (req.user?.role || 'admin').toLowerCase()
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
|
|
||||||
{% block title %}AI Room Reservation Optimizer - Edu-Space Admin{% endblock %}
|
{% block title %}Optimizador de Aulas (IA) - Edu-Space Admin{% endblock %}
|
||||||
|
|
||||||
{% block extra_css %}
|
{% block extra_css %}
|
||||||
<style>
|
<style>
|
||||||
@@ -39,7 +39,8 @@
|
|||||||
left: 0;
|
left: 0;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background-color: rgba(0, 0, 0, 0.7);
|
background-color: rgba(0, 0, 0, 0.75);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
display: none;
|
display: none;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
@@ -47,8 +48,8 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.hero-banner {
|
.hero-banner {
|
||||||
background: linear-gradient(135deg, rgba(37, 99, 235, 0.2) 0%, rgba(30, 41, 59, 0.9) 100%);
|
background: linear-gradient(135deg, rgba(37, 99, 235, 0.15) 0%, rgba(30, 41, 59, 0.85) 100%);
|
||||||
border: 1px solid rgba(255, 255, 255, 0.1);
|
border: 1px solid rgba(255, 255, 255, 0.12);
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
@@ -56,21 +57,21 @@
|
|||||||
|
|
||||||
{% block content %}
|
{% block content %}
|
||||||
<div class="container-fluid pt-5 mt-4">
|
<div class="container-fluid pt-5 mt-4">
|
||||||
<!-- Header -->
|
<!-- Hero Header -->
|
||||||
<div class="row mb-4">
|
<div class="row mb-4">
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
<div class="card hero-banner border-0 shadow-sm p-3">
|
<div class="card hero-banner border-0 shadow-sm p-3">
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
<div class="d-flex align-items-center mb-2">
|
<div class="d-flex align-items-center mb-2 flex-wrap gap-3">
|
||||||
<div class="bg-primary bg-opacity-25 rounded-3 p-3 me-3 text-primary">
|
<div class="bg-primary bg-opacity-25 rounded-3 p-3 text-primary">
|
||||||
<i class="bi bi-cpu fs-2"></i>
|
<i class="bi bi-cpu fs-1"></i>
|
||||||
</div>
|
</div>
|
||||||
<div>
|
<div>
|
||||||
<h1 class="h3 mb-1 fw-bold">
|
<h1 class="h3 mb-1 fw-bold">
|
||||||
AI Room Reservation Optimizer
|
Optimizador Inteligente de Asignación de Aulas (IA)
|
||||||
</h1>
|
</h1>
|
||||||
<p class="text-muted mb-0">
|
<p class="text-muted mb-0">
|
||||||
Use genetic algorithms to automatically optimize room assignments based on capacity, availability, and student enrollment.
|
Utiliza algoritmos genéticos evolutivos para optimizar la asignación física de espacios áulicos según aforo, turnos y disponibilidad horaria de UniCABA.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -81,126 +82,140 @@
|
|||||||
|
|
||||||
<!-- Algorithm Status & Commission Selection -->
|
<!-- Algorithm Status & Commission Selection -->
|
||||||
<div class="row mb-4">
|
<div class="row mb-4">
|
||||||
<!-- Algorithm Status Card -->
|
<!-- Columna Izquierda: Estado del Algoritmo y Controles -->
|
||||||
<div class="col-lg-4 mb-4">
|
<div class="col-lg-4 mb-4">
|
||||||
<div class="algorithm-status" style="z-index: 10;">
|
<div class="algorithm-status" style="z-index: 10;">
|
||||||
|
<!-- Tarjeta 1: Estado del Sistema -->
|
||||||
<div class="card border-0 shadow-sm mb-4">
|
<div class="card border-0 shadow-sm mb-4">
|
||||||
<div class="card-header bg-body-tertiary border-0 py-3">
|
<div class="card-header bg-body-tertiary border-0 py-3">
|
||||||
<h5 class="mb-0 h6 fw-bold">
|
<h5 class="mb-0 h6 fw-bold">
|
||||||
<i class="bi bi-gear-wide-connected text-primary me-2"></i>
|
<i class="bi bi-gear-wide-connected text-primary me-2"></i>
|
||||||
Algorithm Status
|
Estado del Algoritmo
|
||||||
</h5>
|
</h5>
|
||||||
</div>
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="mb-4">
|
|
||||||
<small class="text-muted text-uppercase fw-semibold d-block mb-2">System Status</small>
|
|
||||||
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary">
|
|
||||||
<span>Available Classrooms</span>
|
|
||||||
<span class="badge bg-success" id="available-classrooms">--</span>
|
|
||||||
</div>
|
|
||||||
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary">
|
|
||||||
<span>Active Commissions</span>
|
|
||||||
<span class="badge bg-info" id="active-commissions">--</span>
|
|
||||||
</div>
|
|
||||||
<div class="d-flex justify-content-between align-items-center py-1">
|
|
||||||
<span>Existing Reservations</span>
|
|
||||||
<span class="badge bg-secondary" id="existing-reservations">--</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
<div class="mb-4">
|
<div class="mb-3">
|
||||||
<small class="text-muted text-uppercase fw-semibold d-block mb-2">Algorithm Configuration</small>
|
<small class="text-muted text-uppercase fw-semibold d-block mb-2">Métricas del Sistema</small>
|
||||||
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary">
|
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-body-secondary">
|
||||||
<span>Population Size</span>
|
<span class="small fw-semibold"><i class="bi bi-door-open text-success me-1"></i>Aulas Disponibles</span>
|
||||||
<span class="text-muted">50</span>
|
<span class="badge bg-success font-monospace fs-6" id="available-classrooms">--</span>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center py-2 border-bottom border-body-secondary">
|
||||||
|
<span class="small fw-semibold"><i class="bi bi-diagram-3 text-info me-1"></i>Comisiones Activas</span>
|
||||||
|
<span class="badge bg-info font-monospace fs-6" id="active-commissions">--</span>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center py-2">
|
||||||
|
<span class="small fw-semibold"><i class="bi bi-calendar-check text-secondary me-1"></i>Reservas Confirmadas</span>
|
||||||
|
<span class="badge bg-secondary font-monospace fs-6" id="existing-reservations">--</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary">
|
|
||||||
<span>Generations</span>
|
<div class="mb-3">
|
||||||
<span class="text-muted">100</span>
|
<small class="text-muted text-uppercase fw-semibold d-block mb-2">Parámetros Evolutivos</small>
|
||||||
</div>
|
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary small">
|
||||||
<div class="d-flex justify-content-between align-items-center py-1">
|
<span>Tamaño de Población</span>
|
||||||
<span>Mutation Rate</span>
|
<span class="font-monospace fw-bold">50 individuos</span>
|
||||||
<span class="text-muted">10%</span>
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center py-1 border-bottom border-body-secondary small">
|
||||||
|
<span>Generaciones</span>
|
||||||
|
<span class="font-monospace fw-bold">100 iteraciones</span>
|
||||||
|
</div>
|
||||||
|
<div class="d-flex justify-content-between align-items-center py-1 small">
|
||||||
|
<span>Tasa de Mutación</span>
|
||||||
|
<span class="font-monospace fw-bold">10%</span>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<button class="btn btn-sm btn-outline-primary w-100" onclick="window.refreshStatus()">
|
||||||
|
<i class="bi bi-arrow-clockwise me-1"></i>
|
||||||
|
Actualizar Estado
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<button class="btn btn-sm btn-outline-primary w-100" onclick="window.refreshStatus()">
|
|
||||||
<i class="bi bi-arrow-clockwise me-1"></i>
|
|
||||||
Refresh Status
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Optimization Controls -->
|
<!-- Tarjeta 2: Controles de Optimización -->
|
||||||
<div class="card border-0 shadow-sm">
|
<div class="card border-0 shadow-sm">
|
||||||
<div class="card-header bg-body-tertiary border-0 py-3">
|
<div class="card-header bg-body-tertiary border-0 py-3">
|
||||||
<h5 class="mb-0 h6 fw-bold">
|
<h5 class="mb-0 h6 fw-bold">
|
||||||
<i class="bi bi-sliders text-primary me-2"></i>
|
<i class="bi bi-sliders text-primary me-2"></i>
|
||||||
Optimization Controls
|
Controles de Optimización
|
||||||
</h5>
|
</h5>
|
||||||
</div>
|
|
||||||
<div class="card-body">
|
|
||||||
<div class="row align-items-center mb-3">
|
|
||||||
<div class="col-12">
|
|
||||||
<div class="mb-3">
|
|
||||||
<label for="start-date" class="form-label">Start Date</label>
|
|
||||||
<input type="datetime-local" class="form-control" id="start-date" name="start_date">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div class="col-12">
|
|
||||||
<div class="mb-3">
|
|
||||||
<label for="end-date" class="form-label">End Date</label>
|
|
||||||
<input type="datetime-local" class="form-control" id="end-date" name="end_date">
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
<div class="d-grid gap-2">
|
<div class="row align-items-center mb-3">
|
||||||
<button class="btn btn-info text-white" id="preview-optimization-btn">
|
<div class="col-12">
|
||||||
<i class="bi bi-eye me-1"></i>
|
<div class="mb-2">
|
||||||
Preview
|
<label for="start-date" class="form-label small fw-semibold">Fecha y Hora de Inicio</label>
|
||||||
</button>
|
<input type="datetime-local" class="form-control form-control-sm" id="start-date" name="start_date">
|
||||||
<button class="btn btn-success" id="optimize-assignments-btn">
|
</div>
|
||||||
<i class="bi bi-play-circle me-1"></i>
|
</div>
|
||||||
Run Full Optimization
|
<div class="col-12">
|
||||||
</button>
|
<div class="mb-2">
|
||||||
<button class="btn btn-warning" id="apply-optimization-btn" style="display: none;">
|
<label for="end-date" class="form-label small fw-semibold">Fecha y Hora de Fin</label>
|
||||||
<i class="bi bi-check-circle me-1"></i>
|
<input type="datetime-local" class="form-control form-control-sm" id="end-date" name="end_date">
|
||||||
Apply
|
</div>
|
||||||
</button>
|
</div>
|
||||||
<button class="btn btn-outline-secondary" onclick="resetOptimization()">
|
</div>
|
||||||
<i class="bi bi-arrow-counterclockwise me-1"></i>
|
|
||||||
Reset
|
<div class="d-grid gap-2">
|
||||||
</button>
|
<button class="btn btn-info text-white fw-semibold" id="preview-optimization-btn">
|
||||||
|
<i class="bi bi-eye me-1"></i>
|
||||||
|
Previsualizar Asignación
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-success fw-semibold" id="optimize-assignments-btn">
|
||||||
|
<i class="bi bi-play-circle me-1"></i>
|
||||||
|
Ejecutar Optimización Completa
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-warning fw-bold" id="apply-optimization-btn" style="display: none;">
|
||||||
|
<i class="bi bi-check-circle me-1"></i>
|
||||||
|
Aplicar Asignaciones
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-outline-secondary btn-sm" onclick="resetOptimization()">
|
||||||
|
<i class="bi bi-arrow-counterclockwise me-1"></i>
|
||||||
|
Restablecer Selección
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Commission Selection -->
|
<!-- Columna Derecha: Selección de Comisiones -->
|
||||||
<div class="col-lg-8">
|
<div class="col-lg-8">
|
||||||
<div class="card border-0 shadow-sm">
|
<div class="card border-0 shadow-sm">
|
||||||
<div class="card-header bg-body-tertiary border-0 py-3 d-flex justify-content-between align-items-center">
|
<div class="card-header bg-body-tertiary border-0 py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
|
||||||
<h5 class="mb-0 h6 fw-bold">
|
<div>
|
||||||
<i class="bi bi-list-check text-primary me-2"></i>
|
<h5 class="mb-0 h6 fw-bold">
|
||||||
Select Commissions to Optimize
|
<i class="bi bi-list-check text-primary me-2"></i>
|
||||||
</h5>
|
Seleccionar Comisiones a Optimizar
|
||||||
|
</h5>
|
||||||
|
<small class="text-muted" id="commissions-count-badge">Cargando comisiones de cursada...</small>
|
||||||
|
</div>
|
||||||
<div class="d-flex gap-2">
|
<div class="d-flex gap-2">
|
||||||
<button class="btn btn-sm btn-outline-primary" onclick="selectAllCommissions()">
|
<button class="btn btn-sm btn-outline-primary" onclick="selectAllCommissions()">
|
||||||
Select All
|
<i class="bi bi-check-all me-1"></i>Seleccionar Todas
|
||||||
</button>
|
</button>
|
||||||
<button class="btn btn-sm btn-outline-secondary" onclick="deselectAllCommissions()">
|
<button class="btn btn-sm btn-outline-secondary" onclick="deselectAllCommissions()">
|
||||||
Deselect All
|
<i class="bi bi-dash me-1"></i>Deseleccionar
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="card-body">
|
|
||||||
<div id="commissions-list" class="row">
|
<!-- Buscador rápido en vivo -->
|
||||||
<!-- Commissions will be loaded here -->
|
<div class="card-body border-bottom bg-body-tertiary py-2">
|
||||||
|
<div class="input-group input-group-sm">
|
||||||
|
<span class="input-group-text bg-body border-end-0"><i class="bi bi-search text-muted"></i></span>
|
||||||
|
<input type="text" class="form-control border-start-0" id="comm-search-input"
|
||||||
|
placeholder="Filtrar por código, asignatura, carrera o turno..." oninput="filterCommissions(this.value)">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card-body p-3">
|
||||||
|
<div id="commissions-list" class="row g-3">
|
||||||
|
<!-- Las comisiones se cargan aquí dinámicamente -->
|
||||||
<div class="col-12 text-center text-muted py-5">
|
<div class="col-12 text-center text-muted py-5">
|
||||||
<div class="spinner-border spinner-border-sm me-2 text-primary" role="status"></div>
|
<div class="spinner-border spinner-border-sm me-2 text-primary" role="status"></div>
|
||||||
Loading commissions...
|
Cargando comisiones activas...
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -208,9 +223,7 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- Resultados Section -->
|
||||||
|
|
||||||
<!-- Results Section -->
|
|
||||||
<div class="row mb-4">
|
<div class="row mb-4">
|
||||||
<div class="col-12">
|
<div class="col-12">
|
||||||
<div id="preview-results"></div>
|
<div id="preview-results"></div>
|
||||||
@@ -223,29 +236,25 @@
|
|||||||
<!-- Loading Spinner Overlay -->
|
<!-- Loading Spinner Overlay -->
|
||||||
<div class="spinner-overlay" id="loading-spinner">
|
<div class="spinner-overlay" id="loading-spinner">
|
||||||
<div class="text-center text-white">
|
<div class="text-center text-white">
|
||||||
<div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status"></div>
|
<div class="spinner-border text-primary" style="width: 3.5rem; height: 3.5rem;" role="status"></div>
|
||||||
<p class="mt-3 mb-1 fw-bold fs-5">Running genetic algorithm optimization...</p>
|
<p class="mt-3 mb-1 fw-bold fs-5">Ejecutando algoritmo genético de optimización...</p>
|
||||||
<small class="text-white-50">This may take a few moments</small>
|
<small class="text-white-50">Calculando función de aptitud y evaluando combinaciones áulicas sin colisiones...</small>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Details Modal -->
|
<!-- Details Modal -->
|
||||||
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
|
<div class="modal fade" id="detailsModal" tabindex="-1" aria-labelledby="detailsModalLabel" aria-hidden="true">
|
||||||
<div class="modal-dialog modal-lg">
|
<div class="modal-dialog modal-lg modal-dialog-centered">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<div class="modal-header">
|
<div class="modal-header">
|
||||||
<h5 class="modal-title" id="detailsModalLabel">Reservation Details</h5>
|
<h5 class="modal-title fw-bold" id="detailsModalLabel"><i class="bi bi-calendar3 me-2 text-primary"></i>Detalle de Reservas Optimizadas</h5>
|
||||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-body">
|
<div class="modal-body">
|
||||||
<!-- Content populated dynamically -->
|
<!-- Contenido dinámico -->
|
||||||
</div>
|
</div>
|
||||||
<div class="modal-footer">
|
<div class="modal-footer">
|
||||||
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
|
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
|
||||||
<button type="button" class="btn btn-primary" onclick="downloadReservations()">
|
|
||||||
<i class="bi bi-download me-1"></i>
|
|
||||||
Download
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -255,11 +264,16 @@
|
|||||||
{% block extra_js %}
|
{% block extra_js %}
|
||||||
<script src="/js/genetic-algorithm.js"></script>
|
<script src="/js/genetic-algorithm.js"></script>
|
||||||
<script>
|
<script>
|
||||||
|
let allCommissionsData = [];
|
||||||
|
|
||||||
function selectAllCommissions() {
|
function selectAllCommissions() {
|
||||||
const checkboxes = document.querySelectorAll('input[name="commission_ids"]');
|
const checkboxes = document.querySelectorAll('input[name="commission_ids"]');
|
||||||
checkboxes.forEach(cb => {
|
checkboxes.forEach(cb => {
|
||||||
cb.checked = true;
|
const itemCol = cb.closest('.comm-card-col');
|
||||||
updateCommissionCard(cb.value, true);
|
if (!itemCol || itemCol.style.display !== 'none') {
|
||||||
|
cb.checked = true;
|
||||||
|
updateCommissionCard(cb.value, true);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -282,14 +296,35 @@ function updateCommissionCard(commissionId, selected) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function filterCommissions(query) {
|
||||||
|
const term = (query || '').toLowerCase().trim();
|
||||||
|
const cols = document.querySelectorAll('.comm-card-col');
|
||||||
|
let visibleCount = 0;
|
||||||
|
cols.forEach(col => {
|
||||||
|
const text = col.getAttribute('data-search-text') || '';
|
||||||
|
if (!term || text.includes(term)) {
|
||||||
|
col.style.display = '';
|
||||||
|
visibleCount++;
|
||||||
|
} else {
|
||||||
|
col.style.display = 'none';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const cntBadge = document.getElementById('commissions-count-badge');
|
||||||
|
if (cntBadge) {
|
||||||
|
cntBadge.textContent = `${visibleCount} comisiones encontradas`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function resetOptimization() {
|
function resetOptimization() {
|
||||||
deselectAllCommissions();
|
deselectAllCommissions();
|
||||||
if (window.geneticManager) {
|
if (window.geneticManager) {
|
||||||
geneticManager.clearResults && geneticManager.clearResults();
|
geneticManager.clearResults && geneticManager.clearResults();
|
||||||
geneticManager.clearPreview && geneticManager.clearPreview();
|
geneticManager.clearPreview && geneticManager.clearPreview();
|
||||||
}
|
}
|
||||||
document.getElementById('start-date').value = '';
|
const sInput = document.getElementById('start-date');
|
||||||
document.getElementById('end-date').value = '';
|
const eInput = document.getElementById('end-date');
|
||||||
|
if (sInput) sInput.value = '';
|
||||||
|
if (eInput) eInput.value = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
window.refreshStatus = async function() {
|
window.refreshStatus = async function() {
|
||||||
@@ -298,15 +333,18 @@ window.refreshStatus = async function() {
|
|||||||
const statusResult = await geneticManager.getAlgorithmStatus();
|
const statusResult = await geneticManager.getAlgorithmStatus();
|
||||||
if (statusResult && statusResult.success && statusResult.data) {
|
if (statusResult && statusResult.success && statusResult.data) {
|
||||||
const sysStats = statusResult.data.system_status;
|
const sysStats = statusResult.data.system_status;
|
||||||
document.getElementById('available-classrooms').textContent = sysStats.available_classrooms;
|
const acEl = document.getElementById('available-classrooms');
|
||||||
document.getElementById('active-commissions').textContent = sysStats.active_commissions;
|
const coEl = document.getElementById('active-commissions');
|
||||||
document.getElementById('existing-reservations').textContent = sysStats.confirmed_reservations;
|
const reEl = document.getElementById('existing-reservations');
|
||||||
|
if (acEl) acEl.textContent = sysStats.available_classrooms;
|
||||||
|
if (coEl) coEl.textContent = sysStats.active_commissions;
|
||||||
|
if (reEl) reEl.textContent = sysStats.confirmed_reservations;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Error refreshing status:", e);
|
console.error("Error al refrescar estado del algoritmo:", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', async function() {
|
document.addEventListener('DOMContentLoaded', async function() {
|
||||||
await loadCommissions();
|
await loadCommissions();
|
||||||
@@ -314,50 +352,83 @@ document.addEventListener('DOMContentLoaded', async function() {
|
|||||||
});
|
});
|
||||||
|
|
||||||
async function loadCommissions() {
|
async function loadCommissions() {
|
||||||
|
const commissionsList = document.getElementById('commissions-list');
|
||||||
|
const countBadge = document.getElementById('commissions-count-badge');
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/genetic/commissions');
|
const response = await fetch('/api/genetic/commissions');
|
||||||
|
if (!response.ok) {
|
||||||
|
const errJson = await response.json().catch(() => ({}));
|
||||||
|
throw new Error(errJson.error || errJson.message || `HTTP ${response.status}`);
|
||||||
|
}
|
||||||
|
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
const commissionsList = document.getElementById('commissions-list');
|
|
||||||
const isSpanish = '{{ session.language or "es" }}' === 'es';
|
|
||||||
|
|
||||||
if (data.success && data.commissions && data.commissions.length > 0) {
|
if (data.success && data.commissions && data.commissions.length > 0) {
|
||||||
const commissionsHtml = data.commissions.map(commission => `
|
allCommissionsData = data.commissions;
|
||||||
<div class="col-md-6 mb-3">
|
if (countBadge) {
|
||||||
<div class="card commission-item border-0 shadow-sm" data-commission-id="${commission.id}">
|
countBadge.textContent = `${data.commissions.length} comisiones activas disponibles para optimización`;
|
||||||
<div class="card-body">
|
}
|
||||||
<div class="form-check">
|
|
||||||
<input class="form-check-input" type="checkbox" name="commission_ids"
|
const commissionsHtml = data.commissions.map(commission => {
|
||||||
|
const fullCode = commission.get_full_code || commission.full_code || commission.code;
|
||||||
|
const subjName = commission.subject_name || commission.subject?.name || 'Asignatura no especificada';
|
||||||
|
const careerName = commission.career_name || commission.career_names || (commission.careers && commission.careers[0]?.name) || '';
|
||||||
|
const schedule = commission.schedule || 'Sin horario asignado';
|
||||||
|
const shift = commission.shift || 'General';
|
||||||
|
const teacher = commission.teacher_name || commission.teacher_names || '';
|
||||||
|
const students = `${commission.current_students || 0}/${commission.max_students || 0}`;
|
||||||
|
const searchText = `${fullCode} ${subjName} ${careerName} ${schedule} ${shift} ${teacher}`.toLowerCase();
|
||||||
|
|
||||||
|
return `
|
||||||
|
<div class="col-md-6 comm-card-col" data-search-text="${searchText}">
|
||||||
|
<div class="card commission-item border-0 shadow-sm h-100 p-2" data-commission-id="${commission.id}">
|
||||||
|
<div class="card-body p-2">
|
||||||
|
<div class="form-check d-flex align-items-start gap-2">
|
||||||
|
<input class="form-check-input mt-1 flex-shrink-0" type="checkbox" name="commission_ids"
|
||||||
value="${commission.id}" id="commission-${commission.id}"
|
value="${commission.id}" id="commission-${commission.id}"
|
||||||
onchange="updateCommissionCard('${commission.id}', this.checked)">
|
onchange="updateCommissionCard('${commission.id}', this.checked)">
|
||||||
<label class="form-check-label" for="commission-${commission.id}">
|
<label class="form-check-label w-100 cursor-pointer" for="commission-${commission.id}">
|
||||||
<strong class="text-primary">${commission.get_full_code || commission.code}</strong>
|
<div class="d-flex justify-content-between align-items-center mb-1">
|
||||||
<br>
|
<span class="badge bg-primary font-monospace fw-bold">${fullCode}</span>
|
||||||
<small class="text-muted">${commission.subject?.name || (isSpanish ? 'Materia Desconocida' : 'Unknown Subject')}</small>
|
<span class="badge bg-secondary-subtle text-secondary border small">${shift}</span>
|
||||||
<br>
|
</div>
|
||||||
<span class="badge bg-info mt-1">${commission.current_students || 0}/${commission.max_students} ${isSpanish ? 'estudiantes' : 'students'}</span>
|
<div class="fw-bold text-body mb-1" style="font-size: 0.95rem;">${subjName}</div>
|
||||||
${commission.teacher_name ? `<span class="badge bg-secondary ms-2">${commission.teacher_name}</span>` : ''}
|
${careerName ? `<div class="small text-muted mb-1"><i class="bi bi-mortarboard me-1"></i>${careerName}</div>` : ''}
|
||||||
|
<div class="d-flex justify-content-between align-items-center pt-2 mt-1 border-top small">
|
||||||
|
<span class="text-primary fw-semibold"><i class="bi bi-clock me-1"></i>${schedule}</span>
|
||||||
|
<span class="badge bg-info-subtle text-info border">${students} estudiantes</span>
|
||||||
|
</div>
|
||||||
|
${teacher ? `<div class="small text-muted mt-1"><i class="bi bi-person me-1"></i>${teacher}</div>` : ''}
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`).join('');
|
`;
|
||||||
|
}).join('');
|
||||||
|
|
||||||
commissionsList.innerHTML = commissionsHtml;
|
commissionsList.innerHTML = commissionsHtml;
|
||||||
} else {
|
} else {
|
||||||
|
if (countBadge) countBadge.textContent = '0 comisiones';
|
||||||
commissionsList.innerHTML = `
|
commissionsList.innerHTML = `
|
||||||
<div class="col-12 text-center text-muted py-5">
|
<div class="col-12 text-center text-muted py-5">
|
||||||
<i class="bi bi-inbox fs-1 d-block mb-2"></i>
|
<i class="bi bi-inbox fs-1 d-block mb-2 text-secondary"></i>
|
||||||
${isSpanish ? 'No se encontraron comisiones activas.' : 'No active commissions found.'}
|
<h6 class="fw-bold">No se encontraron comisiones activas</h6>
|
||||||
|
<p class="small text-muted mb-0">No hay comisiones de cursada activas para optimizar en este ciclo lectivo.</p>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error loading commissions:', error);
|
console.error('Error cargando comisiones:', error);
|
||||||
document.getElementById('commissions-list').innerHTML = `
|
if (countBadge) countBadge.textContent = 'Error al cargar';
|
||||||
<div class="col-12 text-center text-danger py-4">
|
commissionsList.innerHTML = `
|
||||||
<i class="bi bi-exclamation-triangle fs-2 d-block mb-2"></i>
|
<div class="col-12 text-center text-danger py-5">
|
||||||
Error al cargar comisiones: ${error.message}
|
<i class="bi bi-exclamation-triangle-fill fs-1 d-block mb-2 text-danger"></i>
|
||||||
|
<h6 class="fw-bold">Error al cargar comisiones</h6>
|
||||||
|
<p class="small text-muted mb-3">${error.message}</p>
|
||||||
|
<button class="btn btn-sm btn-outline-primary" onclick="loadCommissions()">
|
||||||
|
<i class="bi bi-arrow-clockwise me-1"></i>Reintentar
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user