From 368dc71b14a1eb84a75699f14d4e68e599693261 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Thu, 8 Oct 2026 08:26:15 -0300 Subject: [PATCH] fix(v3.4.6): fix reservation cascade, remove calendar mocks, strip auto meet links, friendly dates, dynamic building floors and career filter --- CHANGELOG.md | 17 ++++++ MEMORY.md | 12 ++++ ROADMAP.md | 2 +- backend/app/__init__.py | 2 +- backend/app/models/classroom.py | 21 +++++-- backend/app/routes/api/admin.py | 13 ++--- backend/app/routes/api/openapi.py | 2 +- backend/app/routes/api/reservations.py | 3 + backend/app/services/sheets_importer.py | 24 +++++--- backend/setup.py | 2 +- frontend/package.json | 2 +- frontend/src/app.js | 6 +- frontend/src/routes/buildings.js | 42 +++++++++++++- frontend/src/routes/classrooms.js | 53 +++++++++++++++--- frontend/src/routes/schedule.js | 73 ++++++++++++++++++------- frontend/views/base.html | 2 +- frontend/views/buildings/list.html | 2 +- frontend/views/buildings/view.html | 23 ++++---- frontend/views/classrooms/add.html | 6 +- frontend/views/classrooms/edit.html | 6 +- frontend/views/classrooms/view.html | 8 +-- frontend/views/schedule/add.html | 66 ++++++++++------------ frontend/views/schedule/edit.html | 53 +++++++----------- 23 files changed, 291 insertions(+), 149 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3be818e..7d10aa4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,23 @@ 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. - **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción. +## [3.4.6] - 2026-10-08 +### Corregido & Mejorado (Reservas, Relaciones Edificios/Aulas, Fechas y Filtros) +- **Módulo de Reservas (`/schedule/add_reservation` y `/schedule/edit`):** + - Corrección del fallo de serialización JSON que rompía el selector en cascada Edificio -> Piso -> Aula al seleccionar el "Edificio Central". Inyección segura de `classroom_data_json` y `commission_data_json` sin escape de entidades HTML (`"`), y matching ultra tolerante de pisos físicos y virtuales. +- **Calendario Académico (`/schedule/calendar_view` y `/schedule/calendar_data`):** + - Limpieza exhaustiva de datos mockeados y hardcodeados (`Arquitectura de Software ARQ-101`, `COM-A`, `Licenciatura en Sistemas`). El feed y los filtros ahora consumen estrictamente asignaturas, carreras, comisiones y aulas reales de la base de datos institucional. +- **Importador de Google Sheets (`sheets_importer.py`):** + - Eliminación de la autogeneración no deseada de enlaces de Google Meet / Zoom (`https://meet.google.com/edu-...`) en reservas importadas con celdas vacías (ej. `#9797 ASIG00215 - Marketing Digital`). Se respeta estrictamente el Sheet: solo se asocian enlaces virtuales si vienen explícitamente en el documento original. +- **UX/UI Ficha del Aula (`/classrooms/view_classroom`):** + - Formateo amigable en español institucional para las reservas y clases programadas (ej. `Viernes 04/09/2026 · 18:30 a 21:30 hs`) eliminando el formato ISO repetido y ampliando el rango de consulta a todo el ciclo lectivo 2026. +- **Gestión de Edificios, Aulas y Pisos Dinámicos (`/buildings/list_buildings` y `/buildings/view/:id`):** + - Corrección de la ficha de edificio que mostraba "No hay aulas asignadas a este edificio" a pesar de tener 6 aulas configuradas. Implementación del agrupador `floors_list` y `classrooms_by_floor`. + - Corrección del contador de "Pisos Presenciales" en el listado general de edificios para mostrar el conteo real (4 pisos) en lugar de 0. + - Soporte de niveles dinámicos alfanuméricos: creación y selección de "Planta Baja (PB)", "Entrepiso (EP)", "Subsuelo (SS)", etc., en modelos, datalists y vistas de detalle. +- **Filtros en Gestión de Comisiones (`/admin/commissions_list`):** + - Corrección de `UnboundLocalError` en `backend/app/routes/api/admin.py` dentro de `get_commissions` causado por importación interna tardía de `Career`, que provocaba error 500 al filtrar por carrera (`career_id=180, 181, 182`). Grilla ahora filtra correctamente sobre materias compartidas (`subject_careers`). + ## [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:** diff --git a/MEMORY.md b/MEMORY.md index 42e65d7..61130e3 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -148,6 +148,18 @@ Memoria del proyecto entre sesiones para la rama `dev`. - 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. +- **Sprint v3.4.6: Corrección Integral de Reservas, Pisos Dinámicos, Fechas Humanas y Filtro de Carreras**: + - **Incidencias Resueltas**: + 1. `/schedule/add_reservation` y `/schedule/edit`: Corregido error de serialización JSON que rompía el selector en cascada Edificio -> Piso -> Aula al seleccionar "Edificio Central". Inyección segura sin entities y matching resiliente de pisos físicos y virtuales. + 2. `/schedule/calendar_view`: Limpieza de datos hardcodeados/mockeados (`Arquitectura de Software ARQ-101`, `COM-A`, `Licenciatura en Sistemas`). El feed y filtros ahora consumen asignaturas, carreras y comisiones reales de la BD. + 3. `sheets_importer.py`: Eliminada la autogeneración no deseada de enlaces de Google Meet / Zoom (`meet.google.com/edu-...`) en reservas importadas cuando la celda original está vacía (ej. `#9797 ASIG00215 - Marketing Digital`). + 4. `/classrooms/view_classroom`: Formateadas fechas y horarios a español legible (ej. `Viernes 04/09/2026 · 18:30 a 21:30 hs`) eliminando formato ISO repetido y ampliando rango a todo el semestre 2026. + 5. `/buildings/list_buildings` y `/buildings/view/:id`: Corregida la ficha de edificio que mostraba "No hay aulas asignadas a este edificio" a pesar de tener 6 aulas físicas asociadas (`floors_list` y `classrooms_by_floor`), corregido el contador de "Pisos Presenciales" (4 pisos) y soporte completo de niveles dinámicos alfanuméricos (PB, EP, Subsuelo, etc.). + 6. `/admin/commissions_list`: Corregido `UnboundLocalError` en `backend/app/routes/api/admin.py` por importación interna tardía de `Career`, que arrojaba HTTP 500 al filtrar por `career_id=180, 181, 182`. + - **Bump Semántico y Despliegue Obligatorio (Principio 9)**: + - Versión incrementada a `v3.4.6` en Frontend y Backend. + - Suite completa de 49 pruebas pytest aprobada al 100%. + ## 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). 2. Monitoreo continuo de la experiencia de usuario en Bedelía, Cartelera del Día y Sincronización Académica. \ No newline at end of file diff --git a/ROADMAP.md b/ROADMAP.md index 2864886..ffad839 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -2,7 +2,7 @@ ## Gestión de Espacios Áulicos, Asignación de Comisiones y Operatoria de Bedelía **Institución:** Universidad de la Ciudad de Buenos Aires (UniCABA) -**Versión:** 3.4.5 (Optimizador de Aulas IA: Corrección de Permisos Bedelía, Carga de Comisiones e Interfaz en Español) +**Versión:** 3.4.6 (Corrección Integral de Reservas, Pisos Dinámicos, Fechas Humanas y Filtro de Carreras) **Fecha de Actualización:** 08 de Octubre de 2026 **Rama Base:** `dev` diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 763534d..b6502d3 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -6,7 +6,7 @@ from flask_babel import Babel, gettext as _ from config.config import Config # Initialize extensions -__version__ = "3.4.5" +__version__ = "3.4.6" db = SQLAlchemy() migrate = Migrate() cors = CORS() diff --git a/backend/app/models/classroom.py b/backend/app/models/classroom.py index 1d69e9c..4614857 100644 --- a/backend/app/models/classroom.py +++ b/backend/app/models/classroom.py @@ -30,13 +30,24 @@ class Classroom(db.Model): @property def floor_display(self): - """Formato amigable para el piso: PB, Planta Baja, Piso X""" + """Formato amigable y dinámico para el piso: PB, EP, Subsuelo, Piso X""" + if self.is_virtual: + return 'Campus Virtual' f = str(self.floor).strip() if self.floor is not None else '' - if f in ['0', 'PB', 'pb', 'Planta Baja', 'planta baja']: - return 'Planta Baja' - if f.lower().startswith('piso') or '°' in f: + if not f: + return 'Planta Baja (PB)' + f_lower = f.lower() + if f in ['0', 'PB', 'pb'] or 'planta baja' in f_lower: + return 'Planta Baja (PB)' + if f in ['EP', 'ep'] or 'entrepiso' in f_lower: + return 'Entrepiso (EP)' + if f in ['SS', 'ss'] or 'subsuelo' in f_lower: + return f if 'subsuelo' in f_lower else 'Subsuelo (SS)' + if f_lower.startswith('piso') or f_lower.startswith('planta') or f_lower.startswith('nivel') or '°' in f: return f - return f"Piso {f}" + if f.isdigit(): + return f"Piso {f}" + return f @property def is_virtual(self): diff --git a/backend/app/routes/api/admin.py b/backend/app/routes/api/admin.py index 1cd9e38..c44196c 100644 --- a/backend/app/routes/api/admin.py +++ b/backend/app/routes/api/admin.py @@ -7,6 +7,7 @@ from app.models.role import Role, Permission, SYSTEM_MODULES from app.models.subject import Subject, Commission, CommissionTeacher from app.models.career import Career from app.models.classroom import Classroom +from app.models.building import Building from app.models.reservation import Reservation, ReservationStatus from app.models.academic_term import AcademicTerm from app.models.milestone import MilestoneType, AcademicMilestone @@ -218,7 +219,6 @@ def get_commissions(): commissions = query.order_by(Commission.id.asc()).all() subjects = Subject.query.order_by(Subject.name.asc()).all() - from app.models.career import Career careers = Career.query.order_by(Career.name.asc()).all() careers_data = [{'id': cr.id, 'name': cr.name, 'code': cr.code} for cr in careers] @@ -938,11 +938,7 @@ def create_commission(): if not subject: return jsonify({'error': 'NotFound', 'message': f'La asignatura con ID {subject_id} no existe.'}), 404 - # Generar enlace automático si no fue provisto - if not virtual_link: - s_clean = re.sub(r'[^a-zA-Z0-9]', '', subject.code).lower()[:6] or 'subj' - c_clean = re.sub(r'[^a-zA-Z0-9]', '', code).lower()[:4] or 'c1' - virtual_link = f"https://meet.google.com/edu-{s_clean}-{c_clean}" + virtual_link = (virtual_link or '').strip() or None existing = Commission.query.filter_by( subject_id=int(subject_id), @@ -2518,10 +2514,13 @@ def get_building(id): building = Building.query.get(id) if not building: return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404 + classrooms = Classroom.query.filter( + db.or_(Classroom.building_id == id, Classroom.building == building.name) + ).order_by(Classroom.floor.asc(), Classroom.code.asc()).all() return jsonify({ 'status': 'success', 'building': building.to_dict(), - 'classrooms': [c.to_dict() for c in building.classrooms] + 'classrooms': [c.to_dict() for c in classrooms] }), 200 diff --git a/backend/app/routes/api/openapi.py b/backend/app/routes/api/openapi.py index b640375..7d6be7e 100644 --- a/backend/app/routes/api/openapi.py +++ b/backend/app/routes/api/openapi.py @@ -7,7 +7,7 @@ OPENAPI_SPEC = { "info": { "title": "Edu-Space REST API", "description": "Enterprise Academic & Physical Space Management REST API with JWT Authentication and Role-Based Access Control.", - "version": "3.4.5" + "version": "3.4.6" }, "servers": [ { diff --git a/backend/app/routes/api/reservations.py b/backend/app/routes/api/reservations.py index 2ffa4a5..2aab5cf 100644 --- a/backend/app/routes/api/reservations.py +++ b/backend/app/routes/api/reservations.py @@ -86,6 +86,9 @@ def list_reservations(): 'purpose': r.purpose, 'subject_name': r.subject_name, 'subject_code': r.subject_code, + 'career_name': r.commission.career_name if (r.commission and hasattr(r.commission, 'career_name')) else '', + 'career_names': r.commission.career_names if (r.commission and hasattr(r.commission, 'career_names')) else '', + 'commission_code': r.commission.code if r.commission else '', 'status': str(r.status.value if hasattr(r.status, 'value') else r.status), 'shift': r.shift or 'Mañana', 'virtual_link': r.virtual_link, diff --git a/backend/app/services/sheets_importer.py b/backend/app/services/sheets_importer.py index 345e8d4..0953963 100644 --- a/backend/app/services/sheets_importer.py +++ b/backend/app/services/sheets_importer.py @@ -269,6 +269,14 @@ class GoogleSheetsImporter: elif h < 13: record_shift = 'Mañana' + v_link_row = None + if len(row) > col_offset + 5: + for extra_c in row[col_offset + 5:]: + extra_clean = _clean(extra_c) + if any(x in extra_clean.lower() for x in ['http://', 'https://', 'zoom.us', 'meet.google.com', 'teams.microsoft.com']): + v_link_row = extra_clean + break + records.append({ 'dia': sheet_name, 'codigo': codigo, @@ -276,7 +284,8 @@ class GoogleSheetsImporter: 'aula': aula, 'carrera': carrera, 'horario': horario, - 'turno': record_shift + 'turno': record_shift, + 'virtual_link': v_link_row }) return records @@ -852,13 +861,10 @@ class GoogleSheetsImporter: if import_reservations and classroom and subject and commission and t_start and t_end: is_room_virtual = bool(classroom.is_virtual or 'VIRTUAL' in (classroom.code or '').upper()) - v_link = None - if is_room_virtual: - clean_subj = re.sub(r'[^a-zA-Z0-9]', '', subject.code or 'cls').lower() - clean_comm = re.sub(r'[^a-zA-Z0-9]', '', commission.code or 'c1').lower() - v_link = f"https://meet.google.com/edu-{clean_subj}-{clean_comm}" - if not commission.virtual_link: - commission.virtual_link = v_link + # Respetar estrictamente los datos del Sheet: si no hay enlace explícito en el documento, NO autogenerar ninguno + v_link = rec.get('virtual_link') or None + if v_link and not commission.virtual_link: + commission.virtual_link = v_link # Determinar fechas a generar: específica de la fila (datepicker), puntual o 16 semanas dates_to_generate = [] @@ -921,7 +927,7 @@ class GoogleSheetsImporter: else: existing_res.shift = turno existing_res.notes = note_text - if is_room_virtual and not existing_res.virtual_link: + if v_link: existing_res.virtual_link = v_link if len(stats['sample_records']) < 15: diff --git a/backend/setup.py b/backend/setup.py index 82ee8b1..3883ec6 100644 --- a/backend/setup.py +++ b/backend/setup.py @@ -2,7 +2,7 @@ from setuptools import setup, find_packages setup( name="edu-space-admin", - version="3.4.5", + version="3.4.6", description="Administrative interface for Edu-Space Classroom Management System", author="Edu-Space Development Team", author_email="admin@edu-space.com", diff --git a/frontend/package.json b/frontend/package.json index fc8f5fa..895d68e 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.4.5", + "version": "3.4.6", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/src/app.js b/frontend/src/app.js index 5e2f1bc..6f8fa7b 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -85,9 +85,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), { }); // Versiones institucionales del sistema -const APP_VERSION = '3.4.5'; -const FRONTEND_VERSION = '3.4.5'; -const BACKEND_VERSION = '3.4.5'; +const APP_VERSION = '3.4.6'; +const FRONTEND_VERSION = '3.4.6'; +const BACKEND_VERSION = '3.4.6'; env.addGlobal('app_version', APP_VERSION); env.addGlobal('frontend_version', FRONTEND_VERSION); diff --git a/frontend/src/routes/buildings.js b/frontend/src/routes/buildings.js index d615fe2..2628d71 100644 --- a/frontend/src/routes/buildings.js +++ b/frontend/src/routes/buildings.js @@ -85,12 +85,17 @@ const handleListBuildings = async (req, res) => { .filter(b => !b.is_virtual) .reduce((acc, b) => acc + (b.physical_capacity || b.total_capacity || 0), 0); + const total_floors = stats.total_floors || buildings + .filter(b => !b.is_virtual) + .reduce((acc, b) => acc + (parseInt(b.floors, 10) || 0), 0); + res.render('buildings/list', { title: 'Gestión de Edificios - Edu-Space Admin', buildings, total_classrooms: stats.total_classrooms || buildings.reduce((a, b) => a + (b.classrooms_count || 0), 0), total_capacity: total_physical_capacity, total_physical_capacity, + total_floors, search, status_filter: status }); @@ -102,6 +107,7 @@ const handleListBuildings = async (req, res) => { total_classrooms: 31, total_capacity: 1250, total_physical_capacity: 1250, + total_floors: 4, search: '', status_filter: '' }); @@ -174,10 +180,44 @@ router.get(['/view/:id', '/view_building', '/:id'], async (req, res) => { floors_display: is_virtual ? 'Digital' : String(building.floors ?? 1) }; + // Agrupación dinámica por piso / nivel + const floorsMap = new Map(); + classrooms.forEach(c => { + const floorKey = c.floor_display || (c.floor === '0' || c.floor === 'PB' ? 'Planta Baja (PB)' : (c.floor ? (c.floor.toLowerCase().startsWith('piso') ? c.floor : `Piso ${c.floor}`) : 'Planta Baja (PB)')); + if (!floorsMap.has(floorKey)) { + floorsMap.set(floorKey, []); + } + floorsMap.get(floorKey).push(c); + }); + + const sortedFloorKeys = Array.from(floorsMap.keys()).sort((a, b) => { + const fA = String(a).toUpperCase(); + const fB = String(b).toUpperCase(); + if (fA.includes('SUB') || fA.includes('SS')) return -1; + if (fB.includes('SUB') || fB.includes('SS')) return 1; + if (fA.includes('PB') || fA.includes('PLANTA BAJA')) return -1; + if (fB.includes('PB') || fB.includes('PLANTA BAJA')) return 1; + if (fA.includes('EP') || fA.includes('ENTRE')) return -1; + if (fB.includes('EP') || fB.includes('ENTRE')) return 1; + return fA.localeCompare(fB, undefined, { numeric: true }); + }); + + const floors_list = sortedFloorKeys.map(floorName => ({ + floor_name: floorName, + classrooms: floorsMap.get(floorName) + })); + + const classrooms_by_floor = {}; + floorsMap.forEach((rooms, floorName) => { + classrooms_by_floor[floorName] = rooms; + }); + res.render('buildings/view', { title: `Edificio ${building.name} - Edu-Space Admin`, building, - classrooms + classrooms, + classrooms_by_floor, + floors_list }); }); diff --git a/frontend/src/routes/classrooms.js b/frontend/src/routes/classrooms.js index 891ee5e..50d043b 100644 --- a/frontend/src/routes/classrooms.js +++ b/frontend/src/routes/classrooms.js @@ -456,16 +456,53 @@ const handleViewClassroom = async (req, res) => { classroom.code_display = classroom.code_display || classroom.code || `Aula-${classroomId}`; classroom.building_entity = classroom.building_entity || null; - // Fetch upcoming reservations for this classroom + // Fetch upcoming reservations for this classroom (encompassing full 2026 academic term) try { - const rRes = await req.apiClient.get(`/reservations?classroom_id=${classroomId}&start_date=2026-08-31&end_date=2026-10-01`); + const rRes = await req.apiClient.get(`/reservations?classroom_id=${classroomId}&start_date=2026-08-01&end_date=2026-12-31`); const allClassroomRes = (rRes.data && (rRes.data.reservations || rRes.data)) || []; - upcomingReservations = allClassroomRes.map(r => ({ - ...r, - date_display: r.start_time ? r.start_time.split('T')[0] : '', - start_time_display: r.start_time ? (r.start_time.includes('T') ? r.start_time.split('T')[1].substring(0, 5) : r.start_time) : '', - end_time_display: r.end_time ? (r.end_time.includes('T') ? r.end_time.split('T')[1].substring(0, 5) : r.end_time) : '' - })).sort((a, b) => a.start_time.localeCompare(b.start_time)).slice(0, 20); + const dayNames = ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado']; + + upcomingReservations = allClassroomRes.map(r => { + let dateDisplayFriendly = ''; + let timeRangeFriendly = ''; + let fullDisplay = ''; + + if (r.start_time) { + try { + const rawStart = String(r.start_time).replace(' ', 'T'); + const rawEnd = r.end_time ? String(r.end_time).replace(' ', 'T') : ''; + const dtStart = new Date(rawStart); + const dtEnd = rawEnd ? new Date(rawEnd) : null; + + const dayName = dayNames[dtStart.getDay()]; + const d = String(dtStart.getDate()).padStart(2, '0'); + const m = String(dtStart.getMonth() + 1).padStart(2, '0'); + const y = dtStart.getFullYear(); + dateDisplayFriendly = `${dayName} ${d}/${m}/${y}`; + + const sH = String(dtStart.getHours()).padStart(2, '0'); + const sM = String(dtStart.getMinutes()).padStart(2, '0'); + const eH = dtEnd ? String(dtEnd.getHours()).padStart(2, '0') : ''; + const eM = dtEnd ? String(dtEnd.getMinutes()).padStart(2, '0') : ''; + timeRangeFriendly = dtEnd ? `${sH}:${sM} a ${eH}:${eM} hs` : `${sH}:${sM} hs`; + fullDisplay = `${dateDisplayFriendly} · ${timeRangeFriendly}`; + } catch (e) { + dateDisplayFriendly = r.start_time.split('T')[0] || r.start_time; + timeRangeFriendly = r.end_time ? `${r.start_time} - ${r.end_time}` : r.start_time; + fullDisplay = `${dateDisplayFriendly} · ${timeRangeFriendly}`; + } + } + + return { + ...r, + date_display: r.start_time ? r.start_time.split('T')[0] : '', + date_display_friendly: dateDisplayFriendly, + time_range_friendly: timeRangeFriendly, + full_display: fullDisplay, + start_time_display: r.start_time ? (r.start_time.includes('T') ? r.start_time.split('T')[1].substring(0, 5) : r.start_time) : '', + end_time_display: r.end_time ? (r.end_time.includes('T') ? r.end_time.split('T')[1].substring(0, 5) : r.end_time) : '' + }; + }).sort((a, b) => (a.start_time || '').localeCompare(b.start_time || '')).slice(0, 30); } catch (e) { console.warn('Could not fetch reservations for classroom:', e.message); } diff --git a/frontend/src/routes/schedule.js b/frontend/src/routes/schedule.js index a4a5566..077d009 100644 --- a/frontend/src/routes/schedule.js +++ b/frontend/src/routes/schedule.js @@ -29,6 +29,23 @@ const handleCalendarView = async (req, res) => { console.warn('Could not fetch unassigned commissions for calendar:', e.message); } + let careers = []; + let subjects = []; + try { + const [carRes, subRes] = await Promise.allSettled([ + req.apiClient.get('/careers'), + req.apiClient.get('/subjects') + ]); + if (carRes.status === 'fulfilled' && carRes.value.data) { + careers = carRes.value.data.careers || []; + } + if (subRes.status === 'fulfilled' && subRes.value.data) { + subjects = subRes.value.data.subjects || []; + } + } catch (e) { + console.warn('Could not fetch real careers/subjects for calendar filters:', e.message); + } + res.render('schedule/calendar', { title: 'Reservations Calendar - Edu-Space Admin', today_date: new Date().toISOString().split('T')[0], @@ -39,15 +56,8 @@ const handleCalendarView = async (req, res) => { capacity: c.capacity || 40 })), unassigned_commissions: unassignedCommissions, - subjects: [ - { id: 1, name: 'Arquitectura de Software', code: 'ARQ-101' }, - { id: 2, name: 'Bases de Datos II', code: 'BD-201' }, - { id: 3, name: 'Programación Avanzada', code: 'PRG-301' } - ], - careers: [ - { id: 1, name: 'Licenciatura en Sistemas' }, - { id: 2, name: 'Tecnicatura Universitaria en Desarrollo de Software' } - ], + subjects, + careers, buildings: Array.from(buildingsMap.values()), available_floors: Array.from(floorsSet).sort(), session: { get: (k, d) => d } @@ -89,27 +99,34 @@ const handleCalendarData = async (req, res) => { if (r.status === 'PENDING') eventColor = '#F59E0B'; else if (isVirtual) eventColor = '#6366F1'; + const subjectName = r.subject_name || r.purpose || 'Clase Regular'; + const subjectCode = r.subject_code || ''; + const careerName = (r.commission && r.commission.career_names) || (r.commission && r.commission.career_name) || r.career_names || r.career_name || ''; + const commissionCode = (r.commission && r.commission.code) || r.commission_code || ''; + const roomName = r.classroom_name || (r.classroom ? r.classroom.code : 'Aula'); + const locationDisplay = (r.classroom && r.classroom.location_display) || (r.classroom && r.classroom.building) || r.classroom_name || 'Edificio Central'; + return { id: r.id, - title: `${r.purpose || 'Clase Regular'} - ${r.classroom_name || 'Aula'}`, + title: `${subjectName} - ${roomName}`, start: r.start_time, end: r.end_time, backgroundColor: eventColor, borderColor: eventColor, extendedProps: { - subject_name: 'Arquitectura de Software', - subject_code: 'ARQ-101', - classroom: r.classroom_name || 'Aula Principal', + subject_name: subjectName, + subject_code: subjectCode, + classroom: roomName, is_virtual: isVirtual, - location_display: r.classroom_name || 'Edificio Central', - career: 'Licenciatura en Sistemas', - commission: 'COM-A', - shift: r.shift || 'Noche', + location_display: locationDisplay, + career: careerName, + commission: commissionCode, + shift: r.shift || 'Mañana', status: (r.status || 'CONFIRMED').toUpperCase(), - purpose: r.purpose || 'Clase Regular', - attendees: r.expected_attendees || 35, - teacher: r.teacher_name || 'Profesor Titular', - virtual_link: r.virtual_link || '', + purpose: r.purpose || subjectName, + attendees: r.expected_attendees || 30, + teacher: r.teacher_name || '', + virtual_link: r.effective_virtual_link || r.virtual_link || '', cancel_url: `/schedule/cancel_reservation?id=${r.id}` } }; @@ -528,11 +545,18 @@ const handleAddReservation = async (req, res) => { commission_id: commissionOptions }); + const classroomDataMap = {}; + classroomList.forEach(c => { classroomDataMap[c.id] = c; }); + const commissionDataMap = {}; + commissionList.forEach(c => { commissionDataMap[c.id] = c; }); + res.render('schedule/add', { title: 'New Reservation - Edu-Space Admin', form, classroom_list: classroomList, commission_list: commissionList, + classroom_data_json: JSON.stringify(classroomDataMap), + commission_data_json: JSON.stringify(commissionDataMap), buildings: Array.from(buildingsMap.values()), initial_commission_id: initialCommissionId, initial_classroom_id: initialClassroomId @@ -737,12 +761,19 @@ const handleEditReservation = async (req, res) => { commission_id: commissionOptions }); + const classroomDataMap = {}; + classroomList.forEach(c => { classroomDataMap[c.id] = c; }); + const commissionDataMap = {}; + commissionList.forEach(c => { commissionDataMap[c.id] = c; }); + res.render('schedule/edit', { title: `Modificar Reserva #${id} - Edu-Space Admin`, reservation, form, classroom_list: classroomList, commission_list: commissionList, + classroom_data_json: JSON.stringify(classroomDataMap), + commission_data_json: JSON.stringify(commissionDataMap), buildings: Array.from(buildingsMap.values()) }); } catch (error) { diff --git a/frontend/views/base.html b/frontend/views/base.html index 0323c23..e8ed2d5 100644 --- a/frontend/views/base.html +++ b/frontend/views/base.html @@ -1127,7 +1127,7 @@ diff --git a/frontend/views/buildings/list.html b/frontend/views/buildings/list.html index 4f58c73..f21f678 100644 --- a/frontend/views/buildings/list.html +++ b/frontend/views/buildings/list.html @@ -97,7 +97,7 @@
Pisos Presenciales
-

