497 lines
20 KiB
JavaScript
497 lines
20 KiB
JavaScript
class GeneticAlgorithmManager {
|
|
constructor() {
|
|
this.apiBaseUrl = '/api/genetic';
|
|
this.setupEventListeners();
|
|
}
|
|
|
|
setupEventListeners() {
|
|
// Initialize any UI elements if needed
|
|
document.addEventListener('DOMContentLoaded', () => {
|
|
this.initializeUI();
|
|
});
|
|
}
|
|
|
|
initializeUI() {
|
|
// Set up event listeners for genetic algorithm buttons
|
|
const optimizeBtn = document.getElementById('optimize-assignments-btn');
|
|
const previewBtn = document.getElementById('preview-optimization-btn');
|
|
const applyBtn = document.getElementById('apply-optimization-btn');
|
|
|
|
if (optimizeBtn) {
|
|
optimizeBtn.addEventListener('click', () => this.handleOptimizeReservations());
|
|
}
|
|
|
|
if (previewBtn) {
|
|
previewBtn.addEventListener('click', () => this.handlePreviewOptimization());
|
|
}
|
|
|
|
if (applyBtn) {
|
|
applyBtn.addEventListener('click', () => this.handleApplyOptimization());
|
|
}
|
|
}
|
|
|
|
async optimizeReservations(commissionIds, startDate = null, endDate = null) {
|
|
try {
|
|
const requestBody = {
|
|
commission_ids: commissionIds
|
|
};
|
|
|
|
if (startDate) {
|
|
requestBody.start_date = startDate;
|
|
}
|
|
if (endDate) {
|
|
requestBody.end_date = endDate;
|
|
}
|
|
|
|
const response = await fetch(`${this.apiBaseUrl}/optimize`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
},
|
|
body: JSON.stringify(requestBody)
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.error || 'Optimization failed');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Error optimizing reservations:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async previewOptimization(commissionIds) {
|
|
try {
|
|
const response = await fetch(`${this.apiBaseUrl}/preview-optimization`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
},
|
|
body: JSON.stringify({
|
|
commission_ids: commissionIds,
|
|
dry_run: true
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.error || 'Preview failed');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Error previewing optimization:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async applyOptimization(reservations) {
|
|
try {
|
|
const response = await fetch(`${this.apiBaseUrl}/apply-optimization`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
},
|
|
body: JSON.stringify({
|
|
reservations: reservations
|
|
})
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.error || 'Failed to apply optimization');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Error applying optimization:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async getAlgorithmStatus() {
|
|
try {
|
|
const response = await fetch(`${this.apiBaseUrl}/algorithm-status`, {
|
|
method: 'GET',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-CSRFToken': this.getCSRFToken()
|
|
}
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorData = await response.json();
|
|
throw new Error(errorData.error || 'Failed to get algorithm status');
|
|
}
|
|
|
|
return await response.json();
|
|
} catch (error) {
|
|
console.error('Error getting algorithm status:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
async handleOptimizeReservations() {
|
|
try {
|
|
// Get selected commissions from UI
|
|
const commissionIds = this.getSelectedCommissionIds();
|
|
|
|
if (commissionIds.length === 0) {
|
|
this.showAlert('Por favor seleccione al menos una comisión para optimizar.', 'warning');
|
|
return;
|
|
}
|
|
|
|
this.showLoading(true);
|
|
|
|
const result = await this.optimizeReservations(commissionIds);
|
|
|
|
if (result.success) {
|
|
this.displayOptimizationResults(result.data);
|
|
this.showAlert('¡Optimización de reservas completada con éxito!', 'success');
|
|
} else {
|
|
this.showAlert('Fallo en la optimización: ' + (result.error || 'Error desconocido'), 'danger');
|
|
}
|
|
} catch (error) {
|
|
this.showAlert('Error durante la optimización: ' + error.message, 'danger');
|
|
} finally {
|
|
this.showLoading(false);
|
|
}
|
|
}
|
|
|
|
async handlePreviewOptimization() {
|
|
try {
|
|
const commissionIds = this.getSelectedCommissionIds();
|
|
|
|
if (commissionIds.length === 0) {
|
|
this.showAlert('Por favor seleccione al menos una comisión para previsualizar.', 'warning');
|
|
return;
|
|
}
|
|
|
|
this.showLoading(true);
|
|
|
|
const result = await this.previewOptimization(commissionIds);
|
|
|
|
if (result.success) {
|
|
this.displayPreviewResults(result.data);
|
|
this.showAlert('¡Previsualización generada con éxito!', 'success');
|
|
} else {
|
|
this.showAlert('Fallo en la previsualización: ' + (result.error || 'Error desconocido'), 'danger');
|
|
}
|
|
} catch (error) {
|
|
this.showAlert('Error durante la previsualización: ' + error.message, 'danger');
|
|
} finally {
|
|
this.showLoading(false);
|
|
}
|
|
}
|
|
|
|
async handleApplyOptimization() {
|
|
try {
|
|
const pendingReservations = this.getPendingReservations();
|
|
|
|
if (!pendingReservations || pendingReservations.length === 0) {
|
|
this.showAlert('No hay reservas optimizadas pendientes de aplicar.', 'warning');
|
|
return;
|
|
}
|
|
|
|
if (!confirm('¿Está seguro de que desea aplicar estas asignaciones optimizadas? Se crearán las reservas definitivas en el sistema.')) {
|
|
return;
|
|
}
|
|
|
|
this.showLoading(true);
|
|
|
|
const result = await this.applyOptimization(pendingReservations);
|
|
|
|
if (result.success) {
|
|
this.showAlert(`¡Se aplicaron con éxito ${result.data.applied_count} reservas en Bedelía!`, 'success');
|
|
this.clearPendingReservations();
|
|
// Redirigir al listado de reservas
|
|
window.location.href = '/schedule/list_reservations';
|
|
} else {
|
|
this.showAlert('Fallo al aplicar reservas: ' + (result.error || 'Error desconocido'), 'danger');
|
|
}
|
|
} catch (error) {
|
|
this.showAlert('Error al aplicar reservas: ' + error.message, 'danger');
|
|
} finally {
|
|
this.showLoading(false);
|
|
}
|
|
}
|
|
|
|
getSelectedCommissionIds() {
|
|
const checkboxes = document.querySelectorAll('input[name="commission_ids"]:checked');
|
|
return Array.from(checkboxes).map(cb => parseInt(cb.value));
|
|
}
|
|
|
|
getPendingReservations() {
|
|
// Try to get from localStorage or a hidden form field
|
|
const stored = localStorage.getItem('pending_optimizations');
|
|
return stored ? JSON.parse(stored) : null;
|
|
}
|
|
|
|
storePendingReservations(reservations) {
|
|
localStorage.setItem('pending_optimizations', JSON.stringify(reservations));
|
|
}
|
|
|
|
clearPendingReservations() {
|
|
localStorage.removeItem('pending_optimizations');
|
|
}
|
|
|
|
displayOptimizationResults(data) {
|
|
// Store the results for potential application
|
|
this.storePendingReservations(data.reservations);
|
|
|
|
// Create results display
|
|
const resultsContainer = document.getElementById('optimization-results');
|
|
if (!resultsContainer) return;
|
|
|
|
const scorePercentage = (data.fitness_score * 100).toFixed(1);
|
|
|
|
resultsContainer.innerHTML = `
|
|
<div class="card border-0 shadow-sm mb-4">
|
|
<div class="card-header bg-success text-white py-3">
|
|
<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 class="card-body p-4">
|
|
<div class="row g-3 mb-4 text-center">
|
|
<div class="col-md-4">
|
|
<div class="p-3 rounded bg-primary bg-opacity-10 border border-primary-subtle">
|
|
<h3 class="fw-bold text-primary mb-1">${data.assigned_reservations}</h3>
|
|
<p class="mb-0 text-muted small fw-semibold">Reservas Asignadas</p>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-4">
|
|
<div class="p-3 rounded bg-info bg-opacity-10 border border-info-subtle">
|
|
<h3 class="fw-bold text-info mb-1">${scorePercentage}%</h3>
|
|
<p class="mb-0 text-muted small fw-semibold">Puntaje de Aptitud (Fitness)</p>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-4">
|
|
<div class="p-3 rounded bg-warning bg-opacity-10 border border-warning-subtle">
|
|
<h3 class="fw-bold text-warning mb-1">${data.total_requests}</h3>
|
|
<p class="mb-0 text-muted small fw-semibold">Total de Solicitudes</p>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
${data.conflicts.length > 0 ? `
|
|
<div class="alert alert-warning d-flex align-items-center">
|
|
<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 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 flex-wrap">
|
|
<button class="btn btn-outline-primary" onclick="geneticManager.viewReservationDetails()">
|
|
<i class="bi bi-eye me-1"></i>Ver Detalle de Reservas
|
|
</button>
|
|
<button class="btn btn-success fw-bold px-4" onclick="geneticManager.handleApplyOptimization()">
|
|
<i class="bi bi-check-circle me-1"></i>Aplicar Reservas en Bedelía
|
|
</button>
|
|
<button class="btn btn-outline-secondary" onclick="geneticManager.clearResults()">
|
|
<i class="bi bi-trash me-1"></i>Limpiar
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
displayPreviewResults(data) {
|
|
const previewContainer = document.getElementById('preview-results');
|
|
if (!previewContainer) return;
|
|
|
|
const commissionsHtml = data.commission_details.map(commission => `
|
|
<tr>
|
|
<td class="font-monospace fw-bold text-primary">${commission.code}</td>
|
|
<td>${commission.name}</td>
|
|
<td><span class="badge bg-secondary">${commission.current_students || 0}/${commission.max_students}</span></td>
|
|
</tr>
|
|
`).join('');
|
|
|
|
const optimization = data.optimization_result;
|
|
|
|
previewContainer.innerHTML = `
|
|
<div class="card border-0 shadow-sm mb-4">
|
|
<div class="card-header bg-info text-white py-3">
|
|
<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 class="card-body p-4">
|
|
<div class="row g-4 mb-4">
|
|
<div class="col-md-7">
|
|
<h6 class="fw-bold text-muted text-uppercase small mb-2">Comisiones a Optimizar</h6>
|
|
<div class="table-responsive border rounded">
|
|
<table class="table table-hover table-sm mb-0">
|
|
<thead class="table-light">
|
|
<tr>
|
|
<th>Código</th>
|
|
<th>Asignatura</th>
|
|
<th>Estudiantes</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${commissionsHtml}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</div>
|
|
<div class="col-md-5">
|
|
<h6 class="fw-bold text-muted text-uppercase small mb-2">Resultados Estimados</h6>
|
|
<ul class="list-group shadow-sm">
|
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
|
<span>Reservas Creadas:</span>
|
|
<strong class="text-primary font-monospace fs-6">${optimization.assigned_reservations}</strong>
|
|
</li>
|
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
|
<span>Puntaje de Aptitud:</span>
|
|
<strong class="text-info font-monospace fs-6">${(optimization.fitness_score * 100).toFixed(1)}%</strong>
|
|
</li>
|
|
<li class="list-group-item d-flex justify-content-between align-items-center py-2">
|
|
<span>Conflictos:</span>
|
|
<strong class="font-monospace fs-6 ${optimization.conflicts.length > 0 ? 'text-danger' : 'text-success'}">
|
|
${optimization.conflicts.length}
|
|
</strong>
|
|
</li>
|
|
</ul>
|
|
</div>
|
|
</div>
|
|
|
|
<div class="d-flex gap-2">
|
|
<button class="btn btn-primary" onclick="geneticManager.handleOptimizeReservations()">
|
|
<i class="bi bi-play-circle me-1"></i>Ejecutar Optimización Completa
|
|
</button>
|
|
<button class="btn btn-outline-secondary" onclick="geneticManager.clearPreview()">
|
|
<i class="bi bi-x-circle me-1"></i>Cerrar Previsualización
|
|
</button>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
`;
|
|
}
|
|
|
|
viewReservationDetails() {
|
|
const reservations = this.getPendingReservations();
|
|
if (!reservations || reservations.length === 0) {
|
|
this.showAlert('No hay detalles de reserva disponibles.', 'info');
|
|
return;
|
|
}
|
|
|
|
// Create modal or redirect to detailed view
|
|
const detailsHtml = reservations.map((res, index) => `
|
|
<tr>
|
|
<td>${index + 1}</td>
|
|
<td>${res.purpose || 'Cursada Académica'}</td>
|
|
<td><span class="badge bg-primary">Aula ID ${res.classroom_id}</span></td>
|
|
<td class="small font-monospace">${new Date(res.start_time).toLocaleString('es-AR')}</td>
|
|
<td class="small font-monospace">${new Date(res.end_time).toLocaleString('es-AR')}</td>
|
|
<td><span class="badge bg-secondary">${res.expected_attendees || 0}</span></td>
|
|
</tr>
|
|
`).join('');
|
|
|
|
const modal = document.getElementById('detailsModal');
|
|
if (modal) {
|
|
modal.querySelector('.modal-body').innerHTML = `
|
|
<div class="table-responsive">
|
|
<table class="table table-hover table-sm">
|
|
<thead class="table-light">
|
|
<tr>
|
|
<th>#</th>
|
|
<th>Propósito</th>
|
|
<th>Aula Asignada</th>
|
|
<th>Inicio</th>
|
|
<th>Fin</th>
|
|
<th>Asistentes</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
${detailsHtml}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
`;
|
|
|
|
const bootstrapModal = new bootstrap.Modal(modal);
|
|
bootstrapModal.show();
|
|
}
|
|
}
|
|
|
|
clearResults() {
|
|
const resultsContainer = document.getElementById('optimization-results');
|
|
if (resultsContainer) {
|
|
resultsContainer.innerHTML = '';
|
|
}
|
|
this.clearPendingReservations();
|
|
}
|
|
|
|
clearPreview() {
|
|
const previewContainer = document.getElementById('preview-results');
|
|
if (previewContainer) {
|
|
previewContainer.innerHTML = '';
|
|
}
|
|
}
|
|
|
|
showLoading(show) {
|
|
const loadingSpinner = document.getElementById('loading-spinner');
|
|
if (loadingSpinner) {
|
|
loadingSpinner.style.display = show ? 'block' : 'none';
|
|
}
|
|
}
|
|
|
|
showAlert(message, type = 'info') {
|
|
// Create and show alert
|
|
const alertContainer = document.getElementById('alert-container');
|
|
if (!alertContainer) return;
|
|
|
|
const alertHtml = `
|
|
<div class="alert alert-${type} alert-dismissible fade show" role="alert">
|
|
${message}
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
|
|
</div>
|
|
`;
|
|
|
|
alertContainer.insertAdjacentHTML('beforeend', alertHtml);
|
|
|
|
// Auto-dismiss after 5 seconds
|
|
setTimeout(() => {
|
|
const alert = alertContainer.lastElementChild;
|
|
if (alert) {
|
|
const bsAlert = new bootstrap.Alert(alert);
|
|
bsAlert.close();
|
|
}
|
|
}, 5000);
|
|
}
|
|
|
|
getCSRFToken() {
|
|
// Get CSRF token from meta tag or cookie
|
|
const metaTag = document.querySelector('meta[name="csrf-token"]');
|
|
if (metaTag) {
|
|
return metaTag.getAttribute('content');
|
|
}
|
|
|
|
// Fallback to cookie
|
|
const cookies = document.cookie.split(';');
|
|
for (let cookie of cookies) {
|
|
const [name, value] = cookie.trim().split('=');
|
|
if (name === 'csrf_token') {
|
|
return decodeURIComponent(value);
|
|
}
|
|
}
|
|
|
|
return '';
|
|
}
|
|
}
|
|
|
|
// Initialize the genetic algorithm manager
|
|
const geneticManager = new GeneticAlgorithmManager();
|
|
|
|
// Export for global access
|
|
window.geneticManager = geneticManager; |