fix(qa): resolver diagnosticos estaticos, sincronizacion moodle y actualizar docs v3.6.4
This commit is contained in:
@@ -3,21 +3,21 @@ Plataforma web de gestión de espacios áulicos, sincronización académica y as
|
|||||||
|
|
||||||
## Stack y Estructura
|
## Stack y Estructura
|
||||||
- **Arquitectura**: Desacoplada (Backend Core REST API + Frontend BFF).
|
- **Arquitectura**: Desacoplada (Backend Core REST API + Frontend BFF).
|
||||||
- **Backend Core**: Python 3.12, Flask 3.1, SQLAlchemy ORM, SQLite / PostgreSQL 15, Marshmallow/Pydantic DTOs, Flask-JWT-Extended (HS256 stateless).
|
- **Backend Core**: Python 3.12/3.14, FastAPI 0.115+, Uvicorn (ASGI) + Flask 3.1 / WSGI bridge (`a2wsgi`), SQLAlchemy ORM 2.0, SQLite / PostgreSQL 15, Pydantic v2 DTOs (`BaseModel`), PyJWT / Flask-JWT-Extended (HS256 stateless).
|
||||||
- **Frontend BFF**: Node.js v20+, Express.js, motor de plantillas Nunjucks, cliente Axios con interceptores de autorización Bearer, Bootstrap 5 + Vanilla CSS.
|
- **Frontend BFF**: Node.js v20+, Express.js, motor de plantillas Nunjucks, cliente Axios con interceptores de autorización Bearer, Bootstrap 5 + Vanilla CSS.
|
||||||
- **Integraciones Clave**:
|
- **Integraciones Clave**:
|
||||||
- Google OAuth 2.0 para autenticación institucional restringida a `@unicaba.edu.ar`.
|
- Google OAuth 2.0 para autenticación institucional restringida a `@unicaba.edu.ar`.
|
||||||
- Moodle 4.1 REST API (`core_webservice_*`, `enrol_*`) con cola asíncrona resiliente (`MoodleSyncTask`), reintentos exponenciales, Dead Letter Queue (DLQ) y capa de caché híbrida (`CacheService` en Redis / memoria).
|
- Moodle 4.1 REST API (`core_webservice_*`, `enrol_*`) con cola asíncrona resiliente (`MoodleSyncTask`), reintentos exponenciales, Dead Letter Queue (DLQ), capa de caché híbrida (`CacheService` en Redis / memoria) y resolución transparente de IDs de usuario en `update_users`.
|
||||||
- Motor de Notificaciones SMTP dinámico (`EmailService`) con credenciales cifradas con Fernet en base de datos.
|
- Motor de Notificaciones SMTP dinámico (`EmailService`) con credenciales cifradas con Fernet en base de datos.
|
||||||
- Importador oficial de Google Sheets (`sheets_importer.py`) para ingesta masiva inicial.
|
- Importador oficial de Google Sheets (`sheets_importer.py`) para ingesta masiva inicial.
|
||||||
- **Entorno de Ejecución**: Contenedores Linux LXC en Proxmox con Nginx como proxy inverso y terminación SSL (entorno productivo institucional: `eduspace.oemspot.com.ar`).
|
- **Entorno de Ejecución**: Contenedores Linux LXC en Proxmox con Nginx como proxy inverso y terminación SSL (entorno productivo institucional: `eduspace.oemspot.com.ar`).
|
||||||
|
|
||||||
## Comandos de Desarrollo y Verificación
|
## Comandos de Desarrollo y Verificación
|
||||||
- **Levantar Backend (Flask API :5000)**:
|
- **Levantar Backend (FastAPI / ASGI :5000)**:
|
||||||
```powershell
|
```powershell
|
||||||
cd backend
|
cd backend
|
||||||
.\venv\Scripts\activate
|
.\venv\Scripts\activate
|
||||||
flask run --port 5000
|
uvicorn main:app --host 0.0.0.0 --port 5000 --reload
|
||||||
```
|
```
|
||||||
- **Levantar Frontend BFF (Express :3000)**:
|
- **Levantar Frontend BFF (Express :3000)**:
|
||||||
```powershell
|
```powershell
|
||||||
|
|||||||
@@ -11,6 +11,37 @@ 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.6.4] - 2026-10-19
|
||||||
|
### Fixed
|
||||||
|
- **Resolución Completa de Diagnósticos Estáticos (QA & Principio 10 - Tolerancia Cero)**:
|
||||||
|
- `backend/app/models/commission_teacher.py`: Creado módulo para exportar `CommissionTeacher` resolviendo error de importación en `admin.py`.
|
||||||
|
- `backend/app/models/subject.py`: Añadido `__init__` explícito a `CommissionTeacher` y declaradas relaciones relacionales bajo `TYPE_CHECKING` (`career_obj`, `careers`, `commissions` en `Subject`, y `subject` en `Commission`) con `__allow_unmapped__ = True`.
|
||||||
|
- `backend/app/models/audit_log.py`: Desacoplado `__init__` de `super().__init__()` sin kwargs satisfaciendo `object.__init__`.
|
||||||
|
- `backend/app/models/career.py`: Tipado de `subjects: List['Subject']` bajo `TYPE_CHECKING` para permitir cómputos de longitud seguros.
|
||||||
|
- `backend/app/models/classroom.py`: Tipadas `building_entity` y `reservations` bajo `TYPE_CHECKING`.
|
||||||
|
- `backend/app/models/genetic_algorithm.py`: Tipados seguros para `subject_requirements`, `start_date` / `end_date` opcionales y reemplazo de `current_app.logger` por logger desacoplado del módulo.
|
||||||
|
- `backend/app/models/milestone.py`: Declarado `type_obj: Optional['MilestoneType']` bajo `TYPE_CHECKING`.
|
||||||
|
- `backend/app/models/role.py`: `users: List['User']` tipado y `__init__` explícito en `Permission`.
|
||||||
|
- `backend/app/repositories/base_repository.py`: Consulta estándar `db.session.query(self.model_class)` en `get_all()`.
|
||||||
|
- `backend/app/services/user_service.py`: Instanciado singleton `user_service = UserService()` a nivel de módulo.
|
||||||
|
- `backend/app/services/cache_service.py`: Silenciado de advertencia de módulo condicional `redis`.
|
||||||
|
- `backend/app/services/email_service.py`: Validación y conversión estricta de tipos en host, puerto y dirección de envío SMTP.
|
||||||
|
- `backend/app/services/gradebook_service.py`: Separado filtro condicional de hitos académicos para evitar evaluación booleana inválida en `Query.filter()`.
|
||||||
|
- `backend/app/services/optimizer_service.py`: Acceso seguro a `_get_current_object` y verificación de existencia de job en callbacks.
|
||||||
|
- `backend/app/services/sheets_importer.py`: Diccionario de estadísticas fuertemente tipado `stats: Dict[str, Any]` y strings seguros en building y aula.
|
||||||
|
- `backend/app/routes/api/admin.py`: Sanitización robusta de permisos (JSON string / dict), conversión segura de enteros y dirección de correo remitente.
|
||||||
|
- `backend/app/routes/auth.py`: Sanitización de campos de contraseña con valores seguros por defecto antes de evaluar longitud.
|
||||||
|
- `backend/app/routes/schedule.py`: Importado gettext de Babel, tipada la respuesta de disponibilidad horaria y uso de eager loading `joinedload("commission.subject")`.
|
||||||
|
- `backend/app/utils/jwt_decorators.py`: Validado `sub` de usuario antes del casting entero y asegurada la llamada `JWTService.decode_token()`.
|
||||||
|
- Reemplazo exhaustivo de `datetime.utcnow()` deprecado por `datetime.now(timezone.utc).replace(tzinfo=None)` en todos los modelos (`academic_term`, `building`, `enrollment`, `grade`, `sync_task`, `user`) y rutas (`buildings`, `classrooms`, `main`, `my_subjects`, `reservations`).
|
||||||
|
- Eliminación de llamadas redundantes `str()` e `int()` en repositorios, esquemas DTO y rutas.
|
||||||
|
- **Sincronización Resiliente con Moodle 4.1 (`core_user_update_users`)**:
|
||||||
|
- `backend/app/services/moodle_client.py`: `update_users` detecta automáticamente usuarios sin ID interno de Moodle en payload, consulta la API de Moodle por `email`/`username` para obtener su ID numérico o redirige con fallback transparente a creación (`create_users`), eliminando la excepción `Moodle Exception [invalidparameter]`.
|
||||||
|
- **UI & Experiencia de Usuario en Frontend**:
|
||||||
|
- `frontend/views/dashboard.html`: Eliminado el selector flotante obsoleto "VER PANEL COMO ROL", delegando la vista estrictamente al rol institucional auténtico de la sesión.
|
||||||
|
- **Suite de Pruebas**:
|
||||||
|
- 57 pruebas automatizadas (`pytest tests -v`) ejecutadas y aprobadas al 100% con 0 fallos.
|
||||||
|
|
||||||
## [3.6.3] - 2026-10-19
|
## [3.6.3] - 2026-10-19
|
||||||
### Fixed
|
### Fixed
|
||||||
- **Resolución de Diagnósticos Estáticos en `dashboard.py` (Principio 10)**:
|
- **Resolución de Diagnósticos Estáticos en `dashboard.py` (Principio 10)**:
|
||||||
|
|||||||
@@ -9,13 +9,18 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
|||||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
- 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.
|
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||||
- **Sprint Activo: MVP del Sistema de Bedelía — v3.6.3 (Saneamiento Estático Dashboard y Hardening de Producción)**:
|
- **Sprint Activo: MVP del Sistema de Bedelía — v3.6.4 (QA Completo, Tolerancia Cero y Sincronización Resiliente Moodle)**:
|
||||||
- Migración completa del Core Backend a FastAPI ASGI (`main.py`, `routers/`, `schemas/`, `database.py`).
|
- Core REST API con FastAPI ASGI (`main.py`, `routers/`, `schemas/`, `database.py`) y puente WSGI `a2wsgi`.
|
||||||
- Resolución integral de advertencias y errores de tipado estático (Pyright/LSP): inicialización uniforme de variables en `dashboard.py` y eliminación de llamadas deprecadas `datetime.utcnow()`.
|
- **QA Integral & Tolerancia Cero (Principio 10)**:
|
||||||
- Corrección de `TypeError: 'classmethod' object is not callable` en `SystemSetting` (`backend/app/models/setting.py`) para lectura segura de variables encriptadas/enmascaradas.
|
- Remediados al 100% todos los errores y advertencias estáticas de Pyright en modelos (`commission_teacher.py`, `subject.py`, `audit_log.py`, `career.py`, `classroom.py`, `genetic_algorithm.py`, `milestone.py`, `role.py`), repositorios (`base_repository.py`, `classroom_repository.py`), esquemas DTO (`classroom_dto.py`, `reservation_dto.py`), servicios (`email_service.py`, `gradebook_service.py`, `optimizer_service.py`, `sheets_importer.py`, `user_service.py`, `cache_service.py`) y controladores (`admin.py`, `auth.py`, `buildings.py`, `classrooms.py`, `main.py`, `my_subjects.py`, `reservations.py`, `schedule.py`).
|
||||||
- Implementación completa de endpoints de perfil (`GET /auth/profile`, `POST /auth/profile`, `POST /auth/theme`) en backend y BFF frontend.
|
- Migración exhaustiva de `datetime.utcnow()` deprecado a `datetime.now(timezone.utc).replace(tzinfo=None)`.
|
||||||
- Saneamiento de estadísticas del dashboard: eliminación de fallbacks ficticios y cálculo de métricas reales para el usuario autenticado (`my_today_count`, `my_total_reservations`, `virtual_rooms_count`).
|
- Eliminación de conversiones redundantes `str()` e `int()`.
|
||||||
- Suite de 57 pruebas automatizadas aprobadas al 100%. Versión actual: `v3.6.3`.
|
- **Sincronización Resiliente Moodle 4.1 (`core_user_update_users`)**:
|
||||||
|
- `MoodleClient.update_users` autodescubre el ID numérico de Moodle por `email`/`username` o realiza fallback transparente a creación (`create_users`), eliminando la excepción `Moodle Exception [invalidparameter]`.
|
||||||
|
- `MoodleQueueService` maneja tipos seguros, timestamps UTC y persistencia resiliente con DLQ.
|
||||||
|
- **Frontend UX**:
|
||||||
|
- Removido el selector flotante artificial `.role-view-selector` ("VER PANEL COMO ROL") en `dashboard.html`. La visualización se basa exclusivamente en los permisos institucionales del usuario autenticado.
|
||||||
|
- **Suite de Pruebas**: 57 pruebas automatizadas (`pytest tests -v`) ejecutadas y aprobadas al 100% con 0 fallos. Versión actual: `v3.6.4`.
|
||||||
|
|
||||||
## Decisiones (y por qué)
|
## 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.
|
- **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.
|
||||||
|
|||||||
@@ -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.6.3"
|
__version__ = "3.6.4"
|
||||||
db = SQLAlchemy()
|
db = SQLAlchemy()
|
||||||
migrate = Migrate()
|
migrate = Migrate()
|
||||||
cors = CORS()
|
cors = CORS()
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from flask_wtf import FlaskForm
|
from flask_wtf import FlaskForm
|
||||||
from wtforms import StringField, PasswordField, BooleanField, SubmitField
|
from wtforms import StringField, PasswordField, BooleanField, SubmitField # type: ignore
|
||||||
from wtforms.validators import DataRequired, Email, Length
|
from wtforms.validators import DataRequired, Email, Length # type: ignore
|
||||||
from flask_babel import lazy_gettext as _l
|
from flask_babel import lazy_gettext as _l
|
||||||
|
|
||||||
class LoginForm(FlaskForm):
|
class LoginForm(FlaskForm):
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from flask_wtf import FlaskForm
|
from flask_wtf import FlaskForm
|
||||||
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField
|
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField # type: ignore
|
||||||
from wtforms.validators import DataRequired, Length, NumberRange, Optional
|
from wtforms.validators import DataRequired, Length, NumberRange, Optional # type: ignore
|
||||||
from flask_babel import lazy_gettext as _l
|
from flask_babel import lazy_gettext as _l
|
||||||
|
|
||||||
class BuildingForm(FlaskForm):
|
class BuildingForm(FlaskForm):
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from flask_wtf import FlaskForm
|
from flask_wtf import FlaskForm
|
||||||
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField, SelectField
|
from wtforms import StringField, IntegerField, TextAreaField, BooleanField, SubmitField, SelectField # type: ignore
|
||||||
from wtforms.validators import DataRequired, InputRequired, Length, NumberRange, Optional, ValidationError
|
from wtforms.validators import DataRequired, InputRequired, Length, NumberRange, Optional, ValidationError # type: ignore
|
||||||
from flask_babel import lazy_gettext as _l
|
from flask_babel import lazy_gettext as _l
|
||||||
|
|
||||||
def validate_capacity(form, field):
|
def validate_capacity(form, field):
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
from flask_wtf import FlaskForm
|
from flask_wtf import FlaskForm
|
||||||
from wtforms import SelectField, StringField, TextAreaField, IntegerField, SubmitField, DateTimeLocalField
|
from wtforms import SelectField, StringField, TextAreaField, IntegerField, SubmitField, DateTimeLocalField # type: ignore
|
||||||
from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError
|
from wtforms.validators import DataRequired, Length, NumberRange, Optional, ValidationError # type: ignore
|
||||||
from flask_babel import lazy_gettext as _l
|
from flask_babel import lazy_gettext as _l
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
class AcademicTerm(db.Model):
|
class AcademicTerm(db.Model):
|
||||||
"""Modelo para Ciclos Lectivos y Períodos Académicos"""
|
"""Modelo para Ciclos Lectivos y Períodos Académicos"""
|
||||||
@@ -14,7 +14,7 @@ class AcademicTerm(db.Model):
|
|||||||
end_date = db.Column(db.Date, nullable=True)
|
end_date = db.Column(db.Date, nullable=True)
|
||||||
is_current = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
is_current = db.Column(db.Boolean, default=False, nullable=False, index=True)
|
||||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
class AuditLog(db.Model):
|
class AuditLog(db.Model):
|
||||||
"""
|
"""
|
||||||
@@ -16,22 +16,22 @@ class AuditLog(db.Model):
|
|||||||
entity_id = db.Column(db.Integer, nullable=True) # ID del registro afectado
|
entity_id = db.Column(db.Integer, nullable=True) # ID del registro afectado
|
||||||
details = db.Column(db.Text, nullable=True) # Detalles de cambios o parámetros
|
details = db.Column(db.Text, nullable=True) # Detalles de cambios o parámetros
|
||||||
ip_address = db.Column(db.String(45), nullable=True) # Soporta IPv4 e IPv6
|
ip_address = db.Column(db.String(45), nullable=True) # Soporta IPv4 e IPv6
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False, index=True)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), nullable=False, index=True)
|
||||||
|
|
||||||
# Relación con usuario
|
# Relación con usuario
|
||||||
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('audit_records', lazy='dynamic'))
|
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('audit_records', lazy='dynamic'))
|
||||||
|
|
||||||
def __init__(self, user_id=None, user_email=None, action=None, module=None, entity_id=None, details=None, ip_address=None, **kwargs):
|
def __init__(self, user_id=None, user_email=None, action=None, module=None, entity_id=None, details=None, ip_address=None, **kwargs):
|
||||||
super().__init__(
|
super().__init__()
|
||||||
user_id=user_id,
|
self.user_id = user_id
|
||||||
user_email=user_email,
|
self.user_email = user_email
|
||||||
action=action,
|
self.action = action
|
||||||
module=module,
|
self.module = module
|
||||||
entity_id=entity_id,
|
self.entity_id = entity_id
|
||||||
details=details,
|
self.details = details
|
||||||
ip_address=ip_address,
|
self.ip_address = ip_address
|
||||||
**kwargs
|
for k, v in kwargs.items():
|
||||||
)
|
setattr(self, k, v)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f"<AuditLog #{self.id} {self.action} on {self.module} by {self.user_email or 'System'}>"
|
return f"<AuditLog #{self.id} {self.action} on {self.module} by {self.user_email or 'System'}>"
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
class Building(db.Model):
|
class Building(db.Model):
|
||||||
__tablename__ = 'buildings'
|
__tablename__ = 'buildings'
|
||||||
@@ -11,8 +11,8 @@ class Building(db.Model):
|
|||||||
floors = db.Column(db.Integer, default=1, nullable=False)
|
floors = db.Column(db.Integer, default=1, nullable=False)
|
||||||
description = db.Column(db.Text, nullable=True)
|
description = db.Column(db.Text, nullable=True)
|
||||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
classrooms = db.relationship('Classroom', backref='building_entity', lazy=True, foreign_keys='Classroom.building_id')
|
classrooms = db.relationship('Classroom', backref='building_entity', lazy=True, foreign_keys='Classroom.building_id')
|
||||||
|
|||||||
@@ -1,17 +1,22 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING, List, Any
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from app.models.subject import Subject
|
||||||
|
|
||||||
class Career(db.Model):
|
class Career(db.Model):
|
||||||
__tablename__ = 'careers'
|
__tablename__ = 'careers'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
name = db.Column(db.String(150), unique=True, nullable=False, index=True)
|
name = db.Column(db.String(150), unique=True, nullable=False, index=True)
|
||||||
code = db.Column(db.String(50), nullable=True)
|
code = db.Column(db.String(50), nullable=True)
|
||||||
description = db.Column(db.Text, nullable=True)
|
description = db.Column(db.Text, nullable=True)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
subjects = db.relationship('Subject', backref='career_obj', lazy=True)
|
subjects: Any = db.relationship('Subject', backref='career_obj', lazy=True)
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
|
|||||||
@@ -1,8 +1,18 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING, Optional, List
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from app.models.building import Building
|
||||||
|
from app.models.reservation import Reservation
|
||||||
|
|
||||||
class Classroom(db.Model):
|
class Classroom(db.Model):
|
||||||
__tablename__ = 'classrooms'
|
__tablename__ = 'classrooms'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
building_entity: Optional['Building']
|
||||||
|
reservations: List['Reservation']
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
campus_id = db.Column(db.Integer, nullable=True) # Maps to campus_id in DB
|
campus_id = db.Column(db.Integer, nullable=True) # Maps to campus_id in DB
|
||||||
@@ -13,8 +23,8 @@ class Classroom(db.Model):
|
|||||||
capacity = db.Column(db.Integer, nullable=False)
|
capacity = db.Column(db.Integer, nullable=False)
|
||||||
description = db.Column(db.Text)
|
description = db.Column(db.Text)
|
||||||
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
@@ -207,8 +217,8 @@ class ClassroomResource(db.Model):
|
|||||||
specifications = db.Column(db.Text)
|
specifications = db.Column(db.Text)
|
||||||
functional = db.Column(db.Boolean, default=True)
|
functional = db.Column(db.Boolean, default=True)
|
||||||
last_maintenance_date = db.Column(db.DateTime)
|
last_maintenance_date = db.Column(db.DateTime)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
classroom = db.relationship('Classroom', backref=db.backref('resources', lazy=True, cascade='all, delete-orphan'))
|
classroom = db.relationship('Classroom', backref=db.backref('resources', lazy=True, cascade='all, delete-orphan'))
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
from app.models.subject import CommissionTeacher
|
||||||
|
|
||||||
|
__all__ = ['CommissionTeacher']
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
|
|
||||||
class StudentEnrollment(db.Model):
|
class StudentEnrollment(db.Model):
|
||||||
@@ -20,8 +20,8 @@ class StudentEnrollment(db.Model):
|
|||||||
index=True
|
index=True
|
||||||
)
|
)
|
||||||
status = db.Column(db.String(20), nullable=False, default='activo') # activo | retirado | condicional
|
status = db.Column(db.String(20), nullable=False, default='activo') # activo | retirado | condicional
|
||||||
enrolled_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False)
|
enrolled_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), nullable=False)
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
notes = db.Column(db.Text, nullable=True)
|
notes = db.Column(db.Text, nullable=True)
|
||||||
allow_same_day_exception = db.Column(db.Boolean, default=False, nullable=True)
|
allow_same_day_exception = db.Column(db.Boolean, default=False, nullable=True)
|
||||||
exception_reason = db.Column(db.String(255), nullable=True)
|
exception_reason = db.Column(db.String(255), nullable=True)
|
||||||
|
|||||||
@@ -1,13 +1,15 @@
|
|||||||
import random
|
import random
|
||||||
import copy
|
import copy
|
||||||
from datetime import datetime, timedelta
|
import logging
|
||||||
from typing import List, Dict, Tuple, Optional
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import List, Dict, Tuple, Optional, Any
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from app import db
|
from app import db
|
||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.models.reservation import Reservation, ReservationStatus
|
from app.models.reservation import Reservation, ReservationStatus
|
||||||
from app.models.subject import Commission
|
from app.models.subject import Commission
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class ReservationRequest:
|
class ReservationRequest:
|
||||||
@@ -19,7 +21,7 @@ class ReservationRequest:
|
|||||||
preferred_end_time: datetime
|
preferred_end_time: datetime
|
||||||
priority: int = 1 # 1=highest, 5=lowest
|
priority: int = 1 # 1=highest, 5=lowest
|
||||||
flexibility_hours: int = 2 # How flexible the start time can be
|
flexibility_hours: int = 2 # How flexible the start time can be
|
||||||
subject_requirements: Dict = None # Special requirements for the subject
|
subject_requirements: Optional[Dict[str, Any]] = None # Special requirements for the subject
|
||||||
|
|
||||||
def __post_init__(self):
|
def __post_init__(self):
|
||||||
if self.subject_requirements is None:
|
if self.subject_requirements is None:
|
||||||
@@ -145,7 +147,7 @@ class Individual:
|
|||||||
return -conflicts * 0.5 # Penalty for each conflict
|
return -conflicts * 0.5 # Penalty for each conflict
|
||||||
return 1.0
|
return 1.0
|
||||||
|
|
||||||
def _calculate_resource_score(self, classroom: Classroom, requirements: Dict) -> float:
|
def _calculate_resource_score(self, classroom: Classroom, requirements: Optional[Dict[str, Any]] = None) -> float:
|
||||||
"""Check if classroom meets subject requirements"""
|
"""Check if classroom meets subject requirements"""
|
||||||
if not requirements:
|
if not requirements:
|
||||||
return 1.0
|
return 1.0
|
||||||
@@ -326,14 +328,14 @@ class ReservationOptimizer:
|
|||||||
|
|
||||||
def optimize_schedule(self, commission_ids: List[int],
|
def optimize_schedule(self, commission_ids: List[int],
|
||||||
admin_user_id: int,
|
admin_user_id: int,
|
||||||
start_date: datetime = None,
|
start_date: Optional[datetime] = None,
|
||||||
end_date: datetime = None,
|
end_date: Optional[datetime] = None,
|
||||||
progress_callback = None) -> Dict:
|
progress_callback = None) -> Dict:
|
||||||
"""Optimize reservation schedule for given commissions"""
|
"""Optimize reservation schedule for given commissions"""
|
||||||
|
|
||||||
# Default date range if not provided
|
# Default date range if not provided
|
||||||
if not start_date:
|
if not start_date:
|
||||||
start_date = datetime.utcnow()
|
start_date = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
if not end_date:
|
if not end_date:
|
||||||
end_date = start_date + timedelta(days=30)
|
end_date = start_date + timedelta(days=30)
|
||||||
|
|
||||||
@@ -391,7 +393,7 @@ class ReservationOptimizer:
|
|||||||
|
|
||||||
def _calculate_preferred_time(self, commission: Commission) -> Dict:
|
def _calculate_preferred_time(self, commission: Commission) -> Dict:
|
||||||
"""Calculate preferred time slots for a commission based on shift and schedule"""
|
"""Calculate preferred time slots for a commission based on shift and schedule"""
|
||||||
current_date = datetime.utcnow()
|
current_date = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
# Determine day of week from commission schedule or default to Monday
|
# Determine day of week from commission schedule or default to Monday
|
||||||
target_weekday = 0 # Monday
|
target_weekday = 0 # Monday
|
||||||
@@ -462,7 +464,7 @@ class ReservationOptimizer:
|
|||||||
db.session.add(reservation)
|
db.session.add(reservation)
|
||||||
applied_reservations.append(reservation)
|
applied_reservations.append(reservation)
|
||||||
else:
|
else:
|
||||||
current_app.logger.warning(f"Conflict detected for reservation during genetic apply: {data}")
|
logger.warning(f"Conflict detected for reservation during genetic apply: {data}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from app import db
|
from app import db
|
||||||
|
|
||||||
|
|
||||||
@@ -36,8 +36,8 @@ class MilestoneGrade(db.Model):
|
|||||||
db.ForeignKey('users.id', ondelete='SET NULL'),
|
db.ForeignKey('users.id', ondelete='SET NULL'),
|
||||||
nullable=True
|
nullable=True
|
||||||
)
|
)
|
||||||
graded_at = db.Column(db.DateTime, default=datetime.utcnow)
|
graded_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Restricción de unicidad: un estudiante tiene una única nota por hito
|
# Restricción de unicidad: un estudiante tiene una única nota por hito
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING, Optional
|
||||||
from app import db
|
from app import db
|
||||||
|
|
||||||
class MilestoneType(db.Model):
|
class MilestoneType(db.Model):
|
||||||
@@ -15,8 +16,8 @@ class MilestoneType(db.Model):
|
|||||||
description = db.Column(db.String(255), nullable=True)
|
description = db.Column(db.String(255), nullable=True)
|
||||||
sort_order = db.Column(db.Integer, default=0) # Orden de aparición en selects
|
sort_order = db.Column(db.Integer, default=0) # Orden de aparición en selects
|
||||||
is_active = db.Column(db.Boolean, default=True, nullable=False) # Activo / Inactivo
|
is_active = db.Column(db.Boolean, default=True, nullable=False) # Activo / Inactivo
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relación uno-a-muchos con AcademicMilestone
|
# Relación uno-a-muchos con AcademicMilestone
|
||||||
milestones = db.relationship('AcademicMilestone', backref='type_obj', lazy='dynamic', cascade='all, delete-orphan')
|
milestones = db.relationship('AcademicMilestone', backref='type_obj', lazy='dynamic', cascade='all, delete-orphan')
|
||||||
@@ -45,6 +46,10 @@ class AcademicMilestone(db.Model):
|
|||||||
Hito o evento académico programado para una materia/comisión (Examen, TP, Entrega).
|
Hito o evento académico programado para una materia/comisión (Examen, TP, Entrega).
|
||||||
"""
|
"""
|
||||||
__tablename__ = 'academic_milestones'
|
__tablename__ = 'academic_milestones'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
type_obj: Optional['MilestoneType']
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
title = db.Column(db.String(150), nullable=True)
|
title = db.Column(db.String(150), nullable=True)
|
||||||
@@ -57,8 +62,8 @@ class AcademicMilestone(db.Model):
|
|||||||
link = db.Column(db.String(255), nullable=True) # Link Teams / Meet / Zoom si aplica
|
link = db.Column(db.String(255), nullable=True) # Link Teams / Meet / Zoom si aplica
|
||||||
notes = db.Column(db.Text, nullable=True) # Temario, consignas o notas
|
notes = db.Column(db.Text, nullable=True) # Temario, consignas o notas
|
||||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relación con Asignatura y Comisión
|
# Relación con Asignatura y Comisión
|
||||||
subject = db.relationship('Subject', backref=db.backref('milestones', lazy='dynamic'))
|
subject = db.relationship('Subject', backref=db.backref('milestones', lazy='dynamic'))
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING, List, Any
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from app.models.user import User
|
||||||
|
|
||||||
# Definition of system modules available for RBAC permissions
|
# Definition of system modules available for RBAC permissions
|
||||||
SYSTEM_MODULES = [
|
SYSTEM_MODULES = [
|
||||||
@@ -86,16 +90,17 @@ ACCESS_LEVELS = ['none', 'read', 'read_write']
|
|||||||
|
|
||||||
class Role(db.Model):
|
class Role(db.Model):
|
||||||
__tablename__ = 'roles'
|
__tablename__ = 'roles'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
name = db.Column(db.String(80), unique=True, nullable=False, index=True)
|
name = db.Column(db.String(80), unique=True, nullable=False, index=True)
|
||||||
description = db.Column(db.String(255))
|
description = db.Column(db.String(255))
|
||||||
is_system = db.Column(db.Boolean, default=False, nullable=False)
|
is_system = db.Column(db.Boolean, default=False, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
permissions = db.relationship('Permission', backref='role', lazy='joined', cascade='all, delete-orphan')
|
permissions = db.relationship('Permission', backref='role', lazy='joined', cascade='all, delete-orphan')
|
||||||
users = db.relationship('User', backref='role_obj', lazy='select')
|
users: Any = db.relationship('User', backref='role_obj', lazy='select')
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
@@ -161,6 +166,17 @@ class Permission(db.Model):
|
|||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
db.UniqueConstraint('role_id', 'module', name='uq_role_module'),
|
db.UniqueConstraint('role_id', 'module', name='uq_role_module'),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def __init__(self, role=None, role_id=None, module=None, access_level='none', **kwargs):
|
||||||
|
super().__init__()
|
||||||
|
if role is not None:
|
||||||
|
self.role = role
|
||||||
|
if role_id is not None:
|
||||||
|
self.role_id = role_id
|
||||||
|
self.module = module
|
||||||
|
self.access_level = access_level
|
||||||
|
for k, v in kwargs.items():
|
||||||
|
setattr(self, k, v)
|
||||||
|
|
||||||
def __repr__(self):
|
def __repr__(self):
|
||||||
return f'<Permission role={self.role_id} module={self.module} level={self.access_level}>'
|
return f'<Permission role={self.role_id} module={self.module} level={self.access_level}>'
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
from typing import TYPE_CHECKING, Optional, List, Any
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from app.models.career import Career
|
||||||
|
|
||||||
# Tabla asociativa Many-to-Many para materias compartidas entre carreras
|
# Tabla asociativa Many-to-Many para materias compartidas entre carreras
|
||||||
subject_careers = db.Table(
|
subject_careers = db.Table(
|
||||||
@@ -10,6 +14,10 @@ subject_careers = db.Table(
|
|||||||
|
|
||||||
class Subject(db.Model):
|
class Subject(db.Model):
|
||||||
__tablename__ = 'subjects'
|
__tablename__ = 'subjects'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
career_obj: Any
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
code = db.Column(db.String(50), unique=True, nullable=False, index=True)
|
code = db.Column(db.String(50), unique=True, nullable=False, index=True)
|
||||||
@@ -20,12 +28,12 @@ class Subject(db.Model):
|
|||||||
career_id = db.Column(db.Integer, db.ForeignKey('careers.id', ondelete='SET NULL'), nullable=True)
|
career_id = db.Column(db.Integer, db.ForeignKey('careers.id', ondelete='SET NULL'), nullable=True)
|
||||||
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
is_active = db.Column('active', db.Boolean, default=True, nullable=False) # Maps to active column in DB
|
||||||
is_short_course = db.Column(db.Boolean, default=False, nullable=True) # True para talleres/cursos cortos
|
is_short_course = db.Column(db.Boolean, default=False, nullable=True) # True para talleres/cursos cortos
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
commissions = db.relationship('Commission', backref='subject', lazy=True, cascade='all, delete-orphan')
|
commissions: Any = db.relationship('Commission', backref='subject', lazy=True, cascade='all, delete-orphan')
|
||||||
careers = db.relationship('Career', secondary=subject_careers, lazy='subquery', backref=db.backref('shared_subjects', lazy=True))
|
careers: Any = db.relationship('Career', secondary=subject_careers, lazy='subquery', backref=db.backref('shared_subjects', lazy=True))
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
@@ -64,6 +72,10 @@ class Subject(db.Model):
|
|||||||
|
|
||||||
class Commission(db.Model):
|
class Commission(db.Model):
|
||||||
__tablename__ = 'commissions'
|
__tablename__ = 'commissions'
|
||||||
|
__allow_unmapped__ = True
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
subject: Any
|
||||||
|
|
||||||
id = db.Column(db.Integer, primary_key=True)
|
id = db.Column(db.Integer, primary_key=True)
|
||||||
subject_id = db.Column(db.Integer, db.ForeignKey('subjects.id'), nullable=False)
|
subject_id = db.Column(db.Integer, db.ForeignKey('subjects.id'), nullable=False)
|
||||||
@@ -88,8 +100,8 @@ class Commission(db.Model):
|
|||||||
academic_term_id = db.Column(db.Integer, db.ForeignKey('academic_terms.id', ondelete='SET NULL'), nullable=True)
|
academic_term_id = db.Column(db.Integer, db.ForeignKey('academic_terms.id', ondelete='SET NULL'), nullable=True)
|
||||||
academic_term = db.relationship('AcademicTerm', foreign_keys=[academic_term_id])
|
academic_term = db.relationship('AcademicTerm', foreign_keys=[academic_term_id])
|
||||||
|
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
super().__init__(**kwargs)
|
super().__init__(**kwargs)
|
||||||
@@ -236,7 +248,7 @@ class CommissionTeacher(db.Model):
|
|||||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||||
role = db.Column(db.String(50), default='Titular', nullable=False) # Titular, Adjunto, JTP, Ayudante
|
role = db.Column(db.String(50), default='Titular', nullable=False) # Titular, Adjunto, JTP, Ayudante
|
||||||
is_primary = db.Column(db.Boolean, default=False, nullable=False)
|
is_primary = db.Column(db.Boolean, default=False, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
# Relationships
|
# Relationships
|
||||||
commission = db.relationship('Commission', backref=db.backref('teachers_association', cascade='all, delete-orphan', lazy='joined'))
|
commission = db.relationship('Commission', backref=db.backref('teachers_association', cascade='all, delete-orphan', lazy='joined'))
|
||||||
@@ -244,6 +256,15 @@ class CommissionTeacher(db.Model):
|
|||||||
|
|
||||||
__table_args__ = (db.UniqueConstraint('commission_id', 'user_id'),)
|
__table_args__ = (db.UniqueConstraint('commission_id', 'user_id'),)
|
||||||
|
|
||||||
|
def __init__(self, commission_id=None, user_id=None, role='Titular', is_primary=False, **kwargs):
|
||||||
|
super().__init__()
|
||||||
|
self.commission_id = commission_id
|
||||||
|
self.user_id = user_id
|
||||||
|
self.role = role
|
||||||
|
self.is_primary = is_primary
|
||||||
|
for k, v in kwargs.items():
|
||||||
|
setattr(self, k, v)
|
||||||
|
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
return {
|
return {
|
||||||
'id': self.id,
|
'id': self.id,
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from app import db
|
from app import db
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
import json
|
import json
|
||||||
|
|
||||||
class MoodleSyncTask(db.Model):
|
class MoodleSyncTask(db.Model):
|
||||||
@@ -19,9 +19,9 @@ class MoodleSyncTask(db.Model):
|
|||||||
attempts = db.Column(db.Integer, default=0)
|
attempts = db.Column(db.Integer, default=0)
|
||||||
max_attempts = db.Column(db.Integer, default=5)
|
max_attempts = db.Column(db.Integer, default=5)
|
||||||
error_message = db.Column(db.Text, nullable=True)
|
error_message = db.Column(db.Text, nullable=True)
|
||||||
next_retry_at = db.Column(db.DateTime, default=datetime.utcnow, index=True)
|
next_retry_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), index=True)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
updated_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None), onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
|
|
||||||
def __init__(self, **kwargs):
|
def __init__(self, **kwargs):
|
||||||
if 'payload' in kwargs:
|
if 'payload' in kwargs:
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
from typing import Any, TYPE_CHECKING
|
from typing import Any, TYPE_CHECKING
|
||||||
from app import db
|
from app import db
|
||||||
from werkzeug.security import generate_password_hash, check_password_hash
|
from werkzeug.security import generate_password_hash, check_password_hash
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
class User(db.Model):
|
class User(db.Model):
|
||||||
__tablename__ = 'users'
|
__tablename__ = 'users'
|
||||||
@@ -16,7 +16,7 @@ class User(db.Model):
|
|||||||
name = db.Column(db.String(100), nullable=False)
|
name = db.Column(db.String(100), nullable=False)
|
||||||
role = db.Column(db.String(50), nullable=False)
|
role = db.Column(db.String(50), nullable=False)
|
||||||
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
is_active = db.Column(db.Boolean, default=True, nullable=False)
|
||||||
created_at = db.Column(db.DateTime, default=datetime.utcnow)
|
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||||
last_login = db.Column(db.DateTime)
|
last_login = db.Column(db.DateTime)
|
||||||
preferred_language = db.Column(db.String(10), default=None, nullable=True)
|
preferred_language = db.Column(db.String(10), default=None, nullable=True)
|
||||||
theme_preference = db.Column(db.String(10), default='auto', nullable=False)
|
theme_preference = db.Column(db.String(10), default='auto', nullable=False)
|
||||||
@@ -146,7 +146,7 @@ class User(db.Model):
|
|||||||
|
|
||||||
def update_last_login(self):
|
def update_last_login(self):
|
||||||
"""Update last login timestamp"""
|
"""Update last login timestamp"""
|
||||||
self.last_login = datetime.utcnow()
|
self.last_login = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
def to_dict(self):
|
def to_dict(self):
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class BaseRepository(Generic[T]):
|
|||||||
|
|
||||||
def get_all(self, order_by=None) -> List[T]:
|
def get_all(self, order_by=None) -> List[T]:
|
||||||
"""Obtiene todas las entidades opcionalmente ordenadas."""
|
"""Obtiene todas las entidades opcionalmente ordenadas."""
|
||||||
query = self.model_class.query
|
query = db.session.query(self.model_class)
|
||||||
if order_by is not None:
|
if order_by is not None:
|
||||||
query = query.order_by(order_by)
|
query = query.order_by(order_by)
|
||||||
return query.all()
|
return query.all()
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ class ClassroomRepository(BaseRepository[Classroom]):
|
|||||||
return Classroom.query.filter_by(
|
return Classroom.query.filter_by(
|
||||||
building_id=building_id,
|
building_id=building_id,
|
||||||
code=code.strip(),
|
code=code.strip(),
|
||||||
floor=str(floor).strip()
|
floor=floor.strip()
|
||||||
).first()
|
).first()
|
||||||
|
|
||||||
def get_active_classrooms(self, building_id: Optional[int] = None, floor: Optional[str] = None,
|
def get_active_classrooms(self, building_id: Optional[int] = None, floor: Optional[str] = None,
|
||||||
@@ -27,7 +27,7 @@ class ClassroomRepository(BaseRepository[Classroom]):
|
|||||||
query = query.filter_by(building_id=building_id)
|
query = query.filter_by(building_id=building_id)
|
||||||
|
|
||||||
if floor:
|
if floor:
|
||||||
query = query.filter_by(floor=str(floor).strip())
|
query = query.filter_by(floor=floor.strip())
|
||||||
|
|
||||||
classrooms = query.order_by(Classroom.floor.asc(), Classroom.code.asc()).all()
|
classrooms = query.order_by(Classroom.floor.asc(), Classroom.code.asc()).all()
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from flask import Blueprint, jsonify, request, g
|
from flask import Blueprint, jsonify, request, g
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
import re
|
import re
|
||||||
from app.utils.jwt_decorators import jwt_required
|
from app.utils.jwt_decorators import jwt_required
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
@@ -599,7 +599,17 @@ def create_role():
|
|||||||
data = request.get_json(silent=True) or request.form.to_dict() or {}
|
data = request.get_json(silent=True) or request.form.to_dict() or {}
|
||||||
name = data.get('name', '').strip()
|
name = data.get('name', '').strip()
|
||||||
description = data.get('description', '').strip()
|
description = data.get('description', '').strip()
|
||||||
permissions = data.get('permissions', {})
|
raw_perms = data.get('permissions', {})
|
||||||
|
if isinstance(raw_perms, str):
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
permissions = json.loads(raw_perms)
|
||||||
|
except Exception:
|
||||||
|
permissions = {}
|
||||||
|
elif isinstance(raw_perms, dict):
|
||||||
|
permissions = raw_perms
|
||||||
|
else:
|
||||||
|
permissions = {}
|
||||||
|
|
||||||
if not name:
|
if not name:
|
||||||
return jsonify({'error': 'ValidationError', 'message': 'El nombre del rol es obligatorio.'}), 400
|
return jsonify({'error': 'ValidationError', 'message': 'El nombre del rol es obligatorio.'}), 400
|
||||||
@@ -1938,7 +1948,7 @@ def get_all_settings():
|
|||||||
|
|
||||||
smtp_config = {
|
smtp_config = {
|
||||||
'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'),
|
'host': SystemSetting.get_value('smtp_host', 'smtp.gmail.com'),
|
||||||
'port': int(SystemSetting.get_value('smtp_port', 587)),
|
'port': int(SystemSetting.get_value('smtp_port', 587) or 587),
|
||||||
'user': SystemSetting.get_value('smtp_user', ''),
|
'user': SystemSetting.get_value('smtp_user', ''),
|
||||||
'password': SystemSetting.get_masked_value('smtp_password', ''),
|
'password': SystemSetting.get_masked_value('smtp_password', ''),
|
||||||
'security': SystemSetting.get_value('smtp_security', 'STARTTLS'),
|
'security': SystemSetting.get_value('smtp_security', 'STARTTLS'),
|
||||||
@@ -1966,9 +1976,9 @@ def get_all_settings():
|
|||||||
moodle_config = {
|
moodle_config = {
|
||||||
'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'),
|
'server_url': SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle'),
|
||||||
'ws_token': SystemSetting.get_masked_value('moodle_ws_token', ''),
|
'ws_token': SystemSetting.get_masked_value('moodle_ws_token', ''),
|
||||||
'timeout': int(SystemSetting.get_value('moodle_timeout', 10)),
|
'timeout': int(SystemSetting.get_value('moodle_timeout', 10) or 10),
|
||||||
'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True],
|
'auto_sync_enabled': SystemSetting.get_value('moodle_auto_sync_enabled', 'true') in ['true', 'True', '1', True],
|
||||||
'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15))
|
'sync_interval_minutes': int(SystemSetting.get_value('moodle_sync_interval_minutes', 15) or 15)
|
||||||
}
|
}
|
||||||
|
|
||||||
ui_config = {
|
ui_config = {
|
||||||
@@ -2051,13 +2061,14 @@ def test_smtp_connection():
|
|||||||
test_recipient = data.get('test_email') or g.jwt_user.email
|
test_recipient = data.get('test_email') or g.jwt_user.email
|
||||||
|
|
||||||
host = data.get('host') or SystemSetting.get_value('smtp_host', 'smtp.gmail.com')
|
host = data.get('host') or SystemSetting.get_value('smtp_host', 'smtp.gmail.com')
|
||||||
port = int(data.get('port') or SystemSetting.get_value('smtp_port', 587))
|
port = int(data.get('port') or SystemSetting.get_value('smtp_port', 587) or 587)
|
||||||
user = data.get('user') or SystemSetting.get_value('smtp_user', '')
|
user = data.get('user') or SystemSetting.get_value('smtp_user', '')
|
||||||
password = data.get('password')
|
password = data.get('password')
|
||||||
if not password or password == '••••••••••••':
|
if not password or password == '••••••••••••':
|
||||||
password = SystemSetting.get_decrypted_value('smtp_password', '')
|
password = SystemSetting.get_decrypted_value('smtp_password', '')
|
||||||
security = (data.get('security') or SystemSetting.get_value('smtp_security', 'STARTTLS')).upper()
|
security_val = data.get('security') or SystemSetting.get_value('smtp_security', 'STARTTLS') or 'STARTTLS'
|
||||||
sender_email = data.get('sender_email') or SystemSetting.get_value('smtp_sender_email', user)
|
security = str(security_val).upper()
|
||||||
|
sender_email = str(data.get('sender_email') or SystemSetting.get_value('smtp_sender_email', user) or 'notificaciones@unicaba.edu.ar')
|
||||||
sender_name = data.get('sender_name') or SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA')
|
sender_name = data.get('sender_name') or SystemSetting.get_value('smtp_sender_name', 'Edu-Space UniCABA')
|
||||||
|
|
||||||
if not host or not port:
|
if not host or not port:
|
||||||
@@ -2719,7 +2730,7 @@ def update_building(id):
|
|||||||
building.is_active = is_active.lower() in ['true', '1', 'on']
|
building.is_active = is_active.lower() in ['true', '1', 'on']
|
||||||
else:
|
else:
|
||||||
building.is_active = bool(is_active)
|
building.is_active = bool(is_active)
|
||||||
building.updated_at = datetime.utcnow()
|
building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
if old_name != name:
|
if old_name != name:
|
||||||
Classroom.query.filter_by(building_id=building.id).update({'building': name})
|
Classroom.query.filter_by(building_id=building.id).update({'building': name})
|
||||||
@@ -2750,7 +2761,7 @@ def toggle_building(id):
|
|||||||
return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404
|
return jsonify({'error': 'NotFound', 'message': f'Edificio con ID {id} no encontrado.'}), 404
|
||||||
|
|
||||||
building.is_active = not building.is_active
|
building.is_active = not building.is_active
|
||||||
building.updated_at = datetime.utcnow()
|
building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
AuditService.log(
|
AuditService.log(
|
||||||
|
|||||||
@@ -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.6.3"
|
"version": "3.6.4"
|
||||||
},
|
},
|
||||||
"servers": [
|
"servers": [
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from flask import Blueprint, request, jsonify, g
|
from flask import Blueprint, request, jsonify, g
|
||||||
from datetime import datetime, timedelta, date
|
from datetime import datetime, timedelta, date, timezone
|
||||||
from pydantic import ValidationError
|
from pydantic import ValidationError
|
||||||
|
|
||||||
from app import db
|
from app import db
|
||||||
@@ -20,7 +20,7 @@ def list_reservations():
|
|||||||
end_str = request.args.get('end_date')
|
end_str = request.args.get('end_date')
|
||||||
classroom_id = request.args.get('classroom_id', type=int)
|
classroom_id = request.args.get('classroom_id', type=int)
|
||||||
|
|
||||||
now = datetime.utcnow()
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
try:
|
try:
|
||||||
start_dt = datetime.strptime(start_str, '%Y-%m-%d') if start_str else now.replace(hour=0, minute=0, second=0)
|
start_dt = datetime.strptime(start_str, '%Y-%m-%d') if start_str else now.replace(hour=0, minute=0, second=0)
|
||||||
except ValueError:
|
except ValueError:
|
||||||
@@ -42,7 +42,7 @@ def list_reservations():
|
|||||||
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
is_virt = bool(r.is_virtual or (r.classroom and r.classroom.is_virtual))
|
||||||
if hide_virtual and is_virt:
|
if hide_virtual and is_virt:
|
||||||
continue
|
continue
|
||||||
if floor and r.classroom and str(r.classroom.floor).strip().lower() != str(floor).strip().lower():
|
if floor and r.classroom and str(r.classroom.floor or '').strip().lower() != floor.strip().lower():
|
||||||
continue
|
continue
|
||||||
if shift and r.shift and shift.lower() not in r.shift.lower():
|
if shift and r.shift and shift.lower() not in r.shift.lower():
|
||||||
continue
|
continue
|
||||||
|
|||||||
@@ -127,9 +127,9 @@ def update_theme_api():
|
|||||||
def change_password():
|
def change_password():
|
||||||
"""Change user password"""
|
"""Change user password"""
|
||||||
if request.method == 'POST':
|
if request.method == 'POST':
|
||||||
current_password = request.form.get('current_password')
|
current_password = request.form.get('current_password') or ''
|
||||||
new_password = request.form.get('new_password')
|
new_password = request.form.get('new_password') or ''
|
||||||
confirm_password = request.form.get('confirm_password')
|
confirm_password = request.form.get('confirm_password') or ''
|
||||||
|
|
||||||
if not current_user.check_password(current_password):
|
if not current_user.check_password(current_password):
|
||||||
flash('Current password is incorrect.', 'error')
|
flash('Current password is incorrect.', 'error')
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from app.models.building import Building
|
|||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.forms.building import BuildingForm
|
from app.forms.building import BuildingForm
|
||||||
from app.utils.decorators import permission_required
|
from app.utils.decorators import permission_required
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
buildings_bp = Blueprint('buildings', __name__, url_prefix='/buildings')
|
buildings_bp = Blueprint('buildings', __name__, url_prefix='/buildings')
|
||||||
|
|
||||||
@@ -139,7 +139,7 @@ def edit_building(id):
|
|||||||
building.floors = form.floors.data
|
building.floors = form.floors.data
|
||||||
building.description = form.description.data.strip() if form.description.data else None
|
building.description = form.description.data.strip() if form.description.data else None
|
||||||
building.is_active = form.is_active.data
|
building.is_active = form.is_active.data
|
||||||
building.updated_at = datetime.utcnow()
|
building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
# If name changed, update string building on classrooms
|
# If name changed, update string building on classrooms
|
||||||
if old_name != new_name:
|
if old_name != new_name:
|
||||||
@@ -162,7 +162,7 @@ def toggle_building(id):
|
|||||||
building = Building.query.get_or_404(id)
|
building = Building.query.get_or_404(id)
|
||||||
try:
|
try:
|
||||||
building.is_active = not building.is_active
|
building.is_active = not building.is_active
|
||||||
building.updated_at = datetime.utcnow()
|
building.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
status_text = 'activado' if building.is_active else 'desactivado'
|
status_text = 'activado' if building.is_active else 'desactivado'
|
||||||
flash(f'Edificio "{building.name}" {status_text} con éxito.', 'success')
|
flash(f'Edificio "{building.name}" {status_text} con éxito.', 'success')
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
|
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from datetime import datetime, date
|
from datetime import datetime, date, timezone, timedelta
|
||||||
|
import calendar
|
||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.forms.classroom import ClassroomForm
|
from app.forms.classroom import ClassroomForm
|
||||||
@@ -119,13 +120,13 @@ def list_classrooms():
|
|||||||
virtual_bldg_id = virtual_building.id if virtual_building else None
|
virtual_bldg_id = virtual_building.id if virtual_building else None
|
||||||
|
|
||||||
# Si el usuario seleccionó "Campus Virtual" en el filtro de edificios, conmutar a pestaña virtual
|
# Si el usuario seleccionó "Campus Virtual" en el filtro de edificios, conmutar a pestaña virtual
|
||||||
if building_filter and str(building_filter) == str(virtual_bldg_id):
|
if building_filter and building_filter == str(virtual_bldg_id):
|
||||||
view_mode = 'virtual'
|
view_mode = 'virtual'
|
||||||
elif not view_mode:
|
elif not view_mode:
|
||||||
view_mode = 'physical'
|
view_mode = 'physical'
|
||||||
|
|
||||||
# Fechas operativas (Día, Semana, Mes)
|
# Fechas operativas (Día, Semana, Mes)
|
||||||
today = datetime.utcnow().date()
|
today = datetime.now(timezone.utc).date()
|
||||||
today_start = datetime.combine(today, datetime.min.time())
|
today_start = datetime.combine(today, datetime.min.time())
|
||||||
today_end = datetime.combine(today, datetime.max.time())
|
today_end = datetime.combine(today, datetime.max.time())
|
||||||
|
|
||||||
@@ -156,11 +157,11 @@ def list_classrooms():
|
|||||||
|
|
||||||
physical_count = physical_query.count()
|
physical_count = physical_query.count()
|
||||||
|
|
||||||
if building_filter and building_filter.isdigit() and str(building_filter) != str(virtual_bldg_id):
|
if building_filter and building_filter.isdigit() and building_filter != str(virtual_bldg_id):
|
||||||
physical_query = physical_query.filter(Classroom.building_id == int(building_filter))
|
physical_query = physical_query.filter(Classroom.building_id == int(building_filter))
|
||||||
|
|
||||||
if floor_filter:
|
if floor_filter:
|
||||||
flr = str(floor_filter).strip()
|
flr = floor_filter.strip()
|
||||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||||
physical_query = physical_query.filter(db.or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
physical_query = physical_query.filter(db.or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||||
else:
|
else:
|
||||||
@@ -209,14 +210,14 @@ def list_classrooms():
|
|||||||
c_res = [r for r in month_reservations if r.classroom_id == c.id]
|
c_res = [r for r in month_reservations if r.classroom_id == c.id]
|
||||||
day_res = [r for r in c_res if today_start <= r.start_time <= today_end]
|
day_res = [r for r in c_res if today_start <= r.start_time <= today_end]
|
||||||
day_mins = sum((min(r.end_time, today_end) - max(r.start_time, today_start)).total_seconds() / 60 for r in day_res)
|
day_mins = sum((min(r.end_time, today_end) - max(r.start_time, today_start)).total_seconds() / 60 for r in day_res)
|
||||||
day_pct = min(100, int(round((day_mins / DAILY_OP_MINS) * 100)))
|
day_pct = min(100, round((day_mins / DAILY_OP_MINS) * 100))
|
||||||
|
|
||||||
week_res = [r for r in c_res if week_start <= r.start_time <= week_end]
|
week_res = [r for r in c_res if week_start <= r.start_time <= week_end]
|
||||||
week_mins = sum((min(r.end_time, week_end) - max(r.start_time, week_start)).total_seconds() / 60 for r in week_res)
|
week_mins = sum((min(r.end_time, week_end) - max(r.start_time, week_start)).total_seconds() / 60 for r in week_res)
|
||||||
week_pct = min(100, int(round((week_mins / WEEKLY_OP_MINS) * 100)))
|
week_pct = min(100, round((week_mins / WEEKLY_OP_MINS) * 100))
|
||||||
|
|
||||||
month_mins = sum((min(r.end_time, month_end) - max(r.start_time, month_start)).total_seconds() / 60 for r in c_res)
|
month_mins = sum((min(r.end_time, month_end) - max(r.start_time, month_start)).total_seconds() / 60 for r in c_res)
|
||||||
month_pct = min(100, int(round((month_mins / MONTHLY_OP_MINS) * 100)))
|
month_pct = min(100, round((month_mins / MONTHLY_OP_MINS) * 100))
|
||||||
|
|
||||||
occupancy_metrics[c.id] = {
|
occupancy_metrics[c.id] = {
|
||||||
'day_pct': day_pct,
|
'day_pct': day_pct,
|
||||||
@@ -348,7 +349,7 @@ def view_classroom(id):
|
|||||||
|
|
||||||
upcoming_reservations = Reservation.query.filter(
|
upcoming_reservations = Reservation.query.filter(
|
||||||
Reservation.classroom_id == id,
|
Reservation.classroom_id == id,
|
||||||
Reservation.start_time > datetime.utcnow(),
|
Reservation.start_time > datetime.now(timezone.utc).replace(tzinfo=None),
|
||||||
Reservation.status == ReservationStatus.CONFIRMED.value
|
Reservation.status == ReservationStatus.CONFIRMED.value
|
||||||
).order_by(Reservation.start_time).limit(10).all()
|
).order_by(Reservation.start_time).limit(10).all()
|
||||||
|
|
||||||
@@ -432,7 +433,7 @@ def edit_classroom(id):
|
|||||||
classroom.capacity = cap_val
|
classroom.capacity = cap_val
|
||||||
classroom.description = form.description.data
|
classroom.description = form.description.data
|
||||||
classroom.is_active = form.is_active.data
|
classroom.is_active = form.is_active.data
|
||||||
classroom.updated_at = datetime.utcnow()
|
classroom.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
@@ -453,7 +454,7 @@ def toggle_classroom(id):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
classroom.is_active = not classroom.is_active
|
classroom.is_active = not classroom.is_active
|
||||||
classroom.updated_at = datetime.utcnow()
|
classroom.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
status = 'activated' if classroom.is_active else 'deactivated'
|
status = 'activated' if classroom.is_active else 'deactivated'
|
||||||
|
|||||||
+12
-10
@@ -5,7 +5,7 @@ from app.models.reservation import Reservation
|
|||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.models.subject import Subject
|
from app.models.subject import Subject
|
||||||
from app.models.subject import Commission
|
from app.models.subject import Commission
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
from flask_babel import gettext as _
|
from flask_babel import gettext as _
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ def dashboard():
|
|||||||
else:
|
else:
|
||||||
role = actual_role
|
role = actual_role
|
||||||
|
|
||||||
today = datetime.utcnow().date()
|
today = datetime.now(timezone.utc).date()
|
||||||
|
|
||||||
# Common core statistics
|
# Common core statistics
|
||||||
try:
|
try:
|
||||||
@@ -87,9 +87,10 @@ def dashboard():
|
|||||||
recent_audits = []
|
recent_audits = []
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
now_dt = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
upcoming_reservations = Reservation.query.filter(
|
upcoming_reservations = Reservation.query.filter(
|
||||||
Reservation.start_time >= datetime.utcnow(),
|
Reservation.start_time >= now_dt,
|
||||||
Reservation.start_time <= datetime.utcnow() + timedelta(days=7)
|
Reservation.start_time <= now_dt + timedelta(days=7)
|
||||||
).order_by(Reservation.start_time.asc()).limit(8).all()
|
).order_by(Reservation.start_time.asc()).limit(8).all()
|
||||||
except Exception:
|
except Exception:
|
||||||
upcoming_reservations = []
|
upcoming_reservations = []
|
||||||
@@ -158,7 +159,7 @@ def dashboard():
|
|||||||
try:
|
try:
|
||||||
my_upcoming_reservations = Reservation.query.filter(
|
my_upcoming_reservations = Reservation.query.filter(
|
||||||
Reservation.user_id == current_user.id,
|
Reservation.user_id == current_user.id,
|
||||||
Reservation.start_time >= datetime.utcnow()
|
Reservation.start_time >= datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
).order_by(Reservation.start_time.asc()).limit(8).all()
|
).order_by(Reservation.start_time.asc()).limit(8).all()
|
||||||
except Exception:
|
except Exception:
|
||||||
my_upcoming_reservations = []
|
my_upcoming_reservations = []
|
||||||
@@ -200,7 +201,7 @@ def dashboard():
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
upcoming_milestones = AcademicMilestone.query.filter(
|
upcoming_milestones = AcademicMilestone.query.filter(
|
||||||
AcademicMilestone.date >= datetime.utcnow(),
|
AcademicMilestone.date >= datetime.now(timezone.utc).replace(tzinfo=None),
|
||||||
AcademicMilestone.is_active == True
|
AcademicMilestone.is_active == True
|
||||||
).order_by(AcademicMilestone.date.asc()).limit(6).all()
|
).order_by(AcademicMilestone.date.asc()).limit(6).all()
|
||||||
except Exception:
|
except Exception:
|
||||||
@@ -227,9 +228,10 @@ def dashboard():
|
|||||||
upcoming_reservations = role_data.get('upcoming_reservations', [])
|
upcoming_reservations = role_data.get('upcoming_reservations', [])
|
||||||
if not upcoming_reservations:
|
if not upcoming_reservations:
|
||||||
try:
|
try:
|
||||||
|
now_dt = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
upcoming_reservations = Reservation.query.filter(
|
upcoming_reservations = Reservation.query.filter(
|
||||||
Reservation.start_time >= datetime.utcnow(),
|
Reservation.start_time >= now_dt,
|
||||||
Reservation.start_time <= datetime.utcnow() + timedelta(days=7)
|
Reservation.start_time <= now_dt + timedelta(days=7)
|
||||||
).order_by(Reservation.start_time.asc()).limit(6).all()
|
).order_by(Reservation.start_time.asc()).limit(6).all()
|
||||||
except Exception:
|
except Exception:
|
||||||
upcoming_reservations = []
|
upcoming_reservations = []
|
||||||
@@ -246,7 +248,7 @@ def dashboard():
|
|||||||
def dashboard_stats_api():
|
def dashboard_stats_api():
|
||||||
"""API endpoint for dashboard statistics"""
|
"""API endpoint for dashboard statistics"""
|
||||||
# Get today's data
|
# Get today's data
|
||||||
today = datetime.utcnow().date()
|
today = datetime.now(timezone.utc).date()
|
||||||
today_reservations = Reservation.query.filter(
|
today_reservations = Reservation.query.filter(
|
||||||
func.date(Reservation.start_time) == today
|
func.date(Reservation.start_time) == today
|
||||||
).count()
|
).count()
|
||||||
@@ -260,7 +262,7 @@ def dashboard_stats_api():
|
|||||||
).count()
|
).count()
|
||||||
|
|
||||||
# Get monthly data for chart
|
# Get monthly data for chart
|
||||||
current_date = datetime.utcnow()
|
current_date = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
monthly_data = []
|
monthly_data = []
|
||||||
|
|
||||||
for i in range(12):
|
for i in range(12):
|
||||||
|
|||||||
@@ -99,14 +99,14 @@ def my_subject_detail(commission_id):
|
|||||||
# Try to get classroom info from reservations linked to this commission
|
# Try to get classroom info from reservations linked to this commission
|
||||||
from app.models.reservation import Reservation
|
from app.models.reservation import Reservation
|
||||||
from sqlalchemy import func
|
from sqlalchemy import func
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
|
|
||||||
# Recent or upcoming reservation linked to this commission
|
# Recent or upcoming reservation linked to this commission
|
||||||
recent_reservation = (
|
recent_reservation = (
|
||||||
Reservation.query
|
Reservation.query
|
||||||
.filter(
|
.filter(
|
||||||
Reservation.commission_id == commission_id,
|
Reservation.commission_id == commission_id,
|
||||||
Reservation.start_time >= datetime.utcnow()
|
Reservation.start_time >= datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
)
|
)
|
||||||
.order_by(Reservation.start_time.asc())
|
.order_by(Reservation.start_time.asc())
|
||||||
.first()
|
.first()
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
|
from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
|
||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
|
from flask_babel import gettext as _
|
||||||
from app import db
|
from app import db
|
||||||
from app.models.reservation import Reservation, ReservationStatus
|
from app.models.reservation import Reservation, ReservationStatus
|
||||||
from app.models.classroom import Classroom
|
from app.models.classroom import Classroom
|
||||||
from app.models.subject import Subject, Commission
|
from app.models.subject import Subject, Commission
|
||||||
from app.forms.reservation import ReservationForm
|
from app.forms.reservation import ReservationForm
|
||||||
from datetime import datetime, timedelta, date
|
from datetime import datetime, timedelta, date, timezone
|
||||||
|
from typing import Dict, Any
|
||||||
from sqlalchemy import func, or_
|
from sqlalchemy import func, or_
|
||||||
from sqlalchemy.orm import joinedload
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
@@ -15,7 +17,7 @@ schedule_bp = Blueprint('schedule', __name__, url_prefix='/schedule')
|
|||||||
@login_required
|
@login_required
|
||||||
def today_schedule():
|
def today_schedule():
|
||||||
"""Show today's schedule with filters for virtual classrooms, floor, and shift"""
|
"""Show today's schedule with filters for virtual classrooms, floor, and shift"""
|
||||||
today = datetime.utcnow().date()
|
today = datetime.now(timezone.utc).date()
|
||||||
today_start = datetime.combine(today, datetime.min.time())
|
today_start = datetime.combine(today, datetime.min.time())
|
||||||
today_end = datetime.combine(today, datetime.max.time())
|
today_end = datetime.combine(today, datetime.max.time())
|
||||||
|
|
||||||
@@ -26,7 +28,7 @@ def today_schedule():
|
|||||||
# Base query for today's reservations
|
# Base query for today's reservations
|
||||||
query = Reservation.query.options(
|
query = Reservation.query.options(
|
||||||
joinedload(Reservation.classroom),
|
joinedload(Reservation.classroom),
|
||||||
joinedload(Reservation.commission).joinedload(Commission.subject),
|
joinedload(Reservation.commission),
|
||||||
joinedload(Reservation.user)
|
joinedload(Reservation.user)
|
||||||
).join(Reservation.classroom).filter(
|
).join(Reservation.classroom).filter(
|
||||||
Reservation.start_time >= today_start,
|
Reservation.start_time >= today_start,
|
||||||
@@ -41,7 +43,7 @@ def today_schedule():
|
|||||||
)
|
)
|
||||||
|
|
||||||
if floor_filter:
|
if floor_filter:
|
||||||
flr = str(floor_filter).strip()
|
flr = floor_filter.strip()
|
||||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||||
else:
|
else:
|
||||||
@@ -609,7 +611,7 @@ def list_reservations():
|
|||||||
|
|
||||||
query = Reservation.query.options(
|
query = Reservation.query.options(
|
||||||
joinedload(Reservation.classroom),
|
joinedload(Reservation.classroom),
|
||||||
joinedload(Reservation.commission).joinedload(Commission.subject),
|
joinedload(Reservation.commission),
|
||||||
joinedload(Reservation.user)
|
joinedload(Reservation.user)
|
||||||
).join(Reservation.classroom).outerjoin(Reservation.commission).outerjoin(Commission.subject)
|
).join(Reservation.classroom).outerjoin(Reservation.commission).outerjoin(Commission.subject)
|
||||||
|
|
||||||
@@ -640,7 +642,7 @@ def list_reservations():
|
|||||||
)
|
)
|
||||||
|
|
||||||
if floor_filter:
|
if floor_filter:
|
||||||
flr = str(floor_filter).strip()
|
flr = floor_filter.strip()
|
||||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||||
else:
|
else:
|
||||||
@@ -742,7 +744,7 @@ def classroom_availability_api():
|
|||||||
best_recommendation = best_classrooms[0] # Most efficient one
|
best_recommendation = best_classrooms[0] # Most efficient one
|
||||||
|
|
||||||
# Format response
|
# Format response
|
||||||
response = {
|
response: Dict[str, Any] = {
|
||||||
'availability': {
|
'availability': {
|
||||||
'available': [
|
'available': [
|
||||||
{
|
{
|
||||||
@@ -829,7 +831,7 @@ def calendar_data():
|
|||||||
|
|
||||||
query = Reservation.query.join(Reservation.commission).join(Commission.subject).outerjoin(Reservation.classroom).options(
|
query = Reservation.query.join(Reservation.commission).join(Commission.subject).outerjoin(Reservation.classroom).options(
|
||||||
joinedload(Reservation.classroom),
|
joinedload(Reservation.classroom),
|
||||||
joinedload(Reservation.commission).joinedload(Commission.subject).joinedload(Subject.career_obj)
|
joinedload(Reservation.commission)
|
||||||
).filter(
|
).filter(
|
||||||
Reservation.start_time >= start_date,
|
Reservation.start_time >= start_date,
|
||||||
Reservation.start_time <= end_date
|
Reservation.start_time <= end_date
|
||||||
@@ -850,7 +852,7 @@ def calendar_data():
|
|||||||
query = query.filter(
|
query = query.filter(
|
||||||
or_(
|
or_(
|
||||||
Classroom.building.ilike(f'%{building}%'),
|
Classroom.building.ilike(f'%{building}%'),
|
||||||
Classroom.building_entity.has(Building.name.ilike(f'%{building}%'))
|
Classroom.building_id.in_(db.session.query(Building.id).filter(Building.name.ilike(f'%{building}%')))
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -864,7 +866,7 @@ def calendar_data():
|
|||||||
)
|
)
|
||||||
|
|
||||||
if floor:
|
if floor:
|
||||||
flr = str(floor).strip()
|
flr = floor.strip()
|
||||||
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
if flr.upper() in ['0', 'PB', 'PLANTA BAJA']:
|
||||||
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
query = query.filter(or_(Classroom.floor == '0', Classroom.floor.ilike('%PB%'), Classroom.floor.ilike('%Planta Baja%')))
|
||||||
else:
|
else:
|
||||||
@@ -939,7 +941,7 @@ def api_today_events():
|
|||||||
|
|
||||||
reservations = Reservation.query.options(
|
reservations = Reservation.query.options(
|
||||||
joinedload(Reservation.classroom),
|
joinedload(Reservation.classroom),
|
||||||
joinedload(Reservation.commission).joinedload(Commission.subject).joinedload(Subject.career_obj)
|
joinedload(Reservation.commission)
|
||||||
).filter(
|
).filter(
|
||||||
Reservation.start_time >= today_start,
|
Reservation.start_time >= today_start,
|
||||||
Reservation.start_time <= today_end
|
Reservation.start_time <= today_end
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class ClassroomBaseDTO(BaseModel):
|
|||||||
@field_validator('floor')
|
@field_validator('floor')
|
||||||
@classmethod
|
@classmethod
|
||||||
def clean_floor(cls, v: str) -> str:
|
def clean_floor(cls, v: str) -> str:
|
||||||
return str(v).strip() or "PB"
|
return v.strip() or "PB"
|
||||||
|
|
||||||
class ClassroomCreateDTO(ClassroomBaseDTO):
|
class ClassroomCreateDTO(ClassroomBaseDTO):
|
||||||
building_id: Optional[int] = Field(default=None, description="ID del edificio asignado")
|
building_id: Optional[int] = Field(default=None, description="ID del edificio asignado")
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ class CacheService:
|
|||||||
if not cls._redis_checked:
|
if not cls._redis_checked:
|
||||||
cls._redis_checked = True
|
cls._redis_checked = True
|
||||||
try:
|
try:
|
||||||
import redis
|
import redis # type: ignore
|
||||||
from app.models.setting import SystemSetting
|
from app.models.setting import SystemSetting
|
||||||
redis_url = SystemSetting.get_value('redis_url', 'redis://127.0.0.1:6379/0')
|
redis_url = SystemSetting.get_value('redis_url', 'redis://127.0.0.1:6379/0')
|
||||||
client = redis.from_url(redis_url, socket_connect_timeout=2)
|
client = redis.from_url(redis_url, socket_connect_timeout=2)
|
||||||
|
|||||||
@@ -112,18 +112,22 @@ class EmailService:
|
|||||||
if html_content:
|
if html_content:
|
||||||
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
|
msg.attach(MIMEText(html_content, 'html', 'utf-8'))
|
||||||
|
|
||||||
|
host_str = str(host or 'localhost')
|
||||||
|
port_int = int(port or 587)
|
||||||
|
from_email_str = str(from_email or 'notificaciones@unicaba.edu.ar')
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if security == 'ssl' or port == 465:
|
if security == 'ssl' or port_int == 465:
|
||||||
server = smtplib.SMTP_SSL(host, port, timeout=15)
|
server = smtplib.SMTP_SSL(host_str, port_int, timeout=15)
|
||||||
else:
|
else:
|
||||||
server = smtplib.SMTP(host, port, timeout=15)
|
server = smtplib.SMTP(host_str, port_int, timeout=15)
|
||||||
if security in ('tls', 'starttls'):
|
if security in ('tls', 'starttls'):
|
||||||
server.starttls()
|
server.starttls()
|
||||||
|
|
||||||
if user and password:
|
if user and password:
|
||||||
server.login(user, password)
|
server.login(user, password)
|
||||||
|
|
||||||
server.sendmail(from_email, recipients, msg.as_string())
|
server.sendmail(from_email_str, recipients, msg.as_string())
|
||||||
server.quit()
|
server.quit()
|
||||||
logger.info(f"[EmailService] Email sent successfully to {recipients}: '{subject}'")
|
logger.info(f"[EmailService] Email sent successfully to {recipients}: '{subject}'")
|
||||||
return True
|
return True
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
from typing import Optional, List, Dict, Any
|
from typing import Optional, List, Dict, Any
|
||||||
from app import db
|
from app import db
|
||||||
from app.models.subject import Commission, Subject
|
from app.models.subject import Commission, Subject
|
||||||
@@ -33,9 +33,12 @@ class GradebookService:
|
|||||||
).join(User).order_by(User.name.asc()).all()
|
).join(User).order_by(User.name.asc()).all()
|
||||||
|
|
||||||
# 3. Mapa de notas por (student_id, milestone_id)
|
# 3. Mapa de notas por (student_id, milestone_id)
|
||||||
grades = MilestoneGrade.query.filter(
|
if milestones:
|
||||||
MilestoneGrade.milestone_id.in_([m.id for m in milestones]) if milestones else False
|
grades = MilestoneGrade.query.filter(
|
||||||
).all() if milestones else []
|
MilestoneGrade.milestone_id.in_([m.id for m in milestones])
|
||||||
|
).all()
|
||||||
|
else:
|
||||||
|
grades = []
|
||||||
|
|
||||||
grades_map: Dict[tuple, MilestoneGrade] = {
|
grades_map: Dict[tuple, MilestoneGrade] = {
|
||||||
(g.student_id, g.milestone_id): g for g in grades
|
(g.student_id, g.milestone_id): g for g in grades
|
||||||
@@ -177,7 +180,7 @@ class GradebookService:
|
|||||||
is_absent=final_absent,
|
is_absent=final_absent,
|
||||||
feedback=feedback.strip() if feedback else '',
|
feedback=feedback.strip() if feedback else '',
|
||||||
graded_by_user_id=grader_id,
|
graded_by_user_id=grader_id,
|
||||||
graded_at=datetime.utcnow()
|
graded_at=datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
)
|
)
|
||||||
db.session.add(grade)
|
db.session.add(grade)
|
||||||
else:
|
else:
|
||||||
@@ -186,7 +189,7 @@ class GradebookService:
|
|||||||
if feedback is not None:
|
if feedback is not None:
|
||||||
grade.feedback = feedback.strip()
|
grade.feedback = feedback.strip()
|
||||||
grade.graded_by_user_id = grader_id
|
grade.graded_by_user_id = grader_id
|
||||||
grade.updated_at = datetime.utcnow()
|
grade.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
return grade
|
return grade
|
||||||
@@ -240,7 +243,7 @@ class GradebookService:
|
|||||||
|
|
||||||
acta_num = f'ACTA-{comm.year}-{comm.semester}-{comm.id:04d}'
|
acta_num = f'ACTA-{comm.year}-{comm.semester}-{comm.id:04d}'
|
||||||
comm.grades_closed = True
|
comm.grades_closed = True
|
||||||
comm.grades_closed_at = datetime.utcnow()
|
comm.grades_closed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
comm.grades_closed_by = user_id
|
comm.grades_closed_by = user_id
|
||||||
comm.acta_number = acta_num
|
comm.acta_number = acta_num
|
||||||
|
|
||||||
@@ -383,7 +386,7 @@ class GradebookService:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def get_student_upcoming_milestones(cls, student_id: int, limit: int = 5) -> List[Dict[str, Any]]:
|
def get_student_upcoming_milestones(cls, student_id: int, limit: int = 5) -> List[Dict[str, Any]]:
|
||||||
"""Obtiene las próximas evaluaciones con cálculo de cuenta regresiva para el dashboard."""
|
"""Obtiene las próximas evaluaciones con cálculo de cuenta regresiva para el dashboard."""
|
||||||
now = datetime.utcnow()
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
enrollments = StudentEnrollment.query.filter_by(student_id=student_id).all()
|
enrollments = StudentEnrollment.query.filter_by(student_id=student_id).all()
|
||||||
commission_ids = [e.commission_id for e in enrollments]
|
commission_ids = [e.commission_id for e in enrollments]
|
||||||
|
|
||||||
|
|||||||
@@ -14,12 +14,12 @@ class MoodleClient:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_config(cls) -> Dict[str, Any]:
|
def get_config(cls) -> Dict[str, Any]:
|
||||||
server_url = SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle').rstrip('/')
|
server_url = str(SystemSetting.get_value('moodle_server_url', 'http://10.0.0.207/moodle') or 'http://10.0.0.207/moodle').rstrip('/')
|
||||||
token = SystemSetting.get_decrypted_value('moodle_ws_token', '')
|
token = SystemSetting.get_decrypted_value('moodle_ws_token', '')
|
||||||
# Fallback a token descubierto en Moodle si no está configurado aún en BD
|
# Fallback a token descubierto en Moodle si no está configurado aún en BD
|
||||||
if not token:
|
if not token:
|
||||||
token = '810428346d3601c68a37a315fcba8d4391629f46'
|
token = '810428346d3601c68a37a315fcba8d4391629f46'
|
||||||
timeout = int(SystemSetting.get_value('moodle_timeout', 10))
|
timeout = int(SystemSetting.get_value('moodle_timeout', 10) or 10)
|
||||||
return {
|
return {
|
||||||
'server_url': server_url,
|
'server_url': server_url,
|
||||||
'token': token,
|
'token': token,
|
||||||
@@ -131,7 +131,7 @@ class MoodleClient:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def create_user(cls, username: str, email: str, firstname: str, lastname: str, password: Optional[str] = None) -> Dict[str, Any]:
|
def create_user(cls, username: str, email: str, firstname: str, lastname: str, password: Optional[str] = None) -> Dict[str, Any]:
|
||||||
"""Crea un nuevo usuario en Moodle (core_user_create_users)."""
|
"""Crea un nuevo usuario en Moodle (core_user_create_users)."""
|
||||||
params = {
|
params: Dict[str, Any] = {
|
||||||
'users[0][username]': username.strip().lower(),
|
'users[0][username]': username.strip().lower(),
|
||||||
'users[0][email]': email.strip().lower(),
|
'users[0][email]': email.strip().lower(),
|
||||||
'users[0][firstname]': firstname.strip(),
|
'users[0][firstname]': firstname.strip(),
|
||||||
@@ -152,7 +152,7 @@ class MoodleClient:
|
|||||||
@classmethod
|
@classmethod
|
||||||
def update_user(cls, moodle_user_id: int, firstname: Optional[str] = None, lastname: Optional[str] = None, email: Optional[str] = None) -> Any:
|
def update_user(cls, moodle_user_id: int, firstname: Optional[str] = None, lastname: Optional[str] = None, email: Optional[str] = None) -> Any:
|
||||||
"""Actualiza datos de un usuario en Moodle (core_user_update_users)."""
|
"""Actualiza datos de un usuario en Moodle (core_user_update_users)."""
|
||||||
params = {'users[0][id]': moodle_user_id}
|
params: Dict[str, Any] = {'users[0][id]': moodle_user_id}
|
||||||
if firstname:
|
if firstname:
|
||||||
params['users[0][firstname]'] = firstname
|
params['users[0][firstname]'] = firstname
|
||||||
if lastname:
|
if lastname:
|
||||||
@@ -192,7 +192,8 @@ class MoodleClient:
|
|||||||
def get_enrolled_users(cls, course_id: int) -> List[Dict[str, Any]]:
|
def get_enrolled_users(cls, course_id: int) -> List[Dict[str, Any]]:
|
||||||
"""Obtiene todos los usuarios matriculados en un curso (core_enrol_get_enrolled_users)."""
|
"""Obtiene todos los usuarios matriculados en un curso (core_enrol_get_enrolled_users)."""
|
||||||
params = {'courseid': course_id}
|
params = {'courseid': course_id}
|
||||||
return cls.call('core_enrol_get_enrolled_users', params)
|
res = cls.call('core_enrol_get_enrolled_users', params)
|
||||||
|
return res if isinstance(res, list) else []
|
||||||
|
|
||||||
# --------------------------------------------------------------------------
|
# --------------------------------------------------------------------------
|
||||||
# Asignación de Roles (core_role_*)
|
# Asignación de Roles (core_role_*)
|
||||||
@@ -227,11 +228,41 @@ class MoodleClient:
|
|||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def update_users(cls, users: List[Dict[str, Any]]) -> Any:
|
def update_users(cls, users: List[Dict[str, Any]]) -> Any:
|
||||||
params = {}
|
to_update = []
|
||||||
for idx, u in enumerate(users):
|
to_create = []
|
||||||
for k, v in u.items():
|
for u in users:
|
||||||
params[f'users[{idx}][{k}]'] = v
|
user_data = dict(u)
|
||||||
return cls.call('core_user_update_users', params, method='POST')
|
if 'id' not in user_data or not user_data['id']:
|
||||||
|
# Moodle requiere el ID numérico interno en core_user_update_users.
|
||||||
|
# Buscar en Moodle por email o username para obtener su ID:
|
||||||
|
existing = None
|
||||||
|
if user_data.get('email'):
|
||||||
|
existing = cls.get_user_by_email(str(user_data['email']))
|
||||||
|
if not existing and user_data.get('username'):
|
||||||
|
found = cls.get_users_by_criteria('username', str(user_data['username']))
|
||||||
|
if found:
|
||||||
|
existing = found[0]
|
||||||
|
|
||||||
|
if existing and 'id' in existing:
|
||||||
|
user_data['id'] = existing['id']
|
||||||
|
to_update.append(user_data)
|
||||||
|
else:
|
||||||
|
to_create.append(user_data)
|
||||||
|
else:
|
||||||
|
to_update.append(user_data)
|
||||||
|
|
||||||
|
results = []
|
||||||
|
if to_create:
|
||||||
|
res_c = cls.create_users(to_create)
|
||||||
|
results.append(res_c)
|
||||||
|
if to_update:
|
||||||
|
params = {}
|
||||||
|
for idx, u in enumerate(to_update):
|
||||||
|
for k, v in u.items():
|
||||||
|
params[f'users[{idx}][{k}]'] = v
|
||||||
|
res_u = cls.call('core_user_update_users', params, method='POST')
|
||||||
|
results.append(res_u)
|
||||||
|
return results if len(results) > 1 else (results[0] if results else None)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def enrol_users(cls, enrolments: List[Dict[str, Any]]) -> Any:
|
def enrol_users(cls, enrolments: List[Dict[str, Any]]) -> Any:
|
||||||
|
|||||||
@@ -5,7 +5,8 @@ operations between admin-edu-space and Moodle 4.1.
|
|||||||
Implements Exponential Backoff and Dead Letter Queue (DLQ).
|
Implements Exponential Backoff and Dead Letter Queue (DLQ).
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from typing import Optional
|
||||||
from app import db
|
from app import db
|
||||||
from app.models.sync_task import MoodleSyncTask
|
from app.models.sync_task import MoodleSyncTask
|
||||||
from app.services.moodle_client import moodle_client
|
from app.services.moodle_client import moodle_client
|
||||||
@@ -14,7 +15,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class MoodleQueueService:
|
class MoodleQueueService:
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def enqueue_task(action: str, entity_type: str, entity_id: str = None, payload: dict = None, max_attempts: int = 5) -> MoodleSyncTask:
|
def enqueue_task(action: str, entity_type: str, entity_id: Optional[str] = None, payload: Optional[dict] = None, max_attempts: int = 5) -> MoodleSyncTask:
|
||||||
"""
|
"""
|
||||||
Enqueues a new synchronization task to be processed asynchronously.
|
Enqueues a new synchronization task to be processed asynchronously.
|
||||||
Guarantees that local transactions are never blocked by Moodle unavailability.
|
Guarantees that local transactions are never blocked by Moodle unavailability.
|
||||||
@@ -22,12 +23,12 @@ class MoodleQueueService:
|
|||||||
task = MoodleSyncTask(
|
task = MoodleSyncTask(
|
||||||
action=action,
|
action=action,
|
||||||
entity_type=entity_type,
|
entity_type=entity_type,
|
||||||
entity_id=str(entity_id) if entity_id else None,
|
entity_id=entity_id if entity_id is not None else None,
|
||||||
payload=payload or {},
|
payload=payload or {},
|
||||||
status='PENDING',
|
status='PENDING',
|
||||||
attempts=0,
|
attempts=0,
|
||||||
max_attempts=max_attempts,
|
max_attempts=max_attempts,
|
||||||
next_retry_at=datetime.utcnow()
|
next_retry_at=datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
)
|
)
|
||||||
db.session.add(task)
|
db.session.add(task)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
@@ -41,7 +42,7 @@ class MoodleQueueService:
|
|||||||
Uses exponential backoff for retries and sends to Dead Letter Queue (FAILED)
|
Uses exponential backoff for retries and sends to Dead Letter Queue (FAILED)
|
||||||
if max_attempts are exceeded.
|
if max_attempts are exceeded.
|
||||||
"""
|
"""
|
||||||
now = datetime.utcnow()
|
now = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
tasks = MoodleSyncTask.query.filter(
|
tasks = MoodleSyncTask.query.filter(
|
||||||
MoodleSyncTask.status.in_(['PENDING', 'RETRYING']),
|
MoodleSyncTask.status.in_(['PENDING', 'RETRYING']),
|
||||||
(MoodleSyncTask.next_retry_at == None) | (MoodleSyncTask.next_retry_at <= now)
|
(MoodleSyncTask.next_retry_at == None) | (MoodleSyncTask.next_retry_at <= now)
|
||||||
@@ -60,21 +61,21 @@ class MoodleQueueService:
|
|||||||
for task in tasks:
|
for task in tasks:
|
||||||
results['processed'] += 1
|
results['processed'] += 1
|
||||||
task.status = 'PROCESSING'
|
task.status = 'PROCESSING'
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
MoodleQueueService._execute_task_action(task)
|
MoodleQueueService._execute_task_action(task)
|
||||||
task.status = 'COMPLETED'
|
task.status = 'COMPLETED'
|
||||||
task.error_message = None
|
task.error_message = None
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
results['succeeded'] += 1
|
results['succeeded'] += 1
|
||||||
logger.info(f"[MoodleQueue] Task {task.id} ({task.action}) completed successfully.")
|
logger.info(f"[MoodleQueue] Task {task.id} ({task.action}) completed successfully.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
task.attempts += 1
|
task.attempts += 1
|
||||||
task.error_message = str(e)
|
task.error_message = str(e)
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
if task.attempts >= task.max_attempts:
|
if task.attempts >= task.max_attempts:
|
||||||
task.status = 'FAILED' # Dead Letter Queue (DLQ)
|
task.status = 'FAILED' # Dead Letter Queue (DLQ)
|
||||||
@@ -85,7 +86,7 @@ class MoodleQueueService:
|
|||||||
task.status = 'RETRYING'
|
task.status = 'RETRYING'
|
||||||
# Exponential Backoff: 30s, 60s, 120s, 240s... capped at 1 hour
|
# Exponential Backoff: 30s, 60s, 120s, 240s... capped at 1 hour
|
||||||
delay_seconds = min(3600, (2 ** task.attempts) * 30)
|
delay_seconds = min(3600, (2 ** task.attempts) * 30)
|
||||||
task.next_retry_at = datetime.utcnow() + timedelta(seconds=delay_seconds)
|
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(seconds=delay_seconds)
|
||||||
results['retrying'] += 1
|
results['retrying'] += 1
|
||||||
logger.warning(f"[MoodleQueue] Task {task.id} failed attempt {task.attempts}/{task.max_attempts}. Next retry in {delay_seconds}s: {e}")
|
logger.warning(f"[MoodleQueue] Task {task.id} failed attempt {task.attempts}/{task.max_attempts}. Next retry in {delay_seconds}s: {e}")
|
||||||
|
|
||||||
@@ -123,16 +124,16 @@ class MoodleQueueService:
|
|||||||
return res
|
return res
|
||||||
|
|
||||||
elif action == 'ASSIGN_ROLE':
|
elif action == 'ASSIGN_ROLE':
|
||||||
role_id = payload.get('role_id')
|
role_id = int(payload.get('role_id', 5))
|
||||||
user_id = payload.get('user_id')
|
user_id = int(payload.get('user_id', 0))
|
||||||
context_id = payload.get('context_id', 1)
|
context_id = int(payload.get('context_id', 1))
|
||||||
res = moodle_client.assign_role(role_id, user_id, context_id)
|
res = moodle_client.assign_role(role_id, user_id, context_id)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
elif action == 'UNASSIGN_ROLE':
|
elif action == 'UNASSIGN_ROLE':
|
||||||
role_id = payload.get('role_id')
|
role_id = int(payload.get('role_id', 5))
|
||||||
user_id = payload.get('user_id')
|
user_id = int(payload.get('user_id', 0))
|
||||||
context_id = payload.get('context_id', 1)
|
context_id = int(payload.get('context_id', 1))
|
||||||
res = moodle_client.unassign_role(role_id, user_id, context_id)
|
res = moodle_client.unassign_role(role_id, user_id, context_id)
|
||||||
return res
|
return res
|
||||||
|
|
||||||
@@ -150,9 +151,9 @@ class MoodleQueueService:
|
|||||||
|
|
||||||
task.status = 'PENDING'
|
task.status = 'PENDING'
|
||||||
task.attempts = 0
|
task.attempts = 0
|
||||||
task.next_retry_at = datetime.utcnow()
|
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
task.error_message = None
|
task.error_message = None
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
logger.info(f"[MoodleQueue] Task {task_id} manually reset to PENDING.")
|
logger.info(f"[MoodleQueue] Task {task_id} manually reset to PENDING.")
|
||||||
return True
|
return True
|
||||||
@@ -167,8 +168,8 @@ class MoodleQueueService:
|
|||||||
for task in failed_tasks:
|
for task in failed_tasks:
|
||||||
task.status = 'PENDING'
|
task.status = 'PENDING'
|
||||||
task.attempts = 0
|
task.attempts = 0
|
||||||
task.next_retry_at = datetime.utcnow()
|
task.next_retry_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
task.updated_at = datetime.utcnow()
|
task.updated_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
count += 1
|
count += 1
|
||||||
db.session.commit()
|
db.session.commit()
|
||||||
logger.info(f"[MoodleQueue] Reset {count} failed tasks back to PENDING.")
|
logger.info(f"[MoodleQueue] Reset {count} failed tasks back to PENDING.")
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import time
|
import time
|
||||||
import uuid
|
import uuid
|
||||||
import threading
|
import threading
|
||||||
from datetime import datetime, timedelta
|
from datetime import datetime, timedelta, timezone
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
from typing import List, Dict, Any, Optional
|
from typing import List, Dict, Any, Optional
|
||||||
from flask import current_app
|
from flask import current_app
|
||||||
@@ -39,7 +39,7 @@ class OptimizerJob:
|
|||||||
self.reservations: List[Dict[str, Any]] = []
|
self.reservations: List[Dict[str, Any]] = []
|
||||||
self.conflicts: List[Dict[str, Any]] = []
|
self.conflicts: List[Dict[str, Any]] = []
|
||||||
self.error: Optional[str] = None
|
self.error: Optional[str] = None
|
||||||
self.created_at = datetime.utcnow()
|
self.created_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
self.started_at: Optional[datetime] = None
|
self.started_at: Optional[datetime] = None
|
||||||
self.completed_at: Optional[datetime] = None
|
self.completed_at: Optional[datetime] = None
|
||||||
self.execution_time_ms: Optional[float] = None
|
self.execution_time_ms: Optional[float] = None
|
||||||
@@ -109,7 +109,7 @@ class OptimizerService:
|
|||||||
# Si no se pasó app explícitamente, intentar obtener current_app
|
# Si no se pasó app explícitamente, intentar obtener current_app
|
||||||
if app is None:
|
if app is None:
|
||||||
try:
|
try:
|
||||||
app = current_app._get_current_object()
|
app = getattr(current_app, '_get_current_object', lambda: current_app)()
|
||||||
except Exception:
|
except Exception:
|
||||||
app = None
|
app = None
|
||||||
|
|
||||||
@@ -133,14 +133,15 @@ class OptimizerService:
|
|||||||
t_start = time.perf_counter()
|
t_start = time.perf_counter()
|
||||||
with cls._lock:
|
with cls._lock:
|
||||||
job.status = OptimizerJobStatus.RUNNING
|
job.status = OptimizerJobStatus.RUNNING
|
||||||
job.started_at = datetime.utcnow()
|
job.started_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
def progress_callback(gen: int, total_gen: int, pct: int, best_fit: float):
|
def progress_callback(gen: int, total_gen: int, pct: int, best_fit: float):
|
||||||
with cls._lock:
|
if job:
|
||||||
job.generation = gen
|
with cls._lock:
|
||||||
job.total_generations = total_gen
|
job.generation = gen
|
||||||
job.progress = pct
|
job.total_generations = total_gen
|
||||||
job.fitness_score = best_fit
|
job.progress = pct
|
||||||
|
job.fitness_score = best_fit
|
||||||
|
|
||||||
optimizer = ReservationOptimizer(
|
optimizer = ReservationOptimizer(
|
||||||
population_size=job.params.get("population_size", 40),
|
population_size=job.params.get("population_size", 40),
|
||||||
@@ -167,7 +168,7 @@ class OptimizerService:
|
|||||||
job.assigned_reservations = result.get("assigned_reservations", 0)
|
job.assigned_reservations = result.get("assigned_reservations", 0)
|
||||||
job.reservations = result.get("reservations", [])
|
job.reservations = result.get("reservations", [])
|
||||||
job.conflicts = result.get("conflicts", [])
|
job.conflicts = result.get("conflicts", [])
|
||||||
job.completed_at = datetime.utcnow()
|
job.completed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
job.execution_time_ms = exec_time_ms
|
job.execution_time_ms = exec_time_ms
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -180,7 +181,7 @@ class OptimizerService:
|
|||||||
with cls._lock:
|
with cls._lock:
|
||||||
job.status = OptimizerJobStatus.FAILED
|
job.status = OptimizerJobStatus.FAILED
|
||||||
job.error = str(ex)
|
job.error = str(ex)
|
||||||
job.completed_at = datetime.utcnow()
|
job.completed_at = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def get_job(cls, job_id: str) -> Optional[OptimizerJob]:
|
def get_job(cls, job_id: str) -> Optional[OptimizerJob]:
|
||||||
@@ -278,5 +279,5 @@ class OptimizerService:
|
|||||||
"conflictCount": len(best_individual.conflicts),
|
"conflictCount": len(best_individual.conflicts),
|
||||||
"fitnessScore": round(best_individual.fitness, 2),
|
"fitnessScore": round(best_individual.fitness, 2),
|
||||||
"executionTimeMs": exec_ms,
|
"executionTimeMs": exec_ms,
|
||||||
"timestamp": datetime.utcnow().isoformat() + "Z"
|
"timestamp": datetime.now(timezone.utc).isoformat()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
from typing import Dict, Any, List, Optional
|
||||||
import urllib.request
|
import urllib.request
|
||||||
import csv
|
import csv
|
||||||
import io
|
import io
|
||||||
@@ -460,10 +461,10 @@ class GoogleSheetsImporter:
|
|||||||
row_counter += 1
|
row_counter += 1
|
||||||
aula_raw = r.get('aula', '').strip()
|
aula_raw = r.get('aula', '').strip()
|
||||||
room_info = self.normalize_room(aula_raw)
|
room_info = self.normalize_room(aula_raw)
|
||||||
is_virtual = bool(room_info and ('VIRTUAL' in room_info.get('code', '').upper() or room_info.get('building') == 'Campus Virtual'))
|
is_virtual = bool(room_info and ('VIRTUAL' in str(room_info.get('code', '')).upper() or room_info.get('building') == 'Campus Virtual'))
|
||||||
|
|
||||||
# Calcular fecha tentativa
|
# Calcular fecha tentativa
|
||||||
target_date = ref_monday + timedelta(days=day_idx)
|
target_date = ref_monday + timedelta(days=int(day_idx))
|
||||||
if manual_dt and norm_day == normalize_day_name(['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'][manual_dt.weekday()]):
|
if manual_dt and norm_day == normalize_day_name(['Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'][manual_dt.weekday()]):
|
||||||
target_date = manual_dt
|
target_date = manual_dt
|
||||||
|
|
||||||
@@ -564,7 +565,7 @@ class GoogleSheetsImporter:
|
|||||||
if manual_w < 6:
|
if manual_w < 6:
|
||||||
allowed_days = [dias_esp[manual_w]]
|
allowed_days = [dias_esp[manual_w]]
|
||||||
|
|
||||||
stats = {
|
stats: Dict[str, Any] = {
|
||||||
'total_rows_processed': 0,
|
'total_rows_processed': 0,
|
||||||
'matching_rows': 0,
|
'matching_rows': 0,
|
||||||
'careers_created': 0,
|
'careers_created': 0,
|
||||||
@@ -734,9 +735,11 @@ class GoogleSheetsImporter:
|
|||||||
room_info = self.normalize_room(aula_raw)
|
room_info = self.normalize_room(aula_raw)
|
||||||
classroom = None
|
classroom = None
|
||||||
if room_info:
|
if room_info:
|
||||||
room_key = (room_info['building'].upper(), room_info['code'].upper())
|
b_str = str(room_info.get('building', '')).upper()
|
||||||
|
c_str = str(room_info.get('code', '')).upper()
|
||||||
|
room_key = (b_str, c_str)
|
||||||
classroom = classrooms_cache.get(room_key)
|
classroom = classrooms_cache.get(room_key)
|
||||||
b_entity = buildings_cache.get(room_info['building'].upper())
|
b_entity = buildings_cache.get(b_str)
|
||||||
if not classroom:
|
if not classroom:
|
||||||
if import_classrooms:
|
if import_classrooms:
|
||||||
classroom = Classroom(
|
classroom = Classroom(
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
from typing import Optional, Dict, Any
|
from typing import Optional, Dict, Any
|
||||||
from datetime import datetime
|
from datetime import datetime, timezone
|
||||||
from app.models.user import User
|
from app.models.user import User
|
||||||
from app.repositories.user_repository import UserRepository
|
from app.repositories.user_repository import UserRepository
|
||||||
from app import db
|
from app import db
|
||||||
@@ -20,7 +20,7 @@ class UserService:
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
if user.check_password(password):
|
if user.check_password(password):
|
||||||
user.last_login = datetime.utcnow()
|
user.last_login = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
self.repository.save(user)
|
self.repository.save(user)
|
||||||
return user
|
return user
|
||||||
return None
|
return None
|
||||||
@@ -59,3 +59,5 @@ class UserService:
|
|||||||
'document_number': getattr(user, 'document_number', ''),
|
'document_number': getattr(user, 'document_number', ''),
|
||||||
'personal_email': getattr(user, 'personal_email', '')
|
'personal_email': getattr(user, 'personal_email', '')
|
||||||
}
|
}
|
||||||
|
|
||||||
|
user_service = UserService()
|
||||||
|
|||||||
@@ -39,7 +39,13 @@ def jwt_required(f):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
payload = JWTService.decode_token(token, expected_type='access')
|
payload = JWTService.decode_token(token, expected_type='access')
|
||||||
user_id = int(payload.get('sub'))
|
sub = payload.get('sub')
|
||||||
|
if not sub:
|
||||||
|
return jsonify({
|
||||||
|
'error': 'Unauthorized',
|
||||||
|
'message': 'Token inválido: falta identificador de usuario.'
|
||||||
|
}), 401
|
||||||
|
user_id = int(sub)
|
||||||
from app import db
|
from app import db
|
||||||
user = db.session.get(User, user_id)
|
user = db.session.get(User, user_id)
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
|||||||
|
|
||||||
setup(
|
setup(
|
||||||
name="edu-space-admin",
|
name="edu-space-admin",
|
||||||
version="3.6.3",
|
version="3.6.4",
|
||||||
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",
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ Nada se implementa, refactoriza o modifica en la plataforma si no está document
|
|||||||
|
|
||||||
### 2. Arquitectura Desacoplada (Backend RESTful + Frontend BFF)
|
### 2. Arquitectura Desacoplada (Backend RESTful + Frontend BFF)
|
||||||
El sistema opera bajo una arquitectura desacoplada de dos capas:
|
El sistema opera bajo una arquitectura desacoplada de dos capas:
|
||||||
- **Backend Core API (Python / Flask + SQLAlchemy)**: Expone exclusivamente servicios RESTful bajo el prefijo `/api/v1/`, retornando respuestas JSON estructuradas con serializadores/DTOs. Gestiona la autenticación stateless mediante tokens JWT (HS256), la integridad referencial en base de datos y el pipeline de blindaje `SecurityFilterChain`.
|
- **Backend Core API (Python 3.12+ / FastAPI + Uvicorn ASGI & Flask WSGI bridge + SQLAlchemy 2.0)**: Expone exclusivamente servicios RESTful bajo el prefijo `/api/v1/` y contratos OpenAPI interactivos en `/docs`, retornando respuestas JSON estructuradas con serializadores/DTOs Pydantic. Gestiona la autenticación stateless mediante tokens JWT (HS256), la integridad referencial en base de datos y el pipeline de blindaje `SecurityFilterChain`.
|
||||||
- **Frontend BFF (Node.js / Express + Nunjucks)**: Orquesta la presentación y la experiencia de usuario (UX), mantiene la sesión mediante cookies seguras `HttpOnly`, inyecta encabezados de autorización Bearer en llamadas Axios hacia el backend y adapta las vistas según el rol del usuario autenticado.
|
- **Frontend BFF (Node.js / Express + Nunjucks)**: Orquesta la presentación y la experiencia de usuario (UX), mantiene la sesión mediante cookies seguras `HttpOnly`, inyecta encabezados de autorización Bearer en llamadas Axios hacia el backend y adapta las vistas según el rol del usuario autenticado.
|
||||||
|
|
||||||
### 3. Reemplazo Definitivo del Excel como Herramienta Operativa
|
### 3. Reemplazo Definitivo del Excel como Herramienta Operativa
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "frontend",
|
"name": "frontend",
|
||||||
"version": "3.6.3",
|
"version": "3.6.4",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -51,32 +51,7 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Role Perspective Switcher for Admins & Managers -->
|
|
||||||
{% if user.is_admin() or user.can_manage() %}
|
|
||||||
<div class="d-flex flex-column align-items-end">
|
|
||||||
<small class="text-muted fw-semibold mb-1" style="font-size: 0.72rem; letter-spacing: 0.3px;">
|
|
||||||
<i class="bi bi-person-bounding-box me-1"></i>VER PANEL COMO ROL:
|
|
||||||
</small>
|
|
||||||
<div class="btn-group role-view-selector bg-body-tertiary p-1 rounded-pill border" role="group">
|
|
||||||
<a href="/dashboard?role=admin"
|
|
||||||
class="btn btn-sm {% if not role or role == 'admin' %}btn-primary active{% else %}btn-outline-secondary border-0{% endif %}">
|
|
||||||
<i class="bi bi-shield-check me-1"></i>Admin
|
|
||||||
</a>
|
|
||||||
<a href="/dashboard?role=bedelia"
|
|
||||||
class="btn btn-sm {% if role == 'bedelia' %}btn-warning active text-dark{% else %}btn-outline-secondary border-0{% endif %}">
|
|
||||||
<i class="bi bi-building-gear me-1"></i>Bedelía
|
|
||||||
</a>
|
|
||||||
<a href="/dashboard?role=docente"
|
|
||||||
class="btn btn-sm {% if role == 'docente' %}btn-info active text-white{% else %}btn-outline-secondary border-0{% endif %}">
|
|
||||||
<i class="bi bi-person-video3 me-1"></i>Docente
|
|
||||||
</a>
|
|
||||||
<a href="/dashboard?role=alumno"
|
|
||||||
class="btn btn-sm {% if role == 'alumno' %}btn-success active text-white{% else %}btn-outline-secondary border-0{% endif %}">
|
|
||||||
<i class="bi bi-mortarboard me-1"></i>Alumno
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
{% endif %}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
|
|||||||
Reference in New Issue
Block a user