{{ buildings|sum(attribute='floors') }}

+

{{ total_floors or 4 }}

Plantas físicas activas
diff --git a/frontend/views/buildings/view.html b/frontend/views/buildings/view.html index a8542a5..2d8b100 100644 --- a/frontend/views/buildings/view.html +++ b/frontend/views/buildings/view.html @@ -97,27 +97,27 @@ {{ classrooms|length }} aulas configuradas
- {% if classrooms_by_floor %} - {% for floor_num in classrooms_by_floor|sort %} + {% if floors_list and (classrooms|length > 0) %} + {% for fl in floors_list %}
- {% if floor_num == 0 %}Planta Baja{% else %}Piso {{ floor_num }}{% endif %} + {{ fl.floor_name }}
- {{ classrooms_by_floor[floor_num]|length }} aulas + {{ fl.classrooms|length }} aula(s)
- {% for c in classrooms_by_floor[floor_num] %} + {% for c in fl.classrooms %}
- Capacidad: {{ c.capacity }} estudiantes + Capacidad: {{ c.capacity or 35 }} estudiantes
{% if c.description %} @@ -136,11 +136,14 @@ {% endif %}
- + Ver Ficha + + Reservar + {% if user.has_permission('classrooms', 'read_write') %} - + Editar {% endif %} diff --git a/frontend/views/classrooms/add.html b/frontend/views/classrooms/add.html index 4c42fe7..76de65a 100644 --- a/frontend/views/classrooms/add.html +++ b/frontend/views/classrooms/add.html @@ -195,10 +195,12 @@ document.addEventListener('DOMContentLoaded', function() { if (!floorDatalist) return; floorDatalist.innerHTML = ''; var floors = buildingFloors[bId] || []; - floors.forEach(function(f) { + var dynamicDefaults = ['Planta Baja (PB)', 'Entrepiso (EP)', 'Subsuelo', 'Piso 1', 'Piso 2', 'Piso 3', 'Piso 4']; + var allOptions = Array.from(new Set([...dynamicDefaults, ...floors])); + allOptions.forEach(function(f) { var opt = document.createElement('option'); opt.value = f; - opt.textContent = (f === '0' || f === 'PB') ? 'Planta Baja' : 'Piso ' + f; + opt.textContent = f; floorDatalist.appendChild(opt); }); } diff --git a/frontend/views/classrooms/edit.html b/frontend/views/classrooms/edit.html index 640ee23..66dbdf3 100644 --- a/frontend/views/classrooms/edit.html +++ b/frontend/views/classrooms/edit.html @@ -188,10 +188,12 @@ document.addEventListener('DOMContentLoaded', function() { if (!floorDatalist) return; floorDatalist.innerHTML = ''; var floors = buildingFloors[bId] || []; - floors.forEach(function(f) { + var dynamicDefaults = ['Planta Baja (PB)', 'Entrepiso (EP)', 'Subsuelo', 'Piso 1', 'Piso 2', 'Piso 3', 'Piso 4']; + var allOptions = Array.from(new Set([...dynamicDefaults, ...floors])); + allOptions.forEach(function(f) { var opt = document.createElement('option'); opt.value = f; - opt.textContent = (f === '0' || f === 'PB') ? 'Planta Baja' : 'Piso ' + f; + opt.textContent = f; floorDatalist.appendChild(opt); }); } diff --git a/frontend/views/classrooms/view.html b/frontend/views/classrooms/view.html index dcde145..1b6d48b 100644 --- a/frontend/views/classrooms/view.html +++ b/frontend/views/classrooms/view.html @@ -122,11 +122,11 @@ {% for res in upcoming_reservations %} -
- {{ res.start_time }} +
+ {{ res.date_display_friendly or res.date_display or res.start_time }}
-
- {{ res.start_time }} - {{ res.end_time }} hs +
+ {{ res.time_range_friendly or (res.start_time_display + ' a ' + res.end_time_display + ' hs') }}
diff --git a/frontend/views/schedule/add.html b/frontend/views/schedule/add.html index 8b7b7be..9582d06 100644 --- a/frontend/views/schedule/add.html +++ b/frontend/views/schedule/add.html @@ -248,36 +248,11 @@ {% block extra_js %}