From 173cdaa9524f3b2f6fc15da6961dec50e2cf50e9 Mon Sep 17 00:00:00 2001 From: Carlos Tello Date: Mon, 26 Oct 2026 18:53:44 -0300 Subject: [PATCH] feat(academic): allow subjects to be associated with multiple careers (v3.8.21) --- CHANGELOG.md | 9 ++ MEMORY.md | 23 ++-- backend/app/__init__.py | 2 +- backend/routers/academic.py | 22 ++-- backend/setup.py | 2 +- backend/tests/test_abm_endpoints.py | 56 ++++++++ frontend/package.json | 2 +- frontend/src/app.js | 6 +- frontend/src/routes/admin.js | 28 +++- frontend/views/admin/subjects/list.html | 165 ++++++++++++++++++++++-- 10 files changed, 273 insertions(+), 42 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c521195..0e7131e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,15 @@ 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.8.21] - 2026-10-26 +### Added & Improved +- **Gestión de Asignaturas: Asociación a Múltiples Carreras (`admin/subjects_list`)**: + - Reemplazado el selector simple de carrera por un componente de selección múltiple interactivo y responsivo tanto en la creación (`modalAddSubject`) como en la edición (`modalEditSubject`). + - Incorporado buscador rápido de carreras, botones de acción masiva ("Todas" / "Ninguna"), badges de código y contador dinámico de carreras seleccionadas. + - Sincronización completa en Frontend BFF (`handleSubjectAdd`, `handleSubjectEdit`) enviando arrays de `career_ids` y preservando `career_id` principal por compatibilidad relacional. + - Sincronización robusta en Backend FastAPI (`POST /subjects` y `PUT /subjects/{id}`), actualizando la relación Many-to-Many `Subject.careers` (tabla `subject_careers`). + - Suite de pruebas ampliada con `test_subject_multiple_careers_create_and_update` (80 tests 100% pasando). + ## [3.8.20] - 2026-10-26 ### Fixed & Improved - **Gestión de Comisiones: Visualización de Asignatura y Carreras Heredadas**: diff --git a/MEMORY.md b/MEMORY.md index 84c33df..e8ced30 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -9,17 +9,18 @@ Memoria del proyecto entre sesiones para la rama `dev`. - Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables. - Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación. - Reinicialización segura del sistema con contraseña de Administrador. -- **Sprint Activo: Corrección de Comisiones (Asignatura y Carreras Heredadas), Scoping de Roles y Libro de Calificaciones — v3.8.20**: - - **Asignatura y Carreras en Comisiones**: Corregido el mapeo en `admin/commissions_list` para que la columna "Asignatura" muestre destacadamente el nombre de la materia/asignatura real (`comm.subject.name or comm.subject_name`), junto con su código y las carreras que hereda la comisión. - - **Selector de Asignaturas en Modales de Alta y Edición**: `modalAddCommission` y `modalEditCommission` ahora cargan la lista de materias activas con sus planes y carreras asociadas, junto con un banner interactivo que previsualiza las carreras heredadas y enlace directo al catálogo de materias. - - **Enriquecimiento de Backend**: `Commission.to_dict()` expone `subject_name` y `subject_code`, y `GET /commissions` devuelve `subjects`, `careers` y `academic_terms` para evitar llamadas redundantes y asegurar dropdowns siempre poblados. - - **Scoping por Roles (Docente / Alumno / Bedelía)**: - - Docentes: Filtrado estricto en materias (`my_subjects`), reservas (`/schedule/list_reservations`) y aulas virtuales (`/classrooms/list_classrooms?view_mode=virtual`) para ver únicamente lo asignado a su usuario. - - Libro de Calificaciones: Habilitada la programación de evaluaciones (Parciales, TPs, Finales) mediante modal `#addMilestoneModal`, eliminación de hitos si el acta no está sellada, autocalculado de notas en vivo y guardado debounced. - - Alumnos: Visualización de materias inscritas y notas en `my_grades.html`. - - Eliminados fallbacks con datos mock/relleno en toda la plataforma. - - **QA & Seguridad**: 79 tests aprobados en `pytest` (100%), 0 vulnerabilidades en auditoría de seguridad (Bandit, pip-audit, njsscan, npm audit). - - **Versión Consolidada**: `v3.8.20`. +- **Sprint Activo: Asociación de Asignaturas a Múltiples Carreras y Enriquecimiento Académico — v3.8.21**: + - **Asociación Multicarrera de Asignaturas (`admin/subjects_list`)**: + - Reemplazado el selector simple de carrera por un componente interactivo de selección múltiple con buscador en tiempo real, botones masivos "Todas"/"Ninguna", badges de código y contador dinámico ("X seleccionadas"). + - Sincronización en modales `modalAddSubject` y `modalEditSubject` vía JavaScript nativo pre-poblando checkboxes a partir de `data-career-ids`. + - Adaptado el Frontend BFF (`admin.js`) para capturar arrays o valores únicos de `career_ids` y despacharlos al backend. + - Sincronización robusta en Backend FastAPI (`POST /subjects` y `PUT /subjects/{id}`), actualizando `subject.careers` (Many-to-Many `subject_careers`) y manteniendo `career_id` principal como fallback relacional. + - **Comisiones, Roles y Calificaciones (Consolidado de v3.8.20)**: + - Nombre de materia y badges de carreras heredadas en `admin/commissions_list`. + - Scoping estricto para Docentes y Alumnos (cero fallbacks mock). + - Gestión de hitos y actas en Gradebook. + - **QA & Seguridad**: 80 tests aprobados en `pytest` (100%), 0 vulnerabilidades en auditoría de seguridad (Bandit, pip-audit, njsscan, npm audit). + - **Versión Consolidada**: `v3.8.21`. ## Decisiones (y por qué) - **Flujo Secuencial de Bedelía (9 Pasos)**: Estandarizar la carga operativa en: 1) Sede -> 2) Aula -> 3) Ciclo Lectivo -> 4) Carrera -> 5) Materia (vinculada a Carrera) -> 6) Comisión (asociada a Materia, Carrera y Ciclo) -> 7) Profesores -> 8) Alumnos -> 9) Reserva de Espacio. Esto asegura consistencia e integridad relacional. diff --git a/backend/app/__init__.py b/backend/app/__init__.py index 23f5801..a9520c2 100644 --- a/backend/app/__init__.py +++ b/backend/app/__init__.py @@ -7,7 +7,7 @@ from typing import Any from database import db, get_db, engine, SessionLocal, session from config.config import Config -__version__ = "3.8.20" +__version__ = "3.8.21" class DummyContext: def __enter__(self): diff --git a/backend/routers/academic.py b/backend/routers/academic.py index c3d3ef6..8ce46cc 100644 --- a/backend/routers/academic.py +++ b/backend/routers/academic.py @@ -311,10 +311,6 @@ async def update_subject( except (ValueError, TypeError): pass - if 'career_id' in data: - c_id = data['career_id'] - subject.career_id = int(c_id) if c_id else None - if 'career_ids' in data: career_ids = data.get('career_ids') if isinstance(career_ids, str): @@ -326,14 +322,20 @@ async def update_subject( if c_id_list: c_objs = Career.query.filter(Career.id.in_(c_id_list)).all() subject.careers = c_objs - if c_objs and not subject.career_id: - subject.career_id = c_objs[0].id + if not subject.career_id or subject.career_id not in c_id_list: + subject.career_id = c_objs[0].id if c_objs else None + else: + subject.careers = [] + subject.career_id = None + elif 'career_id' in data: + c_id = data['career_id'] + subject.career_id = int(c_id) if c_id else None + if subject.career_id: + c_obj = Career.query.get(subject.career_id) + if c_obj: + subject.careers = [c_obj] else: subject.careers = [] - elif 'career_id' in data and subject.career_id: - c_obj = Career.query.get(subject.career_id) - if c_obj and c_obj not in subject.careers: - subject.careers = [c_obj] if 'description' in data: subject.description = (data['description'] or '').strip() diff --git a/backend/setup.py b/backend/setup.py index c436650..8654d94 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.8.20", + version="3.8.21", description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)", author="Edu-Space Development Team", author_email="admin@edu-space.com", diff --git a/backend/tests/test_abm_endpoints.py b/backend/tests/test_abm_endpoints.py index 4ce5bbd..b4fb53d 100644 --- a/backend/tests/test_abm_endpoints.py +++ b/backend/tests/test_abm_endpoints.py @@ -228,3 +228,59 @@ def test_system_reset_success_preserves_users(client, auth_headers): assert len(reset_logs) == 1 assert reset_logs[0].user_email == 'admin_abm@unicaba.edu.ar' + +def test_subject_multiple_careers_create_and_update(client, auth_headers): + from app.models.career import Career + + # 1. Crear carreras + c1 = Career(name='Licenciatura en Ciencia de Datos', code='DATOS') + c2 = Career(name='Tecnicatura en Videojuegos', code='VJ') + c3 = Career(name='Tecnicatura en Desarrollo Digital', code='TEC-DIG') + db.session.add_all([c1, c2, c3]) + db.session.commit() + + # 2. Crear una materia con múltiples carreras asociadas (c1 y c2) + payload_create = { + 'code': 'SUBJ-MULTI-1', + 'name': 'Programación Interactiva Avanzada', + 'credits': 4, + 'career_ids': [c1.id, c2.id], + 'department': 'Tecnología', + 'description': 'Materia compartida entre Datos y Videojuegos' + } + res_create = client.post('/api/v1/subjects', headers=auth_headers, json=payload_create) + assert res_create.status_code == 201 + data_create = res_create.get_json() + assert data_create['status'] == 'success' + subj_data = data_create['subject'] + assert subj_data['code'] == 'SUBJ-MULTI-1' + assert len(subj_data['careers']) == 2 + career_names = [c['name'] for c in subj_data['careers']] + assert 'Licenciatura en Ciencia de Datos' in career_names + assert 'Tecnicatura en Videojuegos' in career_names + + subj_id = subj_data['id'] + + # 3. Actualizar la materia para asociarla a c2 y c3 + payload_update = { + 'career_ids': [c2.id, c3.id], + 'description': 'Actualizada a Videojuegos y Desarrollo Digital' + } + res_update = client.put(f'/api/v1/subjects/{subj_id}', headers=auth_headers, json=payload_update) + assert res_update.status_code == 200 + data_update = res_update.get_json() + subj_updated = data_update['subject'] + assert len(subj_updated['careers']) == 2 + updated_career_names = [c['name'] for c in subj_updated['careers']] + assert 'Tecnicatura en Videojuegos' in updated_career_names + assert 'Tecnicatura en Desarrollo Digital' in updated_career_names + assert 'Licenciatura en Ciencia de Datos' not in updated_career_names + + # 4. Verificar que GET /subjects lista la materia con sus carreras + res_get = client.get('/api/v1/subjects', headers=auth_headers) + assert res_get.status_code == 200 + all_subjects = res_get.get_json()['subjects'] + found = next((s for s in all_subjects if s['id'] == subj_id), None) + assert found is not None + assert len(found['careers']) == 2 + diff --git a/frontend/package.json b/frontend/package.json index 6bf0571..91cd447 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,6 +1,6 @@ { "name": "frontend", - "version": "3.8.20", + "version": "3.8.21", "description": "", "main": "index.js", "scripts": { diff --git a/frontend/src/app.js b/frontend/src/app.js index 3c80ad6..8463993 100644 --- a/frontend/src/app.js +++ b/frontend/src/app.js @@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), { }); // Versiones institucionales del sistema -const APP_VERSION = '3.8.20'; -const FRONTEND_VERSION = '3.8.20'; -const BACKEND_VERSION = '3.8.20'; +const APP_VERSION = '3.8.21'; +const FRONTEND_VERSION = '3.8.21'; +const BACKEND_VERSION = '3.8.21'; env.addGlobal('app_version', APP_VERSION); env.addGlobal('frontend_version', FRONTEND_VERSION); diff --git a/frontend/src/routes/admin.js b/frontend/src/routes/admin.js index 2eb9e54..0d17276 100644 --- a/frontend/src/routes/admin.js +++ b/frontend/src/routes/admin.js @@ -962,14 +962,24 @@ const handleSubjectsList = async (req, res) => { }; const handleSubjectAdd = async (req, res) => { - const { code, name, department, credits, career_id, description, is_active } = req.body; + const { code, name, department, credits, description, is_active } = req.body; + let careerIds = []; + if (Array.isArray(req.body.career_ids)) { + careerIds = req.body.career_ids.map(id => parseInt(id, 10)).filter(id => !isNaN(id)); + } else if (req.body.career_ids) { + careerIds = [parseInt(req.body.career_ids, 10)].filter(id => !isNaN(id)); + } else if (req.body.career_id) { + careerIds = [parseInt(req.body.career_id, 10)].filter(id => !isNaN(id)); + } + try { await req.apiClient.post('/subjects', { code, name, department, credits: parseInt(credits, 10) || 4, - career_id: career_id ? parseInt(career_id, 10) : null, + career_id: careerIds.length > 0 ? careerIds[0] : null, + career_ids: careerIds, description, is_active: is_active === 'on' || is_active === 'true' || is_active === true }); @@ -983,14 +993,24 @@ const handleSubjectAdd = async (req, res) => { const handleSubjectEdit = async (req, res) => { const id = req.params.id || req.body.id; - const { code, name, department, credits, career_id, description, is_active } = req.body; + const { code, name, department, credits, description, is_active } = req.body; + let careerIds = []; + if (Array.isArray(req.body.career_ids)) { + careerIds = req.body.career_ids.map(cid => parseInt(cid, 10)).filter(cid => !isNaN(cid)); + } else if (req.body.career_ids) { + careerIds = [parseInt(req.body.career_ids, 10)].filter(cid => !isNaN(cid)); + } else if (req.body.career_id) { + careerIds = [parseInt(req.body.career_id, 10)].filter(cid => !isNaN(cid)); + } + try { await req.apiClient.put(`/subjects/${id}`, { code, name, department, credits: parseInt(credits, 10) || 4, - career_id: career_id ? parseInt(career_id, 10) : null, + career_id: careerIds.length > 0 ? careerIds[0] : null, + career_ids: careerIds, description, is_active: is_active === 'on' || is_active === 'true' || is_active === true }); diff --git a/frontend/views/admin/subjects/list.html b/frontend/views/admin/subjects/list.html index 1fd15fb..65f87ce 100644 --- a/frontend/views/admin/subjects/list.html +++ b/frontend/views/admin/subjects/list.html @@ -190,6 +190,7 @@ data-name="{{ s.name }}" data-credits="{{ s.credits }}" data-career-id="{{ s.career_id or '' }}" + data-career-ids="{% if s.careers %}{% for c in s.careers %}{{ c.id }}{% if not loop.last %},{% endif %}{% endfor %}{% elif s.career_id %}{{ s.career_id }}{% endif %}" data-department="{{ s.department or '' }}" data-description="{{ s.description or '' }}" data-active="{{ 'true' if s.is_active else 'false' }}" @@ -291,13 +292,33 @@
- - +
+ + +
+
+
{% for c in careers %} - +
+ + +
+ {% else %} +

No hay carreras registradas.

{% endfor %} - +
+ Podés seleccionar una o más carreras para asociar esta asignatura a múltiples planes de estudio.
@@ -345,13 +366,33 @@
- - +
+ + +
+
+
{% for c in careers %} - +
+ + +
+ {% else %} +

No hay carreras registradas.

{% endfor %} - +
+ Podés seleccionar una o más carreras para asociar esta asignatura a múltiples planes de estudio.
@@ -405,6 +446,93 @@