feat(benefits-reception): add institutional benefits, QR digital card & reception access control (SDD-012 v3.8.39)
This commit is contained in:
@@ -11,6 +11,20 @@ El formato está basado en [Keep a Changelog](https://keepachangelog.com/es-ES/1
|
||||
- **Sincronización Continua Moodle (Fase 6):** Automatización de workers persistentes en background para el procesamiento continuo de la cola de Web Services Moodle 4.1.
|
||||
- **Pruebas de Carga y Hardening (Fase 6):** Pruebas de estrés de concurrencia y validación final de producción.
|
||||
|
||||
## [3.8.39] - 2026-10-27
|
||||
### Added & Enhanced (Club de Beneficios y Convenios Institucionales + Control de Acceso QR / Recepción — SDD-012)
|
||||
- **Club de Beneficios y Convenios Institucionales**:
|
||||
- Nuevo modelo relacional `InstitutionalBenefit` para convenios y promociones comerciales (cafeterías, librerías, gimnasios, tecnología).
|
||||
- Panel administrativo de gestión para Bedelía y Administradores (`/benefits/manage` y `/api/v1/benefits`) con filtros, métricas en vivo, carga de cupones, porcentaje de descuento y control de vigencia.
|
||||
- Catálogo interactivo tipo marketplace para Alumnos y Docentes (`/benefits`) con filtrado por categorías y revelado seguro de cupones.
|
||||
- **Valor agregado con IA (UdeCi)**: `LiveContextService` enriquecido para responder con convenios activos de la base de datos ante preguntas como *"¿Qué descuentos hay en cafetería hoy?"*.
|
||||
- **Perfil de Recepción y Control de Acceso QR**:
|
||||
- Nuevo rol institucional `RECEPCION` con permisos específicos para mesas de entrada y molinetes.
|
||||
- Consola de escaneo de alta velocidad (`/reception/scanner` y `/api/v1/reception/verify-qr`) con soporte para cámara web (`html5-qrcode`) y pistolas ópticas USB de código de barras.
|
||||
- Indicador de clase del día en tiempo real: al escanear la credencial, muestra inmediatamente al ingresante su aula física asignada, piso, horario y docente.
|
||||
- Nueva Credencial Universitaria Digital (`/credential/my-card` y `/api/v1/reception/my-qr-token`) con token dinámico firmado con JWT (`credential_qr`), DNI institucional y diseño tipo tarjeta universitaria.
|
||||
- Modelo `AccessLogQR` para registro y trazabilidad de ingresos con estados `AUTORIZADO`, `RESTRINGIDO` y `DENEGADO`.
|
||||
|
||||
## [3.8.38] - 2026-10-27
|
||||
### Fixed & Improved (Resiliencia de Respuesta de UdeCi y Compatibilidad Dual DTO)
|
||||
- **Corrección de Mapeo de Respuestas en Frontend (`response` vs `reply`)**:
|
||||
|
||||
@@ -9,10 +9,11 @@ Memoria del proyecto entre sesiones para la rama `dev`.
|
||||
- Libro de Calificaciones (*Gradebook*) con actas de regularidad inmutables.
|
||||
- Autenticación híbrida (Google OAuth 2.0, Moodle SSO, Local) y Modo Impersonación.
|
||||
- Reinicialización segura del sistema con contraseña de Administrador.
|
||||
- **Sprint Activo: Resiliencia de Respuestas y Corrección DTO de UdeCi — SDD-011 (v3.8.38)**:
|
||||
- **Corrección de Mapeo de Atributos DTO**: Se corrigió el desacople de nombres de campo entre el frontend (`ai-chat-widget.js`) y el backend (`ChatResponse`), asegurando que las respuestas factualmente válidas del motor de IA (`response`, `quick_options`) se muestren fluidamente y no caigan en el texto de fallo por defecto.
|
||||
- **Dual DTO & Spotlight Integration**: Soporte en backend de alias `reply` y `options`, e integración de `guide_step` con `WalkthroughEngine.startStep()`.
|
||||
- **Versión Consolidada**: `v3.8.38`.
|
||||
- **Sprint Activo: Club de Beneficios, Convenios Institucionales y Control de Acceso QR / Recepción — SDD-012 (v3.8.39)**:
|
||||
- **Club de Beneficios y Convenios**: ABM completo para Bedelía/Admin (`/benefits/manage`), catálogo visual estilo marketplace para Alumnos/Docentes (`/benefits`), y valor agregado con IA donde UdeCi cita en tiempo real convenios vigentes desde la base de datos relacional (`LiveContextService`).
|
||||
- **Recepción y Control de Acceso QR**: Rol `RECEPCION`, consola de escaneo de alta velocidad (`/reception/scanner`) con soporte de cámara web y lector de código de barras USB. Verificación de credencial con alerta visual de matrícula e indicación inmediata del aula física, piso y horario asignado al alumno/docente en el día.
|
||||
- **Credencial Digital**: Vista de tarjeta institucional (`/credential/my-card`) con token QR dinámico criptográficamente firmado (`credential_qr`).
|
||||
- **Versión Consolidada**: `v3.8.39`.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import Any
|
||||
from database import db, get_db, engine, SessionLocal, session
|
||||
from config.config import Config
|
||||
|
||||
__version__ = "3.8.38"
|
||||
__version__ = "3.8.39"
|
||||
|
||||
class DummyContext:
|
||||
def __enter__(self):
|
||||
|
||||
@@ -14,6 +14,8 @@ from .setting import SystemSetting
|
||||
from .grade import MilestoneGrade
|
||||
from .sync_task import MoodleSyncTask
|
||||
from .knowledge_chunk import KnowledgeChunk
|
||||
from .institutional_benefit import InstitutionalBenefit
|
||||
from .access_log_qr import AccessLogQR
|
||||
|
||||
__all__ = [
|
||||
'User',
|
||||
@@ -40,5 +42,7 @@ __all__ = [
|
||||
'SystemSetting',
|
||||
'MilestoneGrade',
|
||||
'MoodleSyncTask',
|
||||
'KnowledgeChunk'
|
||||
'KnowledgeChunk',
|
||||
'InstitutionalBenefit',
|
||||
'AccessLogQR'
|
||||
]
|
||||
@@ -0,0 +1,50 @@
|
||||
from app import db
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class AccessLogQR(db.Model):
|
||||
"""
|
||||
Registro y trazabilidad de ingresos escaneados por código QR en Recepción (SDD-012).
|
||||
Permite auditar el ingreso físico de alumnos y docentes a las sedes institucionales.
|
||||
"""
|
||||
__tablename__ = 'access_logs_qr'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='CASCADE'), nullable=False, index=True)
|
||||
building_id = db.Column(db.Integer, db.ForeignKey('buildings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
scanned_by_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
scanned_at = db.Column(
|
||||
db.DateTime,
|
||||
default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
nullable=False,
|
||||
index=True
|
||||
)
|
||||
status = db.Column(db.String(20), default='AUTORIZADO', nullable=False) # AUTORIZADO, DENEGADO, RESTRINGIDO
|
||||
reason = db.Column(db.String(150), nullable=True)
|
||||
|
||||
# Relaciones
|
||||
user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('qr_access_logs', lazy='dynamic'))
|
||||
building = db.relationship('Building', foreign_keys=[building_id])
|
||||
scanned_by = db.relationship('User', foreign_keys=[scanned_by_user_id])
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serializa el registro de acceso a diccionario JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'user_id': self.user_id,
|
||||
'user_name': self.user.name if self.user else 'Desconocido',
|
||||
'user_dni': self.user.document_number if self.user else None,
|
||||
'user_role': self.user.role if self.user else None,
|
||||
'building_id': self.building_id,
|
||||
'building_name': self.building.name if self.building else 'Sede Desconocida',
|
||||
'scanned_by_user_id': self.scanned_by_user_id,
|
||||
'scanned_by_name': self.scanned_by.name if self.scanned_by else 'Sistema',
|
||||
'scanned_at': self.scanned_at.isoformat() if self.scanned_at else None,
|
||||
'status': self.status,
|
||||
'reason': self.reason
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
from app import db
|
||||
from datetime import datetime, timezone, date
|
||||
from typing import Optional, Dict, Any
|
||||
|
||||
|
||||
class InstitutionalBenefit(db.Model):
|
||||
"""
|
||||
Modelo de Beneficios y Convenios Comerciales Institucionales para UniCABA (SDD-012).
|
||||
Permite a Bedelía y Administradores cargar promociones, descuentos y convenios
|
||||
con comercios (cafeterías, librerías, tecnología, salud) para alumnos y docentes.
|
||||
"""
|
||||
__tablename__ = 'institutional_benefits'
|
||||
__allow_unmapped__ = True
|
||||
|
||||
id = db.Column(db.Integer, primary_key=True)
|
||||
title = db.Column(db.String(150), nullable=False, index=True)
|
||||
partner_name = db.Column(db.String(120), nullable=False, index=True)
|
||||
category = db.Column(db.String(50), nullable=False, default='GENERAL', index=True)
|
||||
discount_label = db.Column(db.String(80), nullable=False)
|
||||
description = db.Column(db.Text, nullable=True)
|
||||
terms_conditions = db.Column(db.Text, nullable=True)
|
||||
target_roles = db.Column(db.String(100), nullable=False, default='ALL')
|
||||
building_id = db.Column(db.Integer, db.ForeignKey('buildings.id', ondelete='SET NULL'), nullable=True, index=True)
|
||||
coupon_code = db.Column(db.String(50), nullable=True)
|
||||
valid_from = db.Column(db.Date, nullable=False, default=date.today)
|
||||
valid_until = db.Column(db.Date, nullable=True)
|
||||
is_active = db.Column(db.Boolean, default=True, nullable=False, index=True)
|
||||
image_url = db.Column(db.String(255), nullable=True)
|
||||
created_by_user_id = db.Column(db.Integer, db.ForeignKey('users.id', ondelete='SET NULL'), nullable=True)
|
||||
created_at = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc).replace(tzinfo=None))
|
||||
updated_at = db.Column(
|
||||
db.DateTime,
|
||||
default=lambda: datetime.now(timezone.utc).replace(tzinfo=None),
|
||||
onupdate=lambda: datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
)
|
||||
|
||||
# Relaciones
|
||||
building = db.relationship('Building', backref=db.backref('institutional_benefits', lazy='dynamic'))
|
||||
creator = db.relationship('User', foreign_keys=[created_by_user_id])
|
||||
|
||||
def __init__(self, **kwargs):
|
||||
super().__init__(**kwargs)
|
||||
|
||||
@property
|
||||
def is_currently_valid(self) -> bool:
|
||||
"""Determina si el convenio está activo y dentro de su rango de vigencia."""
|
||||
if not self.is_active:
|
||||
return False
|
||||
today = date.today()
|
||||
if self.valid_from and self.valid_from > today:
|
||||
return False
|
||||
if self.valid_until and self.valid_until < today:
|
||||
return False
|
||||
return True
|
||||
|
||||
def applies_to_role(self, role: str) -> bool:
|
||||
"""Verifica si el beneficio aplica al rol indicado (alumno, docente, bedelia, admin)."""
|
||||
if not role:
|
||||
return False
|
||||
target = (self.target_roles or 'ALL').upper()
|
||||
if 'ALL' in target or 'TODOS' in target:
|
||||
return True
|
||||
r = role.strip().upper()
|
||||
if r in target:
|
||||
return True
|
||||
if r in ['ESTUDIANTE', 'ALUMNO'] and ('ALUMNO' in target or 'ESTUDIANTE' in target):
|
||||
return True
|
||||
if r in ['DOCENTE', 'PROFESOR', 'TEACHER'] and ('DOCENTE' in target or 'PROFESOR' in target):
|
||||
return True
|
||||
return False
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
"""Serializa la entidad a diccionario compatible con JSON."""
|
||||
return {
|
||||
'id': self.id,
|
||||
'title': self.title,
|
||||
'partner_name': self.partner_name,
|
||||
'category': self.category,
|
||||
'discount_label': self.discount_label,
|
||||
'description': self.description,
|
||||
'terms_conditions': self.terms_conditions,
|
||||
'target_roles': self.target_roles,
|
||||
'building_id': self.building_id,
|
||||
'building_name': self.building.name if self.building else 'Todas las Sedes',
|
||||
'coupon_code': self.coupon_code,
|
||||
'valid_from': self.valid_from.isoformat() if self.valid_from else None,
|
||||
'valid_until': self.valid_until.isoformat() if self.valid_until else None,
|
||||
'is_active': self.is_active,
|
||||
'is_currently_valid': self.is_currently_valid,
|
||||
'image_url': self.image_url,
|
||||
'created_by_user_id': self.created_by_user_id,
|
||||
'created_at': self.created_at.isoformat() if self.created_at else None,
|
||||
'updated_at': self.updated_at.isoformat() if self.updated_at else None,
|
||||
}
|
||||
@@ -18,6 +18,7 @@ from app.models.reservation import Reservation
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.milestone import AcademicMilestone, MilestoneType
|
||||
from app.models.grade import MilestoneGrade
|
||||
from app.models.institutional_benefit import InstitutionalBenefit
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.services.gradebook_service import GradebookService
|
||||
@@ -621,6 +622,39 @@ class LiveContextService:
|
||||
for rm in matched_rooms:
|
||||
cap = rm.capacity_display
|
||||
lines.append(f"• Aula {rm.code_display} (Piso: {rm.floor_display}, Capacidad: {cap})")
|
||||
|
||||
# E. Búsqueda de Convenios y Beneficios Institucionales
|
||||
benefit_keywords = [
|
||||
'convenio', 'convenios', 'beneficio', 'beneficios', 'descuento', 'descuentos',
|
||||
'promocion', 'promociones', 'promo', 'cafeteria', 'cafe', 'comida', 'almuerzo',
|
||||
'libreria', 'fotocopia', 'deporte', 'gimnasio', 'salud', 'cupon'
|
||||
]
|
||||
if any(bk in q_lower for bk in benefit_keywords):
|
||||
from datetime import date
|
||||
today_b = date.today()
|
||||
active_b = (
|
||||
InstitutionalBenefit.query
|
||||
.filter(
|
||||
InstitutionalBenefit.is_active.is_(True),
|
||||
InstitutionalBenefit.valid_from <= today_b,
|
||||
or_(
|
||||
InstitutionalBenefit.valid_until.is_(None),
|
||||
InstitutionalBenefit.valid_until >= today_b
|
||||
)
|
||||
)
|
||||
.order_by(InstitutionalBenefit.title.asc())
|
||||
.limit(8)
|
||||
.all()
|
||||
)
|
||||
matching_b = [b for b in active_b if b.applies_to_role(role)]
|
||||
if matching_b:
|
||||
lines.append("\nCONVENIOS Y BENEFICIOS INSTITUCIONALES ACTIVOS:")
|
||||
for ben in matching_b:
|
||||
bld_str = f"en {ben.building.name}" if ben.building else "en Todas las Sedes"
|
||||
coupon_str = f" | Código Cupón: {ben.coupon_code}" if ben.coupon_code else ""
|
||||
lines.append(f"• {ben.title}: {ben.discount_label} en {ben.partner_name} ({ben.category} {bld_str}){coupon_str}. {ben.description or ''}")
|
||||
else:
|
||||
lines.append("\nCONVENIOS Y BENEFICIOS: No se encontraron promociones activas registradas para la consulta.")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
import hmac
|
||||
import hashlib
|
||||
import json
|
||||
import base64
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone, date
|
||||
from typing import Dict, Any, Optional, Tuple, List
|
||||
import jwt
|
||||
|
||||
from config.config import Config
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.building import Building
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.subject import Commission, Subject
|
||||
from schemas.reception_dto import TodayClassDTO
|
||||
|
||||
|
||||
class QRSecurityService:
|
||||
"""
|
||||
Servicio de emisión, validación criptográfica y resolución académica para
|
||||
la Credencial Digital y el Control de Acceso por QR en Recepción (SDD-012).
|
||||
"""
|
||||
|
||||
QR_TOKEN_TYPE = "credential_qr"
|
||||
DEFAULT_VALID_HOURS = 72
|
||||
|
||||
@classmethod
|
||||
def _get_secret(cls) -> str:
|
||||
return getattr(Config, 'SECRET_KEY', 'unicaba-secret-qr-key')
|
||||
|
||||
@classmethod
|
||||
def generate_qr_token(cls, user: User, hours_valid: int = DEFAULT_VALID_HOURS) -> str:
|
||||
"""
|
||||
Emite un token JWT firmado de credencial institucional para el usuario.
|
||||
Contiene identificación, rol, DNI y tiempo de expiración.
|
||||
"""
|
||||
now = datetime.now(timezone.utc)
|
||||
payload = {
|
||||
"sub": str(user.id),
|
||||
"dni": user.document_number or "",
|
||||
"name": user.name or "",
|
||||
"role": (user.role or "ALUMNO").upper(),
|
||||
"type": cls.QR_TOKEN_TYPE,
|
||||
"jti": str(uuid.uuid4())[:8],
|
||||
"iat": now,
|
||||
"exp": now + timedelta(hours=hours_valid)
|
||||
}
|
||||
return jwt.encode(payload, cls._get_secret(), algorithm="HS256")
|
||||
|
||||
@classmethod
|
||||
def decode_and_resolve_user(cls, raw_input: str) -> Tuple[Optional[User], str, str]:
|
||||
"""
|
||||
Decodifica y valida el token escaneado. Soporta:
|
||||
1. Token JWT firmado institucional.
|
||||
2. Formato prefijado 'UNICABA:QR:<token>'.
|
||||
3. Formato fallback por DNI 'DNI:<documento>' o número de documento directo.
|
||||
|
||||
Retorna: (User or None, status: 'AUTORIZADO' | 'DENEGADO' | 'RESTRINGIDO', reason: str)
|
||||
"""
|
||||
if not raw_input or not raw_input.strip():
|
||||
return None, "DENEGADO", "El código escaneado está vacío."
|
||||
|
||||
clean = raw_input.strip()
|
||||
|
||||
# Si viene con prefijo UNICABA:QR:
|
||||
if clean.startswith("UNICABA:QR:"):
|
||||
clean = clean[len("UNICABA:QR:"):].strip()
|
||||
|
||||
# 1. Intentar validar como JWT institucional
|
||||
if clean.count(".") == 2:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
clean,
|
||||
cls._get_secret(),
|
||||
algorithms=["HS256"],
|
||||
options={"verify_exp": True}
|
||||
)
|
||||
if payload.get("type") != cls.QR_TOKEN_TYPE:
|
||||
return None, "DENEGADO", "El token no corresponde a una credencial institucional válida."
|
||||
|
||||
user_id = payload.get("sub")
|
||||
user = User.query.get(int(user_id)) if user_id else None
|
||||
if not user:
|
||||
return None, "DENEGADO", "Usuario no encontrado en la base de datos."
|
||||
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "La cuenta del usuario se encuentra inactiva o suspendida."
|
||||
|
||||
return user, "AUTORIZADO", "Credencial institucional válida y activa."
|
||||
except jwt.ExpiredSignatureError:
|
||||
return None, "DENEGADO", "La credencial digital ha expirado. El alumno debe abrir su app para renovarla."
|
||||
except jwt.PyJWTError as e:
|
||||
return None, "DENEGADO", f"Firma criptográfica inválida: {str(e)}"
|
||||
|
||||
# 2. Fallback: Lectura de pistola óptica o documento directo (ej: 'DNI:12345678' o '12345678')
|
||||
doc_num = clean
|
||||
if doc_num.upper().startswith("DNI:"):
|
||||
doc_num = doc_num[4:].strip()
|
||||
|
||||
user = User.query.filter_by(document_number=doc_num).first()
|
||||
if user:
|
||||
if not user.is_active:
|
||||
return user, "RESTRINGIDO", "Usuario inactivo en el sistema institucional."
|
||||
return user, "AUTORIZADO", "Identificación validada por documento de identidad."
|
||||
|
||||
return None, "DENEGADO", f"No se encontró ningún estudiante o docente con DNI {doc_num}."
|
||||
|
||||
@classmethod
|
||||
def get_todays_classes_for_user(cls, user: User, target_date: Optional[date] = None) -> List[TodayClassDTO]:
|
||||
"""
|
||||
Recupera el cronograma presencial y virtual asignado para el usuario en la fecha indicada (por defecto hoy).
|
||||
Indica sede, aula física, piso, horarios y nombre del docente.
|
||||
"""
|
||||
ref_date = target_date or date.today()
|
||||
user_role = (user.role or "").lower()
|
||||
classes: List[TodayClassDTO] = []
|
||||
|
||||
start_of_day = datetime.combine(ref_date, datetime.min.time())
|
||||
end_of_day = datetime.combine(ref_date, datetime.max.time())
|
||||
|
||||
# Si el usuario es docente: reservas donde él es el docente asignado
|
||||
if "docente" in user_role or "profesor" in user_role or "teacher" in user_role:
|
||||
reservations = Reservation.query.filter(
|
||||
Reservation.user_id == user.id,
|
||||
Reservation.start_time >= start_of_day,
|
||||
Reservation.start_time <= end_of_day,
|
||||
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
|
||||
for r in reservations:
|
||||
comm = r.commission
|
||||
subj_name = comm.subject.name if (comm and comm.subject) else "Clase Universitaria"
|
||||
comm_name = comm.name if comm else "Comisión"
|
||||
classroom = r.classroom
|
||||
bld = classroom.building_entity if classroom else None
|
||||
|
||||
classes.append(TodayClassDTO(
|
||||
subject_name=subj_name,
|
||||
commission_name=comm_name,
|
||||
classroom_name=classroom.name if classroom else "Aula no asignada",
|
||||
building_name=bld.name if bld else "Sede Central",
|
||||
floor=getattr(classroom, "floor", 1),
|
||||
start_time=r.start_time.strftime("%H:%M"),
|
||||
end_time=r.end_time.strftime("%H:%M"),
|
||||
teacher_name=user.name
|
||||
))
|
||||
return classes
|
||||
|
||||
# Si el usuario es alumno: comisiones donde está inscripto
|
||||
enrollments = StudentEnrollment.query.filter_by(student_id=user.id).all()
|
||||
comm_ids = [e.commission_id for e in enrollments if e.commission_id]
|
||||
|
||||
if not comm_ids:
|
||||
return []
|
||||
|
||||
reservations = Reservation.query.filter(
|
||||
Reservation.commission_id.in_(comm_ids),
|
||||
Reservation.start_time >= start_of_day,
|
||||
Reservation.start_time <= end_of_day,
|
||||
Reservation.status.in_(["CONFIRMED", "PENDING"])
|
||||
).order_by(Reservation.start_time.asc()).all()
|
||||
|
||||
for r in reservations:
|
||||
comm = r.commission
|
||||
subj_name = comm.subject.name if (comm and comm.subject) else "Materia Cursada"
|
||||
comm_name = comm.name if comm else "Comisión"
|
||||
classroom = r.classroom
|
||||
bld = classroom.building_entity if classroom else None
|
||||
teacher_name = r.user.name if r.user else "Docente Titular"
|
||||
|
||||
classes.append(TodayClassDTO(
|
||||
subject_name=subj_name,
|
||||
commission_name=comm_name,
|
||||
classroom_name=classroom.name if classroom else "Aula no asignada",
|
||||
building_name=bld.name if bld else "Sede Central",
|
||||
floor=getattr(classroom, "floor", 1),
|
||||
start_time=r.start_time.strftime("%H:%M"),
|
||||
end_time=r.end_time.strftime("%H:%M"),
|
||||
teacher_name=teacher_name
|
||||
))
|
||||
|
||||
return classes
|
||||
@@ -21,6 +21,8 @@ from routers.dashboard import dashboard_router
|
||||
from routers.optimizer import optimizer_router, genetic_router
|
||||
from routers.ai_chat import router as ai_chat_router
|
||||
from routers.mcp import router as mcp_router
|
||||
from routers.benefits import router as benefits_router
|
||||
from routers.reception import router as reception_router
|
||||
|
||||
# Initialize FastAPI Application
|
||||
app = FastAPI(
|
||||
@@ -57,6 +59,8 @@ app.include_router(ai_chat_router, prefix="/api/chat")
|
||||
app.include_router(ai_chat_router, prefix="/api/v1/chat")
|
||||
app.include_router(mcp_router, prefix="/api/mcp")
|
||||
app.include_router(mcp_router, prefix="/api/v1/mcp")
|
||||
app.include_router(benefits_router)
|
||||
app.include_router(reception_router)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -128,6 +128,8 @@ def generate_system_prompt_for_role(
|
||||
" * Clima y temperatura en tiempo real en UniCABA Sede Central (vía integración meteorológica).\n"
|
||||
" * Rutas y cómo llegar a la universidad con Google Maps y medios de transporte público.\n"
|
||||
" * Flujo operativo de 9 pasos para Bedelía, optimizador genético y soporte en Moodle.\n"
|
||||
" * Convenios comerciales y beneficios institucionales activos (descuentos en cafeterías, librerías y comercios adheridos).\n"
|
||||
" - Si preguntan por convenios, promociones o descuentos (ej: en cafeterías o librerías), responde citando el comercio, descuento y condiciones del estado en vivo.\n"
|
||||
" - Si un alumno pregunta por sus notas o regularidad, responde con las notas y condición académica según 'ESTADO EN VIVO DEL SISTEMA'.\n"
|
||||
" - Si preguntan cuántas comisiones hay sin asignar o cuál es la comisión que más alumnos tiene, responde con los datos operativos del estado en vivo.\n"
|
||||
" - Si preguntan por profesores registrados o si alguno se llama de cierta forma (ej. Sergio), responde en base a la nómina de docentes del estado en vivo.\n"
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
from datetime import date
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import or_
|
||||
|
||||
from app import db
|
||||
from app.models.institutional_benefit import InstitutionalBenefit
|
||||
from app.models.building import Building
|
||||
from app.models.user import User
|
||||
from app.services.audit_service import AuditService
|
||||
from dependencies import get_current_user, get_optional_current_user, require_roles
|
||||
from schemas.benefit_dto import (
|
||||
BenefitCreateDTO,
|
||||
BenefitUpdateDTO,
|
||||
BenefitResponseDTO,
|
||||
BenefitListResponseDTO
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/benefits", tags=["Benefits & Convenios"])
|
||||
|
||||
|
||||
def _to_response_dto(benefit: InstitutionalBenefit) -> BenefitResponseDTO:
|
||||
"""Convierte una entidad InstitutionalBenefit a BenefitResponseDTO."""
|
||||
return BenefitResponseDTO(
|
||||
id=benefit.id,
|
||||
title=benefit.title,
|
||||
partner_name=benefit.partner_name,
|
||||
category=benefit.category,
|
||||
discount_label=benefit.discount_label,
|
||||
description=benefit.description,
|
||||
terms_conditions=benefit.terms_conditions,
|
||||
target_roles=benefit.target_roles,
|
||||
building_id=benefit.building_id,
|
||||
building_name=benefit.building.name if benefit.building else "Todas las Sedes",
|
||||
coupon_code=benefit.coupon_code,
|
||||
valid_from=benefit.valid_from,
|
||||
valid_until=benefit.valid_until,
|
||||
is_active=benefit.is_active,
|
||||
is_currently_valid=benefit.is_currently_valid,
|
||||
image_url=benefit.image_url,
|
||||
created_by_user_id=benefit.created_by_user_id,
|
||||
created_at=benefit.created_at,
|
||||
updated_at=benefit.updated_at
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=BenefitListResponseDTO)
|
||||
@router.get("/", response_model=BenefitListResponseDTO)
|
||||
def list_benefits(
|
||||
role: Optional[str] = Query(None, description="Filtrar por rol destino: alumno, docente, bedelia"),
|
||||
category: Optional[str] = Query(None, description="Filtrar por categoría (ej: GASTRONOMIA, LIBRERIA)"),
|
||||
building_id: Optional[int] = Query(None, description="Filtrar por sede específica"),
|
||||
active_only: bool = Query(True, description="Si es True, sólo retorna beneficios activos y vigentes"),
|
||||
search: Optional[str] = Query(None, description="Búsqueda textual en título, comercio o descripción"),
|
||||
current_user: Optional[User] = Depends(get_optional_current_user)
|
||||
):
|
||||
"""
|
||||
Lista el catálogo de convenios institucionales y promociones disponibles.
|
||||
Permite filtrar por categoría, rol objetivo, sede y búsqueda textual.
|
||||
"""
|
||||
query = InstitutionalBenefit.query
|
||||
|
||||
# Si se pide active_only o si el usuario no es admin/bedelía, se muestran sólo activos
|
||||
is_staff = current_user and (current_user.role or "").upper() in ["ADMIN", "BEDELIA"]
|
||||
if active_only or not is_staff:
|
||||
today = date.today()
|
||||
query = query.filter(
|
||||
InstitutionalBenefit.is_active.is_(True),
|
||||
InstitutionalBenefit.valid_from <= today,
|
||||
or_(
|
||||
InstitutionalBenefit.valid_until.is_(None),
|
||||
InstitutionalBenefit.valid_until >= today
|
||||
)
|
||||
)
|
||||
|
||||
if category and category.strip():
|
||||
query = query.filter(InstitutionalBenefit.category.ilike(category.strip()))
|
||||
|
||||
if building_id:
|
||||
query = query.filter(
|
||||
or_(
|
||||
InstitutionalBenefit.building_id.is_(None),
|
||||
InstitutionalBenefit.building_id == building_id
|
||||
)
|
||||
)
|
||||
|
||||
if search and search.strip():
|
||||
term = f"%{search.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
InstitutionalBenefit.title.ilike(term),
|
||||
InstitutionalBenefit.partner_name.ilike(term),
|
||||
InstitutionalBenefit.description.ilike(term),
|
||||
InstitutionalBenefit.coupon_code.ilike(term)
|
||||
)
|
||||
)
|
||||
|
||||
all_benefits: List[InstitutionalBenefit] = query.order_by(InstitutionalBenefit.title.asc()).all()
|
||||
|
||||
# Filtrar por rol efectivo si se solicitó o si el usuario está autenticado
|
||||
effective_role = role
|
||||
if not effective_role and current_user and not is_staff:
|
||||
effective_role = current_user.role
|
||||
|
||||
filtered_items = []
|
||||
for b in all_benefits:
|
||||
if effective_role and not b.applies_to_role(effective_role):
|
||||
continue
|
||||
filtered_items.append(_to_response_dto(b))
|
||||
|
||||
# Obtener categorías únicas presentes en la base
|
||||
raw_cats = db.session.query(InstitutionalBenefit.category).distinct().all()
|
||||
categories = sorted(list({c[0] for c in raw_cats if c[0]}))
|
||||
|
||||
return BenefitListResponseDTO(
|
||||
total=len(filtered_items),
|
||||
items=filtered_items,
|
||||
categories=categories
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{benefit_id}", response_model=BenefitResponseDTO)
|
||||
def get_benefit_by_id(benefit_id: int):
|
||||
"""Obtiene el detalle completo de un convenio por su identificador."""
|
||||
benefit = InstitutionalBenefit.query.get(benefit_id)
|
||||
if not benefit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Convenio con ID {benefit_id} no encontrado."
|
||||
)
|
||||
return _to_response_dto(benefit)
|
||||
|
||||
|
||||
@router.post("", response_model=BenefitResponseDTO, status_code=status.HTTP_201_CREATED)
|
||||
@router.post("/", response_model=BenefitResponseDTO, status_code=status.HTTP_201_CREATED)
|
||||
def create_benefit(
|
||||
payload: BenefitCreateDTO,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""
|
||||
Crea un nuevo convenio o beneficio institucional.
|
||||
Operación reservada para personal de Bedelía y Administradores.
|
||||
"""
|
||||
if payload.building_id:
|
||||
b_exists = Building.query.get(payload.building_id)
|
||||
if not b_exists:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"La sede con ID {payload.building_id} no existe."
|
||||
)
|
||||
|
||||
if payload.valid_until and payload.valid_until < payload.valid_from:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="La fecha de vencimiento (valid_until) no puede ser anterior al inicio de vigencia."
|
||||
)
|
||||
|
||||
benefit = InstitutionalBenefit(
|
||||
title=payload.title.strip(),
|
||||
partner_name=payload.partner_name.strip(),
|
||||
category=(payload.category or "GENERAL").strip().upper(),
|
||||
discount_label=payload.discount_label.strip(),
|
||||
description=payload.description.strip() if payload.description else None,
|
||||
terms_conditions=payload.terms_conditions.strip() if payload.terms_conditions else None,
|
||||
target_roles=(payload.target_roles or "ALL").strip().upper(),
|
||||
building_id=payload.building_id,
|
||||
coupon_code=payload.coupon_code.strip() if payload.coupon_code else None,
|
||||
valid_from=payload.valid_from,
|
||||
valid_until=payload.valid_until,
|
||||
is_active=payload.is_active,
|
||||
image_url=payload.image_url.strip() if payload.image_url else None,
|
||||
created_by_user_id=current_user.id
|
||||
)
|
||||
|
||||
db.session.add(benefit)
|
||||
db.session.commit()
|
||||
|
||||
# Registro de auditoría
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="CREATE_BENEFIT",
|
||||
module="institutional_benefit",
|
||||
entity_id=benefit.id,
|
||||
details={"title": benefit.title, "partner": benefit.partner_name, "discount": benefit.discount_label}
|
||||
)
|
||||
|
||||
return _to_response_dto(benefit)
|
||||
|
||||
|
||||
@router.put("/{benefit_id}", response_model=BenefitResponseDTO)
|
||||
def update_benefit(
|
||||
benefit_id: int,
|
||||
payload: BenefitUpdateDTO,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""
|
||||
Actualiza la información de un convenio existente.
|
||||
Operación reservada para personal de Bedelía y Administradores.
|
||||
"""
|
||||
benefit = InstitutionalBenefit.query.get(benefit_id)
|
||||
if not benefit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Convenio con ID {benefit_id} no encontrado."
|
||||
)
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
if "building_id" in data and data["building_id"]:
|
||||
b_exists = Building.query.get(data["building_id"])
|
||||
if not b_exists:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"La sede con ID {data['building_id']} no existe."
|
||||
)
|
||||
|
||||
new_from = data.get("valid_from", benefit.valid_from)
|
||||
new_until = data.get("valid_until", benefit.valid_until)
|
||||
if new_until and new_from and new_until < new_from:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="La fecha de vencimiento no puede ser anterior a la fecha de inicio."
|
||||
)
|
||||
|
||||
for field, val in data.items():
|
||||
if isinstance(val, str) and field in ["category", "target_roles"]:
|
||||
setattr(benefit, field, val.strip().upper())
|
||||
elif isinstance(val, str):
|
||||
setattr(benefit, field, val.strip())
|
||||
else:
|
||||
setattr(benefit, field, val)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="UPDATE_BENEFIT",
|
||||
module="institutional_benefit",
|
||||
entity_id=benefit.id,
|
||||
details={"title": benefit.title, "updated_fields": list(data.keys())}
|
||||
)
|
||||
|
||||
return _to_response_dto(benefit)
|
||||
|
||||
|
||||
@router.patch("/{benefit_id}/toggle-status", response_model=BenefitResponseDTO)
|
||||
def toggle_benefit_status(
|
||||
benefit_id: int,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""Activa o pausa la publicación de un convenio."""
|
||||
benefit = InstitutionalBenefit.query.get(benefit_id)
|
||||
if not benefit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Convenio con ID {benefit_id} no encontrado."
|
||||
)
|
||||
|
||||
benefit.is_active = not benefit.is_active
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="TOGGLE_BENEFIT_STATUS",
|
||||
module="institutional_benefit",
|
||||
entity_id=benefit.id,
|
||||
details={"is_active": benefit.is_active}
|
||||
)
|
||||
|
||||
return _to_response_dto(benefit)
|
||||
|
||||
|
||||
@router.delete("/{benefit_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_benefit(
|
||||
benefit_id: int,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA"]))
|
||||
):
|
||||
"""Elimina permanentemente un convenio."""
|
||||
benefit = InstitutionalBenefit.query.get(benefit_id)
|
||||
if not benefit:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Convenio con ID {benefit_id} no encontrado."
|
||||
)
|
||||
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="DELETE_BENEFIT",
|
||||
module="institutional_benefit",
|
||||
entity_id=benefit.id,
|
||||
details={"title": benefit.title, "partner": benefit.partner_name}
|
||||
)
|
||||
|
||||
db.session.delete(benefit)
|
||||
db.session.commit()
|
||||
|
||||
return None
|
||||
@@ -0,0 +1,159 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional, List
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app import db
|
||||
from app.models.user import User
|
||||
from app.models.building import Building
|
||||
from app.models.access_log_qr import AccessLogQR
|
||||
from app.services.audit_service import AuditService
|
||||
from app.services.qr_security_service import QRSecurityService
|
||||
from dependencies import get_current_user, require_roles
|
||||
from schemas.reception_dto import (
|
||||
QRVerificationRequestDTO,
|
||||
QRVerificationResponseDTO,
|
||||
AccessLogResponseDTO,
|
||||
AccessLogListResponseDTO
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/api/v1/reception", tags=["Reception & Access Control"])
|
||||
|
||||
|
||||
@router.post("/verify-qr", response_model=QRVerificationResponseDTO)
|
||||
def verify_qr_and_register_access(
|
||||
payload: QRVerificationRequestDTO,
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA", "RECEPCION"]))
|
||||
):
|
||||
"""
|
||||
Verifica un código QR institucional en la mesa de entrada o torniquete de acceso.
|
||||
Registra el ingreso en AccessLogQR y retorna la identidad del alumno/docente
|
||||
junto con sus clases y aulas asignadas para el día de hoy.
|
||||
"""
|
||||
now_utc = datetime.now(timezone.utc).replace(tzinfo=None)
|
||||
user, auth_status, reason = QRSecurityService.decode_and_resolve_user(payload.qr_token)
|
||||
|
||||
# Si se identificó un usuario
|
||||
if user:
|
||||
classes = QRSecurityService.get_todays_classes_for_user(user)
|
||||
|
||||
# Registro en la base de accesos
|
||||
access_log = AccessLogQR(
|
||||
user_id=user.id,
|
||||
building_id=payload.building_id,
|
||||
scanned_by_user_id=current_user.id,
|
||||
scanned_at=now_utc,
|
||||
status=auth_status,
|
||||
reason=payload.notes or reason
|
||||
)
|
||||
db.session.add(access_log)
|
||||
db.session.commit()
|
||||
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="QR_ACCESS_SCAN",
|
||||
module="reception",
|
||||
entity_id=access_log.id,
|
||||
details={
|
||||
"target_user_id": user.id,
|
||||
"status": auth_status,
|
||||
"building_id": payload.building_id,
|
||||
"classes_today_count": len(classes)
|
||||
}
|
||||
)
|
||||
|
||||
message = (
|
||||
f"Acceso autorizado para {user.name}."
|
||||
if auth_status == "AUTORIZADO"
|
||||
else f"Acceso observado: {reason}"
|
||||
)
|
||||
|
||||
return QRVerificationResponseDTO(
|
||||
status=auth_status,
|
||||
message=message,
|
||||
user_id=user.id,
|
||||
user_name=user.name,
|
||||
user_dni=user.document_number,
|
||||
user_role=(user.role or "ALUMNO").upper(),
|
||||
matricula_status="REGULAR / ACTIVO" if user.is_active else "SUSPENDIDO / INACTIVO",
|
||||
photo_url=None,
|
||||
todays_classes=classes,
|
||||
scanned_at=now_utc.isoformat()
|
||||
)
|
||||
|
||||
# Si el código QR es inválido o el usuario no existe
|
||||
AuditService.log(
|
||||
user_id=current_user.id,
|
||||
action="QR_ACCESS_FAILED",
|
||||
module="reception",
|
||||
entity_id=None,
|
||||
details={"reason": reason, "raw_snippet": payload.qr_token[:15]}
|
||||
)
|
||||
|
||||
return QRVerificationResponseDTO(
|
||||
status="DENEGADO",
|
||||
message=reason,
|
||||
user_id=None,
|
||||
user_name=None,
|
||||
user_dni=None,
|
||||
user_role=None,
|
||||
matricula_status="NO REGISTRADO",
|
||||
photo_url=None,
|
||||
todays_classes=[],
|
||||
scanned_at=now_utc.isoformat()
|
||||
)
|
||||
|
||||
|
||||
@router.get("/recent-logs", response_model=AccessLogListResponseDTO)
|
||||
def get_recent_access_logs(
|
||||
building_id: Optional[int] = Query(None, description="Filtrar por sede específica"),
|
||||
limit: int = Query(50, ge=1, le=200, description="Cantidad máxima de registros a recuperar"),
|
||||
current_user: User = Depends(require_roles(["ADMIN", "BEDELIA", "RECEPCION"]))
|
||||
):
|
||||
"""
|
||||
Retorna los últimos ingresos registrados en el punto de acceso.
|
||||
Permite monitoreo en tiempo real para el personal de Recepción y Seguridad.
|
||||
"""
|
||||
query = AccessLogQR.query
|
||||
if building_id:
|
||||
query = query.filter_by(building_id=building_id)
|
||||
|
||||
logs: List[AccessLogQR] = query.order_by(AccessLogQR.scanned_at.desc()).limit(limit).all()
|
||||
|
||||
items = []
|
||||
for l in logs:
|
||||
items.append(AccessLogResponseDTO(
|
||||
id=l.id,
|
||||
user_name=l.user.name if l.user else "Usuario no disponible",
|
||||
user_dni=l.user.document_number if l.user else None,
|
||||
user_role=l.user.role if l.user else None,
|
||||
building_name=l.building.name if l.building else "Sede no especificada",
|
||||
scanned_by_name=l.scanned_by.name if l.scanned_by else "Recepción",
|
||||
scanned_at=l.scanned_at.isoformat(),
|
||||
status=l.status,
|
||||
reason=l.reason
|
||||
))
|
||||
|
||||
return AccessLogListResponseDTO(
|
||||
total=len(items),
|
||||
items=items
|
||||
)
|
||||
|
||||
|
||||
@router.get("/my-qr-token")
|
||||
def get_my_credential_qr_token(
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""
|
||||
Genera y entrega el token criptográfico del código QR para la credencial digital
|
||||
del usuario autenticado (estudiante o docente).
|
||||
"""
|
||||
token = QRSecurityService.generate_qr_token(current_user)
|
||||
return {
|
||||
"status": "success",
|
||||
"qr_token": token,
|
||||
"user_id": current_user.id,
|
||||
"user_name": current_user.name,
|
||||
"user_dni": current_user.document_number,
|
||||
"user_role": (current_user.role or "ALUMNO").upper(),
|
||||
"expires_in_hours": QRSecurityService.DEFAULT_VALID_HOURS
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
from datetime import date, datetime
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
|
||||
|
||||
class BenefitBaseDTO(BaseModel):
|
||||
title: str = Field(..., min_length=3, max_length=150, description="Título del beneficio o promoción")
|
||||
partner_name: str = Field(..., min_length=2, max_length=120, description="Comercio o entidad adherida")
|
||||
category: str = Field("GENERAL", max_length=50, description="Categoría: GASTRONOMIA, LIBRERIA, TECNOLOGIA, SALUD_DEPORTE, IDIOMAS, etc.")
|
||||
discount_label: str = Field(..., min_length=2, max_length=80, description="Etiqueta visible del descuento (ej: '20% OFF', '2x1')")
|
||||
description: Optional[str] = Field(None, description="Detalle del convenio y cómo aprovecharlo")
|
||||
terms_conditions: Optional[str] = Field(None, description="Términos, condiciones y restricciones")
|
||||
target_roles: str = Field("ALL", max_length=100, description="Roles habilitados: ALL, ALUMNO, DOCENTE, BEDELIA")
|
||||
building_id: Optional[int] = Field(None, ge=1, description="ID de sede aplicable, o null para todas")
|
||||
coupon_code: Optional[str] = Field(None, max_length=50, description="Código de cupón o promoción alfanumérico")
|
||||
valid_from: date = Field(default_factory=date.today, description="Fecha de inicio de vigencia")
|
||||
valid_until: Optional[date] = Field(None, description="Fecha de vencimiento (null si es indefinido)")
|
||||
is_active: bool = Field(True, description="Estado de publicación activo/inactivo")
|
||||
image_url: Optional[str] = Field(None, max_length=255, description="URL de logotipo o imagen del comercio")
|
||||
|
||||
|
||||
class BenefitCreateDTO(BenefitBaseDTO):
|
||||
pass
|
||||
|
||||
|
||||
class BenefitUpdateDTO(BaseModel):
|
||||
title: Optional[str] = Field(None, min_length=3, max_length=150)
|
||||
partner_name: Optional[str] = Field(None, min_length=2, max_length=120)
|
||||
category: Optional[str] = Field(None, max_length=50)
|
||||
discount_label: Optional[str] = Field(None, min_length=2, max_length=80)
|
||||
description: Optional[str] = None
|
||||
terms_conditions: Optional[str] = None
|
||||
target_roles: Optional[str] = Field(None, max_length=100)
|
||||
building_id: Optional[int] = Field(None, ge=1)
|
||||
coupon_code: Optional[str] = Field(None, max_length=50)
|
||||
valid_from: Optional[date] = None
|
||||
valid_until: Optional[date] = None
|
||||
is_active: Optional[bool] = None
|
||||
image_url: Optional[str] = Field(None, max_length=255)
|
||||
|
||||
|
||||
class BenefitResponseDTO(BenefitBaseDTO):
|
||||
id: int
|
||||
building_name: Optional[str] = None
|
||||
is_currently_valid: bool = True
|
||||
created_by_user_id: Optional[int] = None
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class BenefitListResponseDTO(BaseModel):
|
||||
total: int = Field(..., ge=0)
|
||||
items: List[BenefitResponseDTO]
|
||||
categories: List[str] = Field(default_factory=list)
|
||||
@@ -0,0 +1,52 @@
|
||||
from datetime import datetime
|
||||
from typing import Optional, List
|
||||
from pydantic import BaseModel, Field, ConfigDict
|
||||
|
||||
|
||||
class TodayClassDTO(BaseModel):
|
||||
subject_name: str = Field(..., description="Nombre de la asignatura")
|
||||
commission_name: str = Field(..., description="Nombre o código de la comisión")
|
||||
classroom_name: str = Field(..., description="Aula asignada (física o virtual)")
|
||||
building_name: str = Field(..., description="Sede o edificio")
|
||||
floor: Optional[int] = Field(None, description="Piso del aula")
|
||||
start_time: str = Field(..., description="Hora de inicio (HH:MM)")
|
||||
end_time: str = Field(..., description="Hora de finalización (HH:MM)")
|
||||
teacher_name: Optional[str] = Field(None, description="Docente a cargo de la clase")
|
||||
|
||||
|
||||
class QRVerificationRequestDTO(BaseModel):
|
||||
qr_token: str = Field(..., min_length=4, description="Token seguro o contenido del código QR")
|
||||
building_id: Optional[int] = Field(None, ge=1, description="ID de sede donde se ubica el punto de acceso")
|
||||
notes: Optional[str] = Field(None, max_length=200, description="Observaciones opcionales del operador de recepción")
|
||||
|
||||
|
||||
class QRVerificationResponseDTO(BaseModel):
|
||||
status: str = Field("AUTORIZADO", description="Resultado: AUTORIZADO, DENEGADO o RESTRINGIDO")
|
||||
message: str = Field(..., description="Mensaje explicativo del resultado del escaneo")
|
||||
user_id: Optional[int] = None
|
||||
user_name: Optional[str] = None
|
||||
user_dni: Optional[str] = None
|
||||
user_role: Optional[str] = None
|
||||
matricula_status: Optional[str] = None
|
||||
photo_url: Optional[str] = None
|
||||
todays_classes: List[TodayClassDTO] = Field(default_factory=list, description="Clases presenciales o virtuales asignadas para hoy")
|
||||
scanned_at: str = Field(..., description="Timestamp de registro del escaneo")
|
||||
|
||||
|
||||
class AccessLogResponseDTO(BaseModel):
|
||||
id: int
|
||||
user_name: str
|
||||
user_dni: Optional[str] = None
|
||||
user_role: Optional[str] = None
|
||||
building_name: str
|
||||
scanned_by_name: str
|
||||
scanned_at: str
|
||||
status: str
|
||||
reason: Optional[str] = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
class AccessLogListResponseDTO(BaseModel):
|
||||
total: int
|
||||
items: List[AccessLogResponseDTO]
|
||||
+1
-1
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
|
||||
|
||||
setup(
|
||||
name="edu-space-admin",
|
||||
version="3.8.38",
|
||||
version="3.8.39",
|
||||
description="Administrative interface for Edu-Space Classroom Management System (FastAPI ASGI Core)",
|
||||
author="Edu-Space Development Team",
|
||||
author_email="admin@edu-space.com",
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
backend/tests/test_benefits_and_reception.py - Suite de pruebas para SDD-012.
|
||||
Valida:
|
||||
1. Modelo InstitutionalBenefit y AccessLogQR.
|
||||
2. Emisión y decodificación de tokens QR en QRSecurityService.
|
||||
3. Endpoints RESTful de Beneficios (/api/v1/benefits): permisos, CRUD y validación.
|
||||
4. Endpoints de Recepción (/api/v1/reception): verificación de acceso, registro de logs y cronograma del día.
|
||||
5. Inyección de convenios en LiveContextService para UdeCi.
|
||||
"""
|
||||
from datetime import date, timedelta
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import db
|
||||
from main import app
|
||||
from app.models.user import User
|
||||
from app.models.building import Building
|
||||
from app.models.classroom import Classroom
|
||||
from app.models.subject import Subject, Commission
|
||||
from app.models.enrollment import StudentEnrollment
|
||||
from app.models.reservation import Reservation
|
||||
from app.models.institutional_benefit import InstitutionalBenefit
|
||||
from app.models.access_log_qr import AccessLogQR
|
||||
from app.services.jwt_service import JWTService
|
||||
from app.services.qr_security_service import QRSecurityService
|
||||
from app.services.live_context_service import LiveContextService
|
||||
|
||||
|
||||
def _get_or_create_user(email: str, name: str, role: str) -> User:
|
||||
user = User.query.filter_by(email=email).first()
|
||||
if not user:
|
||||
doc_num = f"38{abs(hash(email)) % 1000000:06d}"
|
||||
user = User(
|
||||
email=email,
|
||||
name=name,
|
||||
role=role,
|
||||
document_number=doc_num,
|
||||
is_active=True
|
||||
)
|
||||
user.set_password("Secret123!")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
return user
|
||||
|
||||
|
||||
def test_institutional_benefit_model_and_validity(init_database):
|
||||
"""Verifica lógica de dominio del modelo InstitutionalBenefit."""
|
||||
today = date.today()
|
||||
benefit = InstitutionalBenefit(
|
||||
title="20% en Cafetería Central",
|
||||
partner_name="Café UniCABA",
|
||||
category="GASTRONOMIA",
|
||||
discount_label="20% OFF",
|
||||
target_roles="ALUMNO,DOCENTE",
|
||||
valid_from=today,
|
||||
valid_until=today + timedelta(days=30),
|
||||
is_active=True
|
||||
)
|
||||
assert benefit.is_currently_valid is True
|
||||
assert benefit.applies_to_role("alumno") is True
|
||||
assert benefit.applies_to_role("docente") is True
|
||||
assert benefit.applies_to_role("bedelia") is False
|
||||
|
||||
# Desactivar
|
||||
benefit.is_active = False
|
||||
assert benefit.is_currently_valid is False
|
||||
|
||||
# Vencido
|
||||
benefit.is_active = True
|
||||
benefit.valid_until = today - timedelta(days=1)
|
||||
assert benefit.is_currently_valid is False
|
||||
|
||||
|
||||
def test_qr_security_service_generate_and_decode(init_database):
|
||||
"""Verifica emisión criptográfica de tokens QR y resolución tolerante."""
|
||||
student = _get_or_create_user("test_student_qr@unicaba.edu.ar", "Ana Gómez", "ALUMNO")
|
||||
token = QRSecurityService.generate_qr_token(student, hours_valid=48)
|
||||
assert token and token.count(".") == 2
|
||||
|
||||
# Decodificación de token institucional válido
|
||||
resolved_user, status, reason = QRSecurityService.decode_and_resolve_user(token)
|
||||
assert status == "AUTORIZADO"
|
||||
assert resolved_user is not None
|
||||
assert resolved_user.id == student.id
|
||||
|
||||
# Con prefijo institucional UNICABA:QR:
|
||||
prefixed = f"UNICABA:QR:{token}"
|
||||
resolved_pref, status_p, _ = QRSecurityService.decode_and_resolve_user(prefixed)
|
||||
assert status_p == "AUTORIZADO"
|
||||
assert resolved_pref.id == student.id
|
||||
|
||||
# Fallback por DNI
|
||||
if student.document_number:
|
||||
resolved_dni, status_d, _ = QRSecurityService.decode_and_resolve_user(f"DNI:{student.document_number}")
|
||||
assert status_d == "AUTORIZADO"
|
||||
assert resolved_dni.id == student.id
|
||||
|
||||
# Token corrupto o inválido
|
||||
res_fake, status_f, reason_f = QRSecurityService.decode_and_resolve_user("token_invalido_corrupto")
|
||||
assert status_f == "DENEGADO"
|
||||
assert res_fake is None
|
||||
|
||||
|
||||
def test_benefits_crud_api_flow(init_database):
|
||||
"""Verifica operaciones CRUD del endpoint /api/v1/benefits con permisos de Bedelía."""
|
||||
client = TestClient(app)
|
||||
admin = _get_or_create_user("test_admin_benefits@unicaba.edu.ar", "Admin General", "ADMIN")
|
||||
tokens = JWTService.generate_tokens(admin)
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
# 1. Crear nuevo beneficio (POST 201)
|
||||
payload = {
|
||||
"title": "15% en Librería Universitaria",
|
||||
"partner_name": "Librería CABA",
|
||||
"category": "LIBRERIA",
|
||||
"discount_label": "15% OFF",
|
||||
"description": "Descuento en apuntes y libros presentando credencial.",
|
||||
"target_roles": "ALL",
|
||||
"valid_from": str(date.today()),
|
||||
"valid_until": str(date.today() + timedelta(days=60)),
|
||||
"is_active": True,
|
||||
"coupon_code": "LIBRO15"
|
||||
}
|
||||
create_resp = client.post("/api/v1/benefits", json=payload, headers=headers)
|
||||
assert create_resp.status_code == 201
|
||||
created_data = create_resp.json()
|
||||
benefit_id = created_data["id"]
|
||||
assert created_data["title"] == payload["title"]
|
||||
assert created_data["discount_label"] == "15% OFF"
|
||||
|
||||
# 2. Listar beneficios (GET 200)
|
||||
list_resp = client.get("/api/v1/benefits")
|
||||
assert list_resp.status_code == 200
|
||||
list_data = list_resp.json()
|
||||
assert list_data["total"] >= 1
|
||||
assert any(b["id"] == benefit_id for b in list_data["items"])
|
||||
|
||||
# 3. Consultar por ID (GET 200)
|
||||
get_resp = client.get(f"/api/v1/benefits/{benefit_id}")
|
||||
assert get_resp.status_code == 200
|
||||
assert get_resp.json()["coupon_code"] == "LIBRO15"
|
||||
|
||||
# 4. Actualizar beneficio (PUT 200)
|
||||
update_resp = client.put(
|
||||
f"/api/v1/benefits/{benefit_id}",
|
||||
json={"discount_label": "25% OFF", "title": "25% en Librería Universitaria"},
|
||||
headers=headers
|
||||
)
|
||||
assert update_resp.status_code == 200
|
||||
assert update_resp.json()["discount_label"] == "25% OFF"
|
||||
|
||||
# 5. Toggle de estado activo (PATCH 200)
|
||||
toggle_resp = client.patch(f"/api/v1/benefits/{benefit_id}/toggle-status", headers=headers)
|
||||
assert toggle_resp.status_code == 200
|
||||
assert toggle_resp.json()["is_active"] is False
|
||||
|
||||
# 6. Eliminar (DELETE 204)
|
||||
del_resp = client.delete(f"/api/v1/benefits/{benefit_id}", headers=headers)
|
||||
assert del_resp.status_code == 204
|
||||
|
||||
# 7. Verificar que ya no existe (GET 404)
|
||||
check_resp = client.get(f"/api/v1/benefits/{benefit_id}")
|
||||
assert check_resp.status_code == 404
|
||||
|
||||
|
||||
def test_benefits_role_access_control(init_database):
|
||||
"""Verifica que un Alumno no pueda crear ni modificar convenios (403 Forbidden)."""
|
||||
client = TestClient(app)
|
||||
student = _get_or_create_user("test_student_forbidden@unicaba.edu.ar", "Alumno Prueba", "ALUMNO")
|
||||
tokens = JWTService.generate_tokens(student)
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
payload = {
|
||||
"title": "Intento Ilegal",
|
||||
"partner_name": "Hack",
|
||||
"discount_label": "99% OFF",
|
||||
"valid_from": str(date.today())
|
||||
}
|
||||
resp = client.post("/api/v1/benefits", json=payload, headers=headers)
|
||||
assert resp.status_code == 403
|
||||
|
||||
|
||||
def test_reception_verify_qr_authorized_and_denied(init_database):
|
||||
"""Verifica escaneo de código QR en Recepción con registro de log y cronograma."""
|
||||
client = TestClient(app)
|
||||
staff = _get_or_create_user("test_receptionist@unicaba.edu.ar", "Mesa Entrada", "BEDELIA")
|
||||
tokens = JWTService.generate_tokens(staff)
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
student = _get_or_create_user("test_student_access@unicaba.edu.ar", "Lucas Martín", "ALUMNO")
|
||||
qr_token = QRSecurityService.generate_qr_token(student)
|
||||
|
||||
# 1. Escaneo válido
|
||||
scan_payload = {
|
||||
"qr_token": qr_token,
|
||||
"building_id": None,
|
||||
"notes": "Ingreso por puerta principal"
|
||||
}
|
||||
resp = client.post("/api/v1/reception/verify-qr", json=scan_payload, headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "AUTORIZADO"
|
||||
assert data["user_name"] == "Lucas Martín"
|
||||
assert "todays_classes" in data
|
||||
|
||||
# 2. Verificar que se persistió en AccessLogQR
|
||||
log = AccessLogQR.query.filter_by(user_id=student.id).order_by(AccessLogQR.scanned_at.desc()).first()
|
||||
assert log is not None
|
||||
assert log.status == "AUTORIZADO"
|
||||
assert log.scanned_by_user_id == staff.id
|
||||
|
||||
# 3. Escaneo de código corrupto
|
||||
bad_resp = client.post("/api/v1/reception/verify-qr", json={"qr_token": "token_falso"}, headers=headers)
|
||||
assert bad_resp.status_code == 200
|
||||
bad_data = bad_resp.json()
|
||||
assert bad_data["status"] == "DENEGADO"
|
||||
|
||||
|
||||
def test_reception_my_qr_token_endpoint(init_database):
|
||||
"""Verifica que el endpoint /api/v1/reception/my-qr-token entregue el token del usuario autenticado."""
|
||||
client = TestClient(app)
|
||||
student = _get_or_create_user("test_my_qr@unicaba.edu.ar", "Valeria Paz", "ALUMNO")
|
||||
tokens = JWTService.generate_tokens(student)
|
||||
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
|
||||
|
||||
resp = client.get("/api/v1/reception/my-qr-token", headers=headers)
|
||||
assert resp.status_code == 200
|
||||
data = resp.json()
|
||||
assert data["status"] == "success"
|
||||
assert "qr_token" in data
|
||||
assert data["user_name"] == "Valeria Paz"
|
||||
|
||||
|
||||
def test_live_context_benefit_search_integration(init_database):
|
||||
"""Verifica que LiveContextService inyecte convenios reales ante consultas de cafetería o descuentos."""
|
||||
benefit = InstitutionalBenefit(
|
||||
title="20% en Cafetería Central",
|
||||
partner_name="Café Martínez",
|
||||
category="GASTRONOMIA",
|
||||
discount_label="20% OFF",
|
||||
description="Válido en desayunos y meriendas",
|
||||
target_roles="ALL",
|
||||
coupon_code="UNICABA20",
|
||||
valid_from=date.today(),
|
||||
is_active=True
|
||||
)
|
||||
db.session.add(benefit)
|
||||
db.session.commit()
|
||||
|
||||
context_output = LiveContextService.get_system_snapshot(
|
||||
role="alumno",
|
||||
query="¿Qué descuentos hay en cafetería hoy?"
|
||||
)
|
||||
|
||||
assert "CONVENIOS Y BENEFICIOS INSTITUCIONALES ACTIVOS" in context_output
|
||||
assert "Café Martínez" in context_output
|
||||
assert "20% OFF" in context_output
|
||||
assert "UNICABA20" in context_output
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "3.8.38",
|
||||
"version": "3.8.39",
|
||||
"description": "",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
|
||||
+10
-3
@@ -86,9 +86,9 @@ const env = nunjucks.configure(path.join(__dirname, '../views'), {
|
||||
});
|
||||
|
||||
// Versiones institucionales del sistema
|
||||
const APP_VERSION = '3.8.38';
|
||||
const FRONTEND_VERSION = '3.8.38';
|
||||
const BACKEND_VERSION = '3.8.38';
|
||||
const APP_VERSION = '3.8.39';
|
||||
const FRONTEND_VERSION = '3.8.39';
|
||||
const BACKEND_VERSION = '3.8.39';
|
||||
|
||||
env.addGlobal('app_version', APP_VERSION);
|
||||
env.addGlobal('frontend_version', FRONTEND_VERSION);
|
||||
@@ -311,6 +311,9 @@ const scheduleRoutes = require('./routes/schedule');
|
||||
const buildingsRoutes = require('./routes/buildings');
|
||||
const adminRoutes = require('./routes/admin');
|
||||
const mySubjectsRoutes = require('./routes/my_subjects');
|
||||
const benefitsRoutes = require('./routes/benefits');
|
||||
const receptionRoutes = require('./routes/reception');
|
||||
const credentialRoutes = require('./routes/credential');
|
||||
|
||||
// Proxy transparente hacia la API REST de FastAPI para llamadas AJAX frontend
|
||||
app.use('/api/v1', async (req, res) => {
|
||||
@@ -403,6 +406,10 @@ app.use('/buildings', buildingsRoutes);
|
||||
app.use('/admin', adminRoutes);
|
||||
app.use('/my_subjects', mySubjectsRoutes);
|
||||
app.use('/mis-materias', mySubjectsRoutes);
|
||||
app.use('/benefits', benefitsRoutes);
|
||||
app.use('/reception', receptionRoutes);
|
||||
app.use('/credential', credentialRoutes);
|
||||
app.use('/credencial', credentialRoutes);
|
||||
|
||||
// Redirección de enlaces heredados de Jinja /main/dashboard preservando query params
|
||||
app.get(['/main/dashboard', '/main'], (req, res) => {
|
||||
|
||||
@@ -7,6 +7,7 @@ const buildUserSession = (decoded) => {
|
||||
const isBedelia = roleStr === 'bedelia';
|
||||
const isDocente = roleStr === 'docente' || roleStr === 'profesor';
|
||||
const isAlumno = roleStr === 'alumno' || roleStr === 'estudiante';
|
||||
const isRecepcion = roleStr === 'recepcion' || roleStr === 'recepción' || roleStr === 'seguridad';
|
||||
const canManage = isAdmin || isBedelia;
|
||||
|
||||
let badgeClass = 'bg-primary text-white';
|
||||
@@ -25,6 +26,10 @@ const buildUserSession = (decoded) => {
|
||||
badgeClass = 'bg-success text-white';
|
||||
badgeIcon = 'bi-mortarboard';
|
||||
badgeLabel = 'Alumno';
|
||||
} else if (isRecepcion) {
|
||||
badgeClass = 'bg-secondary text-white';
|
||||
badgeIcon = 'bi-qr-code-scan';
|
||||
badgeLabel = 'Recepción';
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -39,6 +44,7 @@ const buildUserSession = (decoded) => {
|
||||
is_bedelia: () => isBedelia,
|
||||
is_docente: () => isDocente,
|
||||
is_alumno: () => isAlumno,
|
||||
is_recepcion: () => isRecepcion,
|
||||
can_manage: () => canManage,
|
||||
has_role: (r) => roleStr === (r || '').toLowerCase(),
|
||||
has_permission: (module, action) => {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requireAuth } = require('../middlewares/authMiddleware');
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
const getNormalizedRole = (user) => {
|
||||
const roleStr = (user?.role || '').toLowerCase();
|
||||
if (roleStr.includes('admin')) return 'admin';
|
||||
if (roleStr.includes('bedel')) return 'bedelia';
|
||||
if (roleStr.includes('docent') || roleStr.includes('prof')) return 'docente';
|
||||
if (roleStr.includes('recep')) return 'recepcion';
|
||||
return 'alumno';
|
||||
};
|
||||
|
||||
// GET /benefits — Catálogo interactivo para Alumnos, Docentes y Staff
|
||||
router.get('/', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
const category = req.query.category || '';
|
||||
const search = req.query.search || '';
|
||||
|
||||
let benefits = [];
|
||||
let categories = [];
|
||||
try {
|
||||
const resp = await req.apiClient.get('/benefits', {
|
||||
params: {
|
||||
role,
|
||||
category: category || undefined,
|
||||
search: search || undefined,
|
||||
active_only: true
|
||||
}
|
||||
});
|
||||
if (resp.data) {
|
||||
benefits = resp.data.items || [];
|
||||
categories = resp.data.categories || [];
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Benefits catalog fetch notice:', err.message);
|
||||
}
|
||||
|
||||
res.render('benefits/catalog', {
|
||||
title: 'Club de Beneficios & Convenios — Edu-Space',
|
||||
benefits,
|
||||
categories,
|
||||
currentCategory: category,
|
||||
searchQuery: search,
|
||||
userRole: role,
|
||||
canManage: role === 'admin' || role === 'bedelia'
|
||||
});
|
||||
});
|
||||
|
||||
// GET /benefits/manage — Panel de Gestión ABM para Bedelía y Administradores
|
||||
router.get('/manage', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia') {
|
||||
return res.status(403).redirect('/benefits');
|
||||
}
|
||||
|
||||
let benefits = [];
|
||||
let buildings = [];
|
||||
let categories = [];
|
||||
|
||||
try {
|
||||
const [respBenefits, respBuildings] = await Promise.all([
|
||||
req.apiClient.get('/benefits', { params: { active_only: false } }),
|
||||
req.apiClient.get('/buildings')
|
||||
]);
|
||||
|
||||
if (respBenefits.data) {
|
||||
benefits = respBenefits.data.items || [];
|
||||
categories = respBenefits.data.categories || [];
|
||||
}
|
||||
if (respBuildings.data) {
|
||||
buildings = respBuildings.data.buildings || respBuildings.data || [];
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Benefits manage fetch notice:', err.message);
|
||||
}
|
||||
|
||||
res.render('benefits/manage', {
|
||||
title: 'Gestión de Convenios & Beneficios — Bedelía',
|
||||
benefits,
|
||||
buildings,
|
||||
categories,
|
||||
userRole: role
|
||||
});
|
||||
});
|
||||
|
||||
// POST /benefits — Creación de nuevo convenio
|
||||
router.post('/', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia') {
|
||||
return res.status(403).json({ error: 'Acceso no autorizado' });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
title: req.body.title,
|
||||
partner_name: req.body.partner_name,
|
||||
category: req.body.category || 'GENERAL',
|
||||
discount_label: req.body.discount_label,
|
||||
description: req.body.description || null,
|
||||
terms_conditions: req.body.terms_conditions || null,
|
||||
target_roles: req.body.target_roles || 'ALL',
|
||||
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
|
||||
coupon_code: req.body.coupon_code || null,
|
||||
valid_from: req.body.valid_from || new Date().toISOString().split('T')[0],
|
||||
valid_until: req.body.valid_until || null,
|
||||
is_active: req.body.is_active === 'true' || req.body.is_active === true || req.body.is_active === 'on',
|
||||
image_url: req.body.image_url || null
|
||||
};
|
||||
|
||||
const resp = await req.apiClient.post('/benefits', payload);
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.status(201).json(resp.data);
|
||||
}
|
||||
res.redirect('/benefits/manage?msg=created');
|
||||
} catch (err) {
|
||||
console.error('Error creating benefit:', err.response?.data || err.message);
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
|
||||
}
|
||||
res.redirect('/benefits/manage?err=' + encodeURIComponent(err.response?.data?.detail || 'Error al guardar'));
|
||||
}
|
||||
});
|
||||
|
||||
// POST /benefits/:id/edit — Edición de convenio
|
||||
router.post('/:id/edit', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia') {
|
||||
return res.status(403).json({ error: 'Acceso no autorizado' });
|
||||
}
|
||||
|
||||
try {
|
||||
const benefitId = req.params.id;
|
||||
const payload = {
|
||||
title: req.body.title,
|
||||
partner_name: req.body.partner_name,
|
||||
category: req.body.category,
|
||||
discount_label: req.body.discount_label,
|
||||
description: req.body.description || null,
|
||||
terms_conditions: req.body.terms_conditions || null,
|
||||
target_roles: req.body.target_roles,
|
||||
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
|
||||
coupon_code: req.body.coupon_code || null,
|
||||
valid_from: req.body.valid_from,
|
||||
valid_until: req.body.valid_until || null,
|
||||
is_active: req.body.is_active === 'true' || req.body.is_active === true || req.body.is_active === 'on',
|
||||
image_url: req.body.image_url || null
|
||||
};
|
||||
|
||||
const resp = await req.apiClient.put(`/benefits/${benefitId}`, payload);
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.json(resp.data);
|
||||
}
|
||||
res.redirect('/benefits/manage?msg=updated');
|
||||
} catch (err) {
|
||||
console.error('Error updating benefit:', err.response?.data || err.message);
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
|
||||
}
|
||||
res.redirect('/benefits/manage?err=' + encodeURIComponent(err.response?.data?.detail || 'Error al actualizar'));
|
||||
}
|
||||
});
|
||||
|
||||
// POST /benefits/:id/toggle — Switch de publicación rápido
|
||||
router.post('/:id/toggle', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia') {
|
||||
return res.status(403).json({ error: 'Acceso no autorizado' });
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await req.apiClient.patch(`/benefits/${req.params.id}/toggle-status`);
|
||||
res.json(resp.data);
|
||||
} catch (err) {
|
||||
res.status(err.response?.status || 500).json(err.response?.data || { error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
// POST /benefits/:id/delete — Eliminación
|
||||
router.post('/:id/delete', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia') {
|
||||
return res.status(403).json({ error: 'Acceso no autorizado' });
|
||||
}
|
||||
|
||||
try {
|
||||
await req.apiClient.delete(`/benefits/${req.params.id}`);
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.json({ success: true });
|
||||
}
|
||||
res.redirect('/benefits/manage?msg=deleted');
|
||||
} catch (err) {
|
||||
if (req.xhr || req.headers.accept?.includes('application/json')) {
|
||||
return res.status(err.response?.status || 500).json({ error: err.message });
|
||||
}
|
||||
res.redirect('/benefits/manage?err=error_deleting');
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,29 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requireAuth } = require('../middlewares/authMiddleware');
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
router.get(['/my-card', '/', '/mi-credencial'], async (req, res) => {
|
||||
let qrToken = '';
|
||||
let expiresInHours = 72;
|
||||
|
||||
try {
|
||||
const resp = await req.apiClient.get('/reception/my-qr-token');
|
||||
if (resp.data) {
|
||||
qrToken = resp.data.qr_token || '';
|
||||
expiresInHours = resp.data.expires_in_hours || 72;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('QR token generation notice:', err.message);
|
||||
}
|
||||
|
||||
res.render('credential/card', {
|
||||
title: 'Mi Credencial Digital — UniCABA',
|
||||
user: req.user,
|
||||
qrToken,
|
||||
expiresInHours
|
||||
});
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,82 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const { requireAuth } = require('../middlewares/authMiddleware');
|
||||
|
||||
router.use(requireAuth);
|
||||
|
||||
const getNormalizedRole = (user) => {
|
||||
const roleStr = (user?.role || '').toLowerCase();
|
||||
if (roleStr.includes('admin')) return 'admin';
|
||||
if (roleStr.includes('bedel')) return 'bedelia';
|
||||
if (roleStr.includes('recep')) return 'recepcion';
|
||||
return roleStr;
|
||||
};
|
||||
|
||||
// GET /reception/scanner — Consola de Escaneo y Control de Acceso
|
||||
router.get('/scanner', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia' && role !== 'recepcion') {
|
||||
return res.status(403).redirect('/dashboard');
|
||||
}
|
||||
|
||||
let buildings = [];
|
||||
let recentLogs = [];
|
||||
try {
|
||||
const [respBld, respLogs] = await Promise.all([
|
||||
req.apiClient.get('/buildings'),
|
||||
req.apiClient.get('/reception/recent-logs', { params: { limit: 15 } })
|
||||
]);
|
||||
buildings = respBld.data?.buildings || respBld.data || [];
|
||||
recentLogs = respLogs.data?.items || [];
|
||||
} catch (err) {
|
||||
console.warn('Reception scanner init notice:', err.message);
|
||||
}
|
||||
|
||||
res.render('reception/scanner', {
|
||||
title: 'Control de Acceso QR — Recepción & Seguridad',
|
||||
buildings,
|
||||
recentLogs,
|
||||
userRole: role
|
||||
});
|
||||
});
|
||||
|
||||
// POST /reception/verify — Endpoint AJAX de verificación de código QR
|
||||
router.post('/verify', async (req, res) => {
|
||||
const role = getNormalizedRole(req.user);
|
||||
if (role !== 'admin' && role !== 'bedelia' && role !== 'recepcion') {
|
||||
return res.status(403).json({ error: 'Acceso no autorizado' });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
qr_token: req.body.qr_token,
|
||||
building_id: req.body.building_id ? parseInt(req.body.building_id, 10) : null,
|
||||
notes: req.body.notes || null
|
||||
};
|
||||
const resp = await req.apiClient.post('/reception/verify-qr', payload);
|
||||
return res.json(resp.data);
|
||||
} catch (err) {
|
||||
console.error('Error verifying QR in reception:', err.response?.data || err.message);
|
||||
return res.status(err.response?.status || 500).json(
|
||||
err.response?.data || { status: 'DENEGADO', message: 'Error de comunicación con el validador' }
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// GET /reception/recent-logs — Consulta de historial en vivo
|
||||
router.get('/recent-logs', async (req, res) => {
|
||||
try {
|
||||
const buildingId = req.query.building_id;
|
||||
const resp = await req.apiClient.get('/reception/recent-logs', {
|
||||
params: {
|
||||
building_id: buildingId || undefined,
|
||||
limit: 25
|
||||
}
|
||||
});
|
||||
return res.json(resp.data);
|
||||
} catch (err) {
|
||||
return res.status(err.response?.status || 500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -1482,6 +1482,8 @@
|
||||
{% set user_role = 'bedelia' %}
|
||||
{% elif 'docent' in raw_user_role or 'prof' in raw_user_role %}
|
||||
{% set user_role = 'docente' %}
|
||||
{% elif 'recep' in raw_user_role %}
|
||||
{% set user_role = 'recepcion' %}
|
||||
{% else %}
|
||||
{% set user_role = 'alumno' %}
|
||||
{% endif %}
|
||||
@@ -1553,6 +1555,8 @@
|
||||
<li><a class="nav-link" href="/admin/milestone_types_list"><i class="bi bi-bookmark-star me-1"></i>Tipos de Hitos</a></li>
|
||||
<li><a class="nav-link" href="/admin/google_sheets_import"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Sincro Sheets</a></li>
|
||||
<li><a class="nav-link" href="/admin/audit_logs"><i class="bi bi-journal-text me-1"></i>Auditoría</a></li>
|
||||
<li><a class="nav-link text-warning" href="/benefits/manage"><i class="bi bi-tag me-1"></i>Convenios & Beneficios</a></li>
|
||||
<li><a class="nav-link text-info" href="/reception/scanner"><i class="bi bi-qr-code-scan me-1"></i>Control de Acceso QR</a></li>
|
||||
<li><a class="nav-link text-primary fw-semibold" href="/admin/settings"><i class="bi bi-gear-wide-connected me-1"></i>Config. Global</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -1618,6 +1622,8 @@
|
||||
<ul class="sidebar-submenu">
|
||||
<li><a class="nav-link" href="/admin/google_sheets_import"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Importador Google Sheets</a></li>
|
||||
<li><a class="nav-link" href="/admin/milestone_types_list"><i class="bi bi-bookmark-star me-1"></i>Tipos de Hitos Evaluativos</a></li>
|
||||
<li><a class="nav-link text-warning fw-semibold" href="/benefits/manage"><i class="bi bi-tag me-1"></i>Convenios & Beneficios</a></li>
|
||||
<li><a class="nav-link text-info fw-semibold" href="/reception/scanner"><i class="bi bi-qr-code-scan me-1"></i>Control de Acceso QR</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
@@ -1665,6 +1671,13 @@
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
<li class="sidebar-section-header">Servicios & Beneficios</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/benefits"><i class="bi bi-tags text-warning"></i> <span class="nav-text">Club de Beneficios</span></a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/credential/my-card"><i class="bi bi-person-badge text-primary"></i> <span class="nav-text">Mi Credencial QR</span></a>
|
||||
</li>
|
||||
|
||||
{% else %}
|
||||
<!-- ALUMNO / ESTUDIANTE -->
|
||||
@@ -1697,6 +1710,27 @@
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
<li class="sidebar-section-header">Servicios & Beneficios</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/benefits"><i class="bi bi-tags text-warning"></i> <span class="nav-text">Club de Beneficios</span></a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/credential/my-card"><i class="bi bi-person-badge text-primary"></i> <span class="nav-text">Mi Credencial QR</span></a>
|
||||
</li>
|
||||
|
||||
{% elif user_role == 'recepcion' %}
|
||||
<!-- RECEPCIÓN / CONTROL DE ACCESO -->
|
||||
<li class="sidebar-section-header">Control de Acceso</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/reception/scanner"><i class="bi bi-qr-code-scan text-primary"></i> <span class="nav-text">Escáner de Acceso QR</span></a>
|
||||
</li>
|
||||
<li class="sidebar-section-header">Cartelera & Aulas</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/schedule/today_schedule"><i class="bi bi-calendar-day text-info"></i> <span class="nav-text">Cartelera del Día</span></a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a class="nav-link" href="/classrooms/list_classrooms?view_mode=physical"><i class="bi bi-door-closed text-success"></i> <span class="nav-text">Aulas Presenciales</span></a>
|
||||
</li>
|
||||
{% endif %}
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Club de Beneficios & Convenios — UniCABA{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid py-3 px-lg-4">
|
||||
<!-- Hero / Banner Institucional -->
|
||||
<div class="card border-0 rounded-4 p-4 p-lg-5 mb-4 shadow-sm text-white position-relative overflow-hidden"
|
||||
style="background: linear-gradient(135deg, #7E22CE 0%, #B43E8E 50%, #EC4899 100%);">
|
||||
<div class="position-relative z-1" style="max-width: 680px;">
|
||||
<span class="badge bg-white text-dark rounded-pill px-3 py-1 fw-bold small text-uppercase mb-2 shadow-sm">
|
||||
<i class="bi bi-stars text-warning me-1"></i> Comunidad UniCABA
|
||||
</span>
|
||||
<h1 class="display-6 fw-bold mb-2">Club de Beneficios & Convenios</h1>
|
||||
<p class="lead fs-6 mb-3 opacity-90">Aprovecha descuentos exclusivos en cafeterías, librerías, tecnología y comercios presentando tu credencial universitaria digital.</p>
|
||||
<div class="d-flex flex-wrap gap-2">
|
||||
<a href="/credential/my-card" class="btn btn-light btn-sm rounded-pill px-4 fw-semibold text-primary shadow-sm">
|
||||
<i class="bi bi-qr-code me-1"></i> Abrir Mi Credencial QR
|
||||
</a>
|
||||
{% if canManage %}
|
||||
<a href="/benefits/manage" class="btn btn-outline-light btn-sm rounded-pill px-3">
|
||||
<i class="bi bi-gear me-1"></i> Gestionar Convenios (Bedelía)
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="position-absolute end-0 bottom-0 opacity-25 d-none d-md-block pe-4 pb-2">
|
||||
<i class="bi bi-bag-heart-fill" style="font-size: 14rem;"></i>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Barra de Búsqueda y Filtros de Categoría -->
|
||||
<div class="card border-0 shadow-sm rounded-4 p-3 mb-4">
|
||||
<form method="GET" action="/benefits" class="row g-2 align-items-center">
|
||||
<div class="col-md-5 col-12">
|
||||
<div class="input-group">
|
||||
<span class="input-group-text bg-transparent border-end-0 text-muted"><i class="bi bi-search"></i></span>
|
||||
<input type="text" name="search" class="form-control border-start-0 ps-0" placeholder="Buscar por cafetería, librería o descuento..." value="{{ searchQuery }}">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-7 col-12">
|
||||
<div class="d-flex flex-wrap gap-1 align-items-center justify-content-md-end">
|
||||
<a href="/benefits{% if searchQuery %}?search={{ searchQuery }}{% endif %}" class="btn btn-sm rounded-pill px-3 {% if not currentCategory %}btn-primary{% else %}btn-outline-secondary{% endif %}">
|
||||
Todos
|
||||
</a>
|
||||
{% for cat in categories %}
|
||||
<a href="/benefits?category={{ cat }}{% if searchQuery %}&search={{ searchQuery }}{% endif %}" class="btn btn-sm rounded-pill px-3 {% if currentCategory == cat %}btn-primary{% else %}btn-outline-secondary{% endif %}">
|
||||
{% if cat == 'GASTRONOMIA' %}☕ Cafetería
|
||||
{% elif cat == 'LIBRERIA' %}📚 Librería
|
||||
{% elif cat == 'TECNOLOGIA' %}💻 Tecnología
|
||||
{% elif cat == 'SALUD_DEPORTE' %}🏋️ Salud & Deportes
|
||||
{% elif cat == 'IDIOMAS' %}🌍 Idiomas
|
||||
{% elif cat == 'CULTURA' %}🎭 Cultura
|
||||
{% else %}🏷️ {{ cat }}
|
||||
{% endif %}
|
||||
</a>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<!-- Grilla de Tarjetas de Beneficios -->
|
||||
<div class="row g-4" id="benefitsGrid">
|
||||
{% if benefits and benefits | length > 0 %}
|
||||
{% for b in benefits %}
|
||||
<div class="col-12 col-md-6 col-xl-4">
|
||||
<div class="card border-0 shadow-sm rounded-4 h-100 overflow-hidden benefit-card transition-all" style="transition: transform 0.2s ease, box-shadow 0.2s ease;">
|
||||
<div class="card-body p-4 d-flex flex-column justify-content-between">
|
||||
<div>
|
||||
<!-- Header de Tarjeta -->
|
||||
<div class="d-flex align-items-start justify-content-between gap-2 mb-3">
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<div class="rounded-4 p-2 bg-primary-subtle text-primary d-flex align-items-center justify-content-center shadow-sm" style="width: 48px; height: 48px;">
|
||||
{% if b.category == 'GASTRONOMIA' %}
|
||||
<i class="bi bi-cup-hot fs-4"></i>
|
||||
{% elif b.category == 'LIBRERIA' %}
|
||||
<i class="bi bi-book fs-4"></i>
|
||||
{% elif b.category == 'TECNOLOGIA' %}
|
||||
<i class="bi bi-laptop fs-4"></i>
|
||||
{% elif b.category == 'SALUD_DEPORTE' %}
|
||||
<i class="bi bi-heart-pulse fs-4"></i>
|
||||
{% else %}
|
||||
<i class="bi bi-tag fs-4"></i>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div>
|
||||
<span class="badge bg-secondary-subtle text-secondary-emphasis rounded-pill px-2 py-0 small mb-1">
|
||||
{{ b.category }}
|
||||
</span>
|
||||
<h5 class="fw-bold mb-0 text-dark">{{ b.partner_name }}</h5>
|
||||
</div>
|
||||
</div>
|
||||
<span class="badge bg-danger text-white rounded-pill px-3 py-2 fw-bold fs-6 shadow-sm">
|
||||
{{ b.discount_label }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<h6 class="fw-semibold text-primary mb-2">{{ b.title }}</h6>
|
||||
<p class="text-muted small mb-3" style="min-height: 40px;">
|
||||
{{ b.description or 'Presenta tu credencial universitaria en caja para aplicar el beneficio acordado.' }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Footer de Tarjeta -->
|
||||
<div class="pt-3 border-top border-light-subtle d-flex align-items-center justify-content-between">
|
||||
<span class="text-muted small">
|
||||
<i class="bi bi-geo-alt-fill text-danger me-1"></i>{{ b.building_name or 'Todas las Sedes' }}
|
||||
</span>
|
||||
<button type="button" class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm"
|
||||
onclick='openRedeemModal({{ b | tojson | safe }})'>
|
||||
<i class="bi bi-ticket-perforated me-1"></i> Ver Beneficio
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<div class="col-12 py-5 text-center text-muted">
|
||||
<i class="bi bi-tags display-3 text-secondary opacity-50 mb-3 d-block"></i>
|
||||
<h5>No se encontraron promociones en esta categoría</h5>
|
||||
<p class="small text-muted mb-3">Intenta cambiar los filtros de búsqueda o consulta a UdeCi para conocer próximos convenios.</p>
|
||||
<a href="/benefits" class="btn btn-outline-primary btn-sm rounded-pill px-4">Ver Todos los Beneficios</a>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal de Detalle y Canje -->
|
||||
<div class="modal fade" id="redeemModal" tabindex="-1" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered">
|
||||
<div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
|
||||
<div class="modal-header bg-primary text-white py-3 px-4">
|
||||
<h5 class="modal-title fw-bold" id="redeemTitle">Detalle del Beneficio</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body p-4 text-center">
|
||||
<div class="rounded-circle bg-danger-subtle text-danger mx-auto d-flex align-items-center justify-content-center mb-3" style="width: 72px; height: 72px;">
|
||||
<i class="bi bi-gift-fill fs-2"></i>
|
||||
</div>
|
||||
<h4 class="fw-bold mb-1" id="redeemPartner">Comercio</h4>
|
||||
<div class="badge bg-danger fs-5 px-3 py-1 rounded-pill mb-3" id="redeemDiscount">20% OFF</div>
|
||||
|
||||
<p class="text-muted small px-3 mb-3" id="redeemDesc"></p>
|
||||
|
||||
<div class="p-3 bg-light rounded-4 border mb-3 text-start" id="couponBox">
|
||||
<div class="small text-muted text-uppercase fw-bold mb-1">Cupón de Descuento</div>
|
||||
<div class="d-flex align-items-center justify-content-between">
|
||||
<code class="fs-5 fw-bold text-primary" id="redeemCoupon">UNICABA-20</code>
|
||||
<button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" onclick="copyCoupon()">
|
||||
<i class="bi bi-copy me-1"></i> Copiar
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="alert alert-info rounded-4 small text-start mb-3">
|
||||
<i class="bi bi-info-circle-fill me-1"></i> <strong>¿Cómo usar este beneficio?</strong>
|
||||
<div class="mt-1" id="redeemTerms">Presenta tu Credencial Universitaria Digital UniCABA al momento de solicitar la cuenta o pagar en caja.</div>
|
||||
</div>
|
||||
|
||||
<a href="/credential/my-card" class="btn btn-outline-primary rounded-pill w-100 py-2 fw-semibold">
|
||||
<i class="bi bi-qr-code me-1"></i> Mostrar Mi Credencial QR al Comercio
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function openRedeemModal(b) {
|
||||
document.getElementById('redeemTitle').innerText = b.title;
|
||||
document.getElementById('redeemPartner').innerText = b.partner_name;
|
||||
document.getElementById('redeemDiscount').innerText = b.discount_label;
|
||||
document.getElementById('redeemDesc').innerText = b.description || 'Promoción exclusiva para la comunidad universitaria de UniCABA.';
|
||||
document.getElementById('redeemTerms').innerText = b.terms_conditions || 'Válido presentando tu credencial digital con código QR.';
|
||||
|
||||
const couponBox = document.getElementById('couponBox');
|
||||
if (b.coupon_code) {
|
||||
couponBox.style.display = 'block';
|
||||
document.getElementById('redeemCoupon').innerText = b.coupon_code;
|
||||
} else {
|
||||
couponBox.style.display = 'none';
|
||||
}
|
||||
|
||||
const modal = new bootstrap.Modal(document.getElementById('redeemModal'));
|
||||
modal.show();
|
||||
}
|
||||
|
||||
function copyCoupon() {
|
||||
const code = document.getElementById('redeemCoupon').innerText;
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(code).then(() => {
|
||||
alert('¡Código de cupón copiado al portapapeles!');
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style>
|
||||
.benefit-card:hover {
|
||||
transform: translateY(-4px);
|
||||
box-shadow: 0 12px 28px rgba(0,0,0,0.08) !important;
|
||||
}
|
||||
</style>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,403 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Gestión de Convenios & Beneficios — Bedelía{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid py-3 px-lg-4">
|
||||
<!-- Header de Página -->
|
||||
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
|
||||
<div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="badge bg-warning-subtle text-warning-emphasis border border-warning-subtle rounded-pill px-3 py-1 fw-semibold">
|
||||
<i class="bi bi-tag-fill me-1"></i> Bedelía & Servicios
|
||||
</span>
|
||||
<span class="text-muted small">Módulo SDD-012</span>
|
||||
</div>
|
||||
<h1 class="h3 fw-bold mt-1 mb-0">Gestión de Convenios & Beneficios</h1>
|
||||
<p class="text-muted small mb-0">Administra las promociones comerciales, descuentos en cafeterías, librerías y beneficios para la comunidad UniCABA.</p>
|
||||
</div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<a href="/benefits" class="btn btn-outline-secondary btn-sm rounded-pill px-3">
|
||||
<i class="bi bi-eye me-1"></i> Ver Catálogo Público
|
||||
</a>
|
||||
<button type="button" class="btn btn-primary btn-sm rounded-pill px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#benefitModal" onclick="openCreateModal()">
|
||||
<i class="bi bi-plus-lg me-1"></i> Nuevo Convenio
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Alertas de Estado -->
|
||||
<div id="alertContainer"></div>
|
||||
|
||||
<!-- Métricas Rápidas -->
|
||||
<div class="row g-3 mb-4">
|
||||
<div class="col-6 col-md-3">
|
||||
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
|
||||
<div class="d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<span class="text-muted small text-uppercase fw-bold">Total Convenios</span>
|
||||
<h3 class="fw-bold mb-0 text-primary mt-1">{{ benefits | length }}</h3>
|
||||
</div>
|
||||
<div class="p-3 bg-primary-subtle text-primary rounded-circle">
|
||||
<i class="bi bi-tags fs-4"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3">
|
||||
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
|
||||
<div class="d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<span class="text-muted small text-uppercase fw-bold">Activos</span>
|
||||
<h3 class="fw-bold mb-0 text-success mt-1" id="activeCount">
|
||||
{% set active_count = 0 %}
|
||||
{% for b in benefits %}
|
||||
{% if b.is_active %}{% set active_count = active_count + 1 %}{% endif %}
|
||||
{% endfor %}
|
||||
{{ active_count }}
|
||||
</h3>
|
||||
</div>
|
||||
<div class="p-3 bg-success-subtle text-success rounded-circle">
|
||||
<i class="bi bi-check-circle fs-4"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3">
|
||||
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
|
||||
<div class="d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<span class="text-muted small text-uppercase fw-bold">Categorías</span>
|
||||
<h3 class="fw-bold mb-0 text-info mt-1">{{ categories | length }}</h3>
|
||||
</div>
|
||||
<div class="p-3 bg-info-subtle text-info rounded-circle">
|
||||
<i class="bi bi-grid fs-4"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6 col-md-3">
|
||||
<div class="card border-0 shadow-sm rounded-4 h-100 p-3">
|
||||
<div class="d-flex align-items-center justify-content-between">
|
||||
<div>
|
||||
<span class="text-muted small text-uppercase fw-bold">Sedes</span>
|
||||
<h3 class="fw-bold mb-0 text-warning mt-1">{{ buildings | length }}</h3>
|
||||
</div>
|
||||
<div class="p-3 bg-warning-subtle text-warning rounded-circle">
|
||||
<i class="bi bi-buildings fs-4"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabla Principal de Convenios -->
|
||||
<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
|
||||
<div class="card-header bg-body border-0 py-3 px-4 d-flex flex-wrap align-items-center justify-content-between gap-3">
|
||||
<h5 class="fw-bold mb-0">Nómina de Convenios Registrados</h5>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<input type="text" id="tableFilter" class="form-control form-control-sm rounded-pill px-3" placeholder="Filtrar por comercio o título..." style="min-width: 240px;">
|
||||
</div>
|
||||
</div>
|
||||
<div class="table-responsive">
|
||||
<table class="table table-hover align-middle mb-0" id="benefitsTable">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th class="ps-4">Convenio & Comercio</th>
|
||||
<th>Categoría</th>
|
||||
<th>Descuento</th>
|
||||
<th>Sede</th>
|
||||
<th>Destinatarios</th>
|
||||
<th>Vigencia</th>
|
||||
<th>Cupón</th>
|
||||
<th class="text-center">Estado</th>
|
||||
<th class="text-end pe-4">Acciones</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% if benefits and benefits | length > 0 %}
|
||||
{% for b in benefits %}
|
||||
<tr id="benefit-row-{{ b.id }}" data-search="{{ b.title | lower }} {{ b.partner_name | lower }} {{ b.category | lower }}">
|
||||
<td class="ps-4">
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<div class="rounded-3 p-2 bg-primary-subtle text-primary d-flex align-items-center justify-content-center" style="width: 42px; height: 42px;">
|
||||
{% if b.category == 'GASTRONOMIA' %}
|
||||
<i class="bi bi-cup-hot fs-5"></i>
|
||||
{% elif b.category == 'LIBRERIA' %}
|
||||
<i class="bi bi-book fs-5"></i>
|
||||
{% elif b.category == 'TECNOLOGIA' %}
|
||||
<i class="bi bi-laptop fs-5"></i>
|
||||
{% elif b.category == 'SALUD_DEPORTE' %}
|
||||
<i class="bi bi-heart-pulse fs-5"></i>
|
||||
{% else %}
|
||||
<i class="bi bi-tag fs-5"></i>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div>
|
||||
<div class="fw-bold text-dark">{{ b.title }}</div>
|
||||
<div class="small text-muted"><i class="bi bi-shop me-1"></i>{{ b.partner_name }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-secondary-subtle text-secondary-emphasis rounded-pill px-2 py-1 small">
|
||||
{{ b.category }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-danger-subtle text-danger border border-danger-subtle rounded-pill px-2 py-1 fw-bold">
|
||||
{{ b.discount_label }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="small text-muted">
|
||||
<i class="bi bi-geo-alt me-1"></i>{{ b.building_name or 'Todas las Sedes' }}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
{% if b.target_roles == 'ALL' %}
|
||||
<span class="badge bg-info-subtle text-info rounded-pill px-2">Todos</span>
|
||||
{% elif 'ALUMNO' in b.target_roles and 'DOCENTE' in b.target_roles %}
|
||||
<span class="badge bg-primary-subtle text-primary rounded-pill px-2">Alumnos & Docentes</span>
|
||||
{% elif 'ALUMNO' in b.target_roles %}
|
||||
<span class="badge bg-success-subtle text-success rounded-pill px-2">Solo Alumnos</span>
|
||||
{% elif 'DOCENTE' in b.target_roles %}
|
||||
<span class="badge bg-warning-subtle text-warning-emphasis rounded-pill px-2">Solo Docentes</span>
|
||||
{% else %}
|
||||
<span class="badge bg-secondary-subtle text-secondary rounded-pill px-2">{{ b.target_roles }}</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td>
|
||||
<div class="small">
|
||||
<div><i class="bi bi-calendar-check me-1 text-success"></i>Desde: {{ b.valid_from }}</div>
|
||||
{% if b.valid_until %}
|
||||
<div><i class="bi bi-calendar-x me-1 text-danger"></i>Hasta: {{ b.valid_until }}</div>
|
||||
{% else %}
|
||||
<div class="text-muted"><i class="bi bi-infinity me-1"></i>Indefinido</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
{% if b.coupon_code %}
|
||||
<code class="px-2 py-1 bg-light rounded text-primary fw-bold small border">{{ b.coupon_code }}</code>
|
||||
{% else %}
|
||||
<span class="text-muted small">Credencial</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="text-center">
|
||||
<div class="form-check form-switch d-inline-block">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="switch-{{ b.id }}" {% if b.is_active %}checked{% endif %} onchange="toggleStatus({{ b.id }})">
|
||||
</div>
|
||||
</td>
|
||||
<td class="text-end pe-4">
|
||||
<div class="btn-group btn-group-sm">
|
||||
<button type="button" class="btn btn-outline-secondary rounded-start-pill" title="Editar" onclick='openEditModal({{ b | tojson | safe }})'>
|
||||
<i class="bi bi-pencil"></i>
|
||||
</button>
|
||||
<button type="button" class="btn btn-outline-danger rounded-end-pill" title="Eliminar" onclick="confirmDelete({{ b.id }}, '{{ b.title }}')">
|
||||
<i class="bi bi-trash"></i>
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="9" class="text-center py-5 text-muted">
|
||||
<i class="bi bi-tags display-4 d-block mb-3 text-secondary opacity-50"></i>
|
||||
<h5>No hay convenios cargados aún</h5>
|
||||
<p class="small text-muted mb-3">Comienza creando promociones de cafetería, librerías y comercios para los alumnos y docentes.</p>
|
||||
<button type="button" class="btn btn-primary btn-sm rounded-pill px-4" data-bs-toggle="modal" data-bs-target="#benefitModal" onclick="openCreateModal()">
|
||||
<i class="bi bi-plus-lg me-1"></i> Crear Primer Convenio
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal de Creación / Edición -->
|
||||
<div class="modal fade" id="benefitModal" tabindex="-1" aria-labelledby="benefitModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-lg modal-dialog-centered">
|
||||
<div class="modal-content border-0 shadow-lg rounded-4 overflow-hidden">
|
||||
<form id="benefitForm" method="POST" action="/benefits">
|
||||
<div class="modal-header bg-primary text-white py-3 px-4">
|
||||
<h5 class="modal-title fw-bold" id="benefitModalLabel">
|
||||
<i class="bi bi-tag-fill me-2"></i> Nuevo Convenio Comercial
|
||||
</h5>
|
||||
<button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<div class="modal-body p-4">
|
||||
<input type="hidden" id="benefitId" name="benefitId">
|
||||
|
||||
<div class="row g-3">
|
||||
<div class="col-md-7">
|
||||
<label class="form-label small fw-bold">Título de la Promoción *</label>
|
||||
<input type="text" class="form-control" id="title" name="title" required placeholder="Ej: 20% en Cafetería La Estación">
|
||||
</div>
|
||||
<div class="col-md-5">
|
||||
<label class="form-label small fw-bold">Comercio / Entidad *</label>
|
||||
<input type="text" class="form-control" id="partner_name" name="partner_name" required placeholder="Ej: Café Martínez Central">
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<label class="form-label small fw-bold">Categoría *</label>
|
||||
<select class="form-select" id="category" name="category" required>
|
||||
<option value="GASTRONOMIA">☕ Gastronomía / Cafetería</option>
|
||||
<option value="LIBRERIA">📚 Librería / Fotocopias</option>
|
||||
<option value="TECNOLOGIA">💻 Tecnología & Software</option>
|
||||
<option value="SALUD_DEPORTE">🏋️ Salud & Deportes</option>
|
||||
<option value="IDIOMAS">🌍 Idiomas & Cursos</option>
|
||||
<option value="CULTURA">🎭 Cultura & Entretenimiento</option>
|
||||
<option value="GENERAL" selected>🏷️ General / Otros</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label small fw-bold">Etiqueta de Descuento *</label>
|
||||
<input type="text" class="form-control" id="discount_label" name="discount_label" required placeholder="Ej: 20% OFF / 2x1">
|
||||
</div>
|
||||
<div class="col-md-4">
|
||||
<label class="form-label small fw-bold">Código de Cupón (Opcional)</label>
|
||||
<input type="text" class="form-control" id="coupon_code" name="coupon_code" placeholder="Ej: UNICABA-20">
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-bold">Sede Aplicable</label>
|
||||
<select class="form-select" id="building_id" name="building_id">
|
||||
<option value="">Todas las Sedes</option>
|
||||
{% for bld in buildings %}
|
||||
<option value="{{ bld.id }}">{{ bld.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-bold">Destinatarios *</label>
|
||||
<select class="form-select" id="target_roles" name="target_roles" required>
|
||||
<option value="ALL">Todos (Alumnos, Docentes y Personal)</option>
|
||||
<option value="ALUMNO,DOCENTE">Alumnos y Docentes</option>
|
||||
<option value="ALUMNO">Solo Estudiantes</option>
|
||||
<option value="DOCENTE">Solo Docentes</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-bold">Fecha de Inicio *</label>
|
||||
<input type="date" class="form-control" id="valid_from" name="valid_from" required>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<label class="form-label small fw-bold">Fecha de Vencimiento (Opcional)</label>
|
||||
<input type="date" class="form-control" id="valid_until" name="valid_until">
|
||||
</div>
|
||||
|
||||
<div class="col-12">
|
||||
<label class="form-label small fw-bold">Descripción del Beneficio</label>
|
||||
<textarea class="form-control" id="description" name="description" rows="2" placeholder="Detalles de cómo aprovechar el beneficio en el local..."></textarea>
|
||||
</div>
|
||||
|
||||
<div class="col-12">
|
||||
<label class="form-label small fw-bold">Términos & Condiciones</label>
|
||||
<textarea class="form-control" id="terms_conditions" name="terms_conditions" rows="2" placeholder="Válido de lunes a viernes con credencial universitaria vigente..."></textarea>
|
||||
</div>
|
||||
|
||||
<div class="col-12">
|
||||
<div class="form-check form-switch mt-2">
|
||||
<input class="form-check-input" type="checkbox" role="switch" id="is_active" name="is_active" checked>
|
||||
<label class="form-check-label fw-semibold" for="is_active">Publicar inmediatamente en el catálogo de alumnos y docentes</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer bg-light py-3 px-4">
|
||||
<button type="button" class="btn btn-outline-secondary rounded-pill px-4" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary rounded-pill px-4" id="submitBtn">
|
||||
<i class="bi bi-check-lg me-1"></i> Guardar Convenio
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
// Filtro en tiempo real de la tabla
|
||||
document.getElementById('tableFilter').addEventListener('input', function(e) {
|
||||
const val = e.target.value.toLowerCase().trim();
|
||||
const rows = document.querySelectorAll('#benefitsTable tbody tr[data-search]');
|
||||
rows.forEach(r => {
|
||||
const txt = r.getAttribute('data-search');
|
||||
r.style.display = txt.includes(val) ? '' : 'none';
|
||||
});
|
||||
});
|
||||
|
||||
function openCreateModal() {
|
||||
document.getElementById('benefitModalLabel').innerHTML = '<i class="bi bi-tag-fill me-2"></i> Nuevo Convenio Comercial';
|
||||
document.getElementById('benefitForm').action = '/benefits';
|
||||
document.getElementById('benefitForm').reset();
|
||||
document.getElementById('benefitId').value = '';
|
||||
document.getElementById('valid_from').value = new Date().toISOString().split('T')[0];
|
||||
document.getElementById('is_active').checked = true;
|
||||
}
|
||||
|
||||
function openEditModal(b) {
|
||||
document.getElementById('benefitModalLabel').innerHTML = '<i class="bi bi-pencil-fill me-2"></i> Editar Convenio Comercial';
|
||||
document.getElementById('benefitForm').action = `/benefits/${b.id}/edit`;
|
||||
document.getElementById('benefitId').value = b.id;
|
||||
document.getElementById('title').value = b.title || '';
|
||||
document.getElementById('partner_name').value = b.partner_name || '';
|
||||
document.getElementById('category').value = b.category || 'GENERAL';
|
||||
document.getElementById('discount_label').value = b.discount_label || '';
|
||||
document.getElementById('coupon_code').value = b.coupon_code || '';
|
||||
document.getElementById('building_id').value = b.building_id || '';
|
||||
document.getElementById('target_roles').value = b.target_roles || 'ALL';
|
||||
document.getElementById('valid_from').value = b.valid_from ? b.valid_from.split('T')[0] : '';
|
||||
document.getElementById('valid_until').value = b.valid_until ? b.valid_until.split('T')[0] : '';
|
||||
document.getElementById('description').value = b.description || '';
|
||||
document.getElementById('terms_conditions').value = b.terms_conditions || '';
|
||||
document.getElementById('is_active').checked = b.is_active;
|
||||
|
||||
const modal = new bootstrap.Modal(document.getElementById('benefitModal'));
|
||||
modal.show();
|
||||
}
|
||||
|
||||
async function toggleStatus(id) {
|
||||
try {
|
||||
const res = await fetch(`/benefits/${id}/toggle`, { method: 'POST' });
|
||||
if (!res.ok) throw new Error('Error al cambiar estado');
|
||||
const data = await res.json();
|
||||
showAlert('Estado actualizado exitosamente.', 'success');
|
||||
} catch (err) {
|
||||
showAlert('No se pudo actualizar el estado: ' + err.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmDelete(id, title) {
|
||||
if (!confirm(`¿Estás seguro de que deseas eliminar el convenio "${title}"?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/benefits/${id}/delete`, { method: 'POST', headers: { 'Accept': 'application/json' } });
|
||||
if (res.ok) {
|
||||
const row = document.getElementById(`benefit-row-${id}`);
|
||||
if (row) row.remove();
|
||||
showAlert(`Convenio "${title}" eliminado.`, 'info');
|
||||
} else {
|
||||
throw new Error('Error al eliminar');
|
||||
}
|
||||
} catch (err) {
|
||||
showAlert('Error: ' + err.message, 'danger');
|
||||
}
|
||||
}
|
||||
|
||||
function showAlert(msg, type = 'info') {
|
||||
const container = document.getElementById('alertContainer');
|
||||
container.innerHTML = `
|
||||
<div class="alert alert-${type} alert-dismissible fade show rounded-4 shadow-sm" role="alert">
|
||||
<i class="bi bi-info-circle me-2"></i> ${msg}
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
||||
</div>
|
||||
`;
|
||||
setTimeout(() => { container.innerHTML = ''; }, 4000);
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,129 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Mi Credencial Digital — UniCABA{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container py-4">
|
||||
<div class="row justify-content-center">
|
||||
<div class="col-12 col-md-8 col-lg-6 col-xl-5">
|
||||
<!-- Header -->
|
||||
<div class="text-center mb-4">
|
||||
<span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill px-3 py-1 fw-bold text-uppercase small">
|
||||
<i class="bi bi-shield-check me-1"></i> Identidad Universitaria
|
||||
</span>
|
||||
<h1 class="h3 fw-bold mt-2 mb-1">Credencial Digital</h1>
|
||||
<p class="text-muted small">Utiliza este código QR para ingresar a las sedes de UniCABA y acceder a los convenios comerciales.</p>
|
||||
</div>
|
||||
|
||||
<!-- Tarjeta de Credencial Estilo Carnet Físico -->
|
||||
<div class="card border-0 rounded-4 overflow-hidden shadow-lg text-white mb-4 position-relative"
|
||||
style="background: linear-gradient(135deg, #1E1B4B 0%, #4338CA 50%, #B43E8E 100%);">
|
||||
|
||||
<!-- Banda Superior -->
|
||||
<div class="p-3 border-bottom border-white border-opacity-10 d-flex align-items-center justify-content-between">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<img src="/img/logo_unicaba_mini.png" alt="UniCABA" height="26" class="bg-white rounded-circle p-1">
|
||||
<span class="fw-bold tracking-wider fs-6">UniCABA</span>
|
||||
</div>
|
||||
<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-2 py-0 fw-bold small">
|
||||
● ACTIVO
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="p-4 text-center">
|
||||
<!-- Avatar / Foto -->
|
||||
<div class="position-relative d-inline-block mb-3">
|
||||
<div class="rounded-circle bg-white text-primary fw-bold display-6 d-flex align-items-center justify-content-center shadow"
|
||||
style="width: 84px; height: 84px; border: 3px solid rgba(255,255,255,0.4);">
|
||||
{{ (user.name or 'U')[0] }}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h4 class="fw-bold mb-0 text-white">{{ user.name }}</h4>
|
||||
<div class="small opacity-75 mb-3">
|
||||
{% if user.role == 'docente' or user.role == 'profesor' %}
|
||||
DOCENTE INSTITUCIONAL
|
||||
{% elif user.role == 'admin' %}
|
||||
ADMINISTRACIÓN & GOBIERNO
|
||||
{% elif user.role == 'bedelia' %}
|
||||
BEDELÍA & GESTIÓN ÁULICA
|
||||
{% else %}
|
||||
ESTUDIANTE REGULAR
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- Código QR Institucional -->
|
||||
<div class="p-3 bg-white rounded-4 shadow-sm d-inline-block mb-3" style="min-width: 200px; min-height: 200px;">
|
||||
<div id="qrcode" class="d-flex justify-content-center align-items-center"></div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-center align-items-center gap-3 text-start small opacity-90 mb-2">
|
||||
<div>
|
||||
<span class="d-block text-uppercase" style="font-size: 0.65rem;">Documento</span>
|
||||
<span class="fw-bold fs-6">{{ user.document_number or user.email }}</span>
|
||||
</div>
|
||||
<div class="vr bg-white opacity-25"></div>
|
||||
<div>
|
||||
<span class="d-block text-uppercase" style="font-size: 0.65rem;">ID Alumno</span>
|
||||
<span class="fw-bold fs-6">#{{ user.id }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Footer de la Credencial -->
|
||||
<div class="p-3 bg-black bg-opacity-25 border-top border-white border-opacity-10 d-flex align-items-center justify-content-between text-white-50 small">
|
||||
<span><i class="bi bi-clock-history me-1"></i> QR renovable</span>
|
||||
<span>Validez: {{ expiresInHours }}hs</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Accesos Rápidos -->
|
||||
<div class="d-grid gap-2 mb-4">
|
||||
<a href="/benefits" class="btn btn-outline-primary rounded-pill py-2">
|
||||
<i class="bi bi-tags me-1"></i> Ver Convenios y Beneficios Disponibles
|
||||
</a>
|
||||
<a href="/schedule/today_schedule" class="btn btn-light rounded-pill py-2 border text-muted">
|
||||
<i class="bi bi-calendar-day me-1"></i> Consultar Mis Clases de Hoy
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Advertencia / Instructivo de Acceso -->
|
||||
<div class="card border-0 bg-light rounded-4 p-3 small text-muted">
|
||||
<div class="d-flex gap-2">
|
||||
<i class="bi bi-info-circle-fill text-primary fs-5 mt-1"></i>
|
||||
<div>
|
||||
<strong class="text-dark">¿Cómo presentar tu credencial?</strong>
|
||||
<p class="mb-0 mt-1">Al ingresar a la sede, muestra este código QR en la pantalla del lector de Recepción o al personal de Bedelía. El sistema verificará tu matrícula y te indicará en pantalla el aula y piso donde cursas hoy.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Librería QRCode.js via CDN -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/qrcodejs@1.0.0/qrcode.min.js"></script>
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const qrContainer = document.getElementById('qrcode');
|
||||
const token = "{{ qrToken }}";
|
||||
const fallbackText = "UNICABA:USR:{{ user.id }}:DNI:{{ user.document_number or user.email }}";
|
||||
|
||||
const textToEncode = token && token.length > 10 ? token : fallbackText;
|
||||
|
||||
try {
|
||||
new QRCode(qrContainer, {
|
||||
text: textToEncode,
|
||||
width: 180,
|
||||
height: 180,
|
||||
colorDark: "#0F172A",
|
||||
colorLight: "#FFFFFF",
|
||||
correctLevel: QRCode.CorrectLevel.M
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Error generando QR:', e);
|
||||
qrContainer.innerHTML = '<div class="alert alert-warning p-2 small">Código disponible en modo texto</div>';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,390 @@
|
||||
{% extends "base.html" %}
|
||||
|
||||
{% block title %}Consola de Acceso QR — Recepción & Seguridad{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="container-fluid py-3 px-lg-4">
|
||||
<!-- Header de Control de Acceso -->
|
||||
<div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-4">
|
||||
<div>
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="badge bg-secondary text-white rounded-pill px-3 py-1 fw-semibold">
|
||||
<i class="bi bi-qr-code-scan me-1"></i> Control de Acceso
|
||||
</span>
|
||||
<span class="badge bg-success-subtle text-success border border-success-subtle rounded-pill px-2 py-0">En Línea</span>
|
||||
</div>
|
||||
<h1 class="h3 fw-bold mt-1 mb-0">Consola de Recepción & Escáner QR</h1>
|
||||
<p class="text-muted small mb-0">Identifica a los estudiantes y docentes al ingresar, valida su estado de matrícula e infórmales su aula y piso del día.</p>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center gap-3">
|
||||
<div>
|
||||
<label class="small text-muted fw-bold d-block">Punto de Control / Sede:</label>
|
||||
<select class="form-select form-select-sm rounded-pill px-3" id="buildingSelect">
|
||||
<option value="">Todas las Sedes</option>
|
||||
{% for b in buildings %}
|
||||
<option value="{{ b.id }}" {% if loop.first %}selected{% endif %}>{{ b.name }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row g-4">
|
||||
<!-- Columna Izquierda: Escáner y Entrada Rápida -->
|
||||
<div class="col-12 col-lg-5">
|
||||
<div class="card border-0 shadow-sm rounded-4 p-4 mb-4">
|
||||
<h5 class="fw-bold mb-3 d-flex align-items-center justify-content-between">
|
||||
<span><i class="bi bi-camera me-2 text-primary"></i>Lector de Cámara</span>
|
||||
<button type="button" class="btn btn-sm btn-outline-primary rounded-pill px-3" id="toggleCamBtn" onclick="toggleCamera()">
|
||||
<i class="bi bi-play-circle me-1"></i> Iniciar Cámara
|
||||
</button>
|
||||
</h5>
|
||||
|
||||
<!-- Visor de Cámara -->
|
||||
<div id="reader" class="rounded-4 overflow-hidden bg-dark position-relative d-flex align-items-center justify-content-center text-white"
|
||||
style="width: 100%; min-height: 280px;">
|
||||
<div id="cameraPlaceholder" class="text-center p-4">
|
||||
<i class="bi bi-camera-video display-4 text-secondary mb-2 d-block"></i>
|
||||
<span class="small text-muted">Cámara en espera. Presiona "Iniciar Cámara" o utiliza un lector óptico USB.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Entrada Manual o Pistola Óptica USB -->
|
||||
<div class="mt-4 pt-3 border-top">
|
||||
<label class="form-label small fw-bold text-uppercase text-muted">
|
||||
<i class="bi bi-upc-scan me-1 text-primary"></i> Pistola Óptica USB o Entrada Manual por DNI
|
||||
</label>
|
||||
<form id="manualScanForm" onsubmit="handleManualScan(event)">
|
||||
<div class="input-group">
|
||||
<input type="text" class="form-control rounded-start-pill ps-3" id="scannerInput"
|
||||
placeholder="Escanea con la pistola o escribe el DNI..." autofocus autocomplete="off">
|
||||
<button class="btn btn-primary rounded-end-pill px-4 fw-semibold" type="submit">
|
||||
Validar
|
||||
</button>
|
||||
</div>
|
||||
<span class="small text-muted d-block mt-1">El lector óptico envía la lectura directamente a este campo con retorno de carro automático.</span>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Columna Derecha: Tarjeta de Validación Instantánea y Aulas del Día -->
|
||||
<div class="col-12 col-lg-7">
|
||||
<!-- Tarjeta de Resultado en Pantalla Completa -->
|
||||
<div class="card border-0 shadow-sm rounded-4 overflow-hidden mb-4" id="resultCard" style="min-height: 380px;">
|
||||
<div class="card-header py-3 px-4 bg-light border-0 d-flex align-items-center justify-content-between" id="resultHeader">
|
||||
<h5 class="fw-bold mb-0" id="resultStatusText">
|
||||
<i class="bi bi-person-badge me-2 text-muted"></i> Esperando lectura...
|
||||
</h5>
|
||||
<span class="badge bg-secondary rounded-pill px-3 py-1" id="resultTimeBadge">--:--</span>
|
||||
</div>
|
||||
<div class="card-body p-4 d-flex flex-column justify-content-center text-center" id="resultBody">
|
||||
<div class="py-5 text-muted" id="waitingState">
|
||||
<i class="bi bi-qr-code-scan display-1 opacity-25 text-primary mb-3 d-block"></i>
|
||||
<h4 class="fw-bold text-secondary">Apunta el código QR a la cámara</h4>
|
||||
<p class="small text-muted max-w-md mx-auto">
|
||||
Al detectar la credencial del alumno o docente, el sistema mostrará instantáneamente sus datos de ingreso y las aulas donde cursa hoy.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<!-- Contenedor de Resultado Activo (Oculto inicialmente) -->
|
||||
<div id="activeResultState" class="d-none text-start">
|
||||
<div class="row align-items-center mb-4">
|
||||
<div class="col-auto">
|
||||
<div class="rounded-circle bg-primary text-white display-6 fw-bold d-flex align-items-center justify-content-center shadow-sm"
|
||||
style="width: 80px; height: 80px;" id="userInitial">
|
||||
A
|
||||
</div>
|
||||
</div>
|
||||
<div class="col">
|
||||
<div class="badge bg-success rounded-pill px-3 py-1 mb-1" id="matriculaBadge">REGULAR / ACTIVO</div>
|
||||
<h3 class="fw-bold mb-0 text-dark" id="userNameText">Nombre del Alumno</h3>
|
||||
<div class="text-muted small">
|
||||
<span id="userRoleText">ESTUDIANTE</span> • DNI: <strong id="userDniText">12345678</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sección de Aulas y Clases de Hoy -->
|
||||
<div class="p-3 bg-light rounded-4 border mb-3">
|
||||
<h6 class="fw-bold text-uppercase text-primary small mb-3">
|
||||
<i class="bi bi-compass-fill me-1"></i> Cronograma Áulico del Día de Hoy
|
||||
</h6>
|
||||
<div id="classesContainer">
|
||||
<!-- Inyección dinámica de clases -->
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center justify-content-between text-muted small">
|
||||
<span id="scanTimestampText"><i class="bi bi-clock me-1"></i> Escaneado a las: --:--</span>
|
||||
<span class="badge bg-primary-subtle text-primary border border-primary-subtle rounded-pill px-3 py-1">
|
||||
Check-in Registrado
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Tabla de Ingresos Recientes -->
|
||||
<div class="card border-0 shadow-sm rounded-4 overflow-hidden">
|
||||
<div class="card-header bg-body border-0 py-3 px-4 d-flex align-items-center justify-content-between">
|
||||
<h6 class="fw-bold mb-0 text-dark">
|
||||
<i class="bi bi-clock-history me-2 text-primary"></i> Últimos Ingresos Registrados en Sede
|
||||
</h6>
|
||||
<button type="button" class="btn btn-sm btn-link text-decoration-none p-0" onclick="refreshRecentLogs()">
|
||||
<i class="bi bi-arrow-clockwise me-1"></i> Actualizar
|
||||
</button>
|
||||
</div>
|
||||
<div class="table-responsive" style="max-height: 250px;">
|
||||
<table class="table table-hover table-sm align-middle mb-0" id="recentLogsTable">
|
||||
<thead class="table-light small">
|
||||
<tr>
|
||||
<th class="ps-4">Usuario</th>
|
||||
<th>Rol</th>
|
||||
<th>DNI</th>
|
||||
<th>Sede</th>
|
||||
<th>Hora</th>
|
||||
<th class="text-center">Estado</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="small" id="recentLogsBody">
|
||||
{% if recentLogs and recentLogs | length > 0 %}
|
||||
{% for log in recentLogs %}
|
||||
<tr>
|
||||
<td class="ps-4 fw-semibold">{{ log.user_name }}</td>
|
||||
<td><span class="badge bg-light text-dark border">{{ log.user_role or 'ALUMNO' }}</span></td>
|
||||
<td>{{ log.user_dni or '--' }}</td>
|
||||
<td>{{ log.building_name }}</td>
|
||||
<td>{{ log.scanned_at | replace('T', ' ') | truncate(16, true, '') }}</td>
|
||||
<td class="text-center">
|
||||
{% if log.status == 'AUTORIZADO' %}
|
||||
<span class="badge bg-success-subtle text-success">OK</span>
|
||||
{% else %}
|
||||
<span class="badge bg-danger-subtle text-danger">{{ log.status }}</span>
|
||||
{% endif %}
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
{% else %}
|
||||
<tr>
|
||||
<td colspan="6" class="text-center py-3 text-muted">Aún no se han registrado ingresos hoy.</td>
|
||||
</tr>
|
||||
{% endif %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- html5-qrcode Library via CDN -->
|
||||
<script src="https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
|
||||
|
||||
<script>
|
||||
let html5QrCode = null;
|
||||
let isCameraRunning = false;
|
||||
let isScanningLocked = false;
|
||||
|
||||
// Inicializar o alternar cámara
|
||||
function toggleCamera() {
|
||||
const btn = document.getElementById('toggleCamBtn');
|
||||
const placeholder = document.getElementById('cameraPlaceholder');
|
||||
|
||||
if (isCameraRunning) {
|
||||
if (html5QrCode) {
|
||||
html5QrCode.stop().then(() => {
|
||||
isCameraRunning = false;
|
||||
btn.innerHTML = '<i class="bi bi-play-circle me-1"></i> Iniciar Cámara';
|
||||
btn.classList.replace('btn-danger', 'btn-outline-primary');
|
||||
placeholder.classList.remove('d-none');
|
||||
});
|
||||
}
|
||||
} else {
|
||||
html5QrCode = new Html5Qrcode("reader");
|
||||
placeholder.classList.add('d-none');
|
||||
|
||||
html5QrCode.start(
|
||||
{ facingMode: "environment" },
|
||||
{
|
||||
fps: 10,
|
||||
qrbox: { width: 250, height: 250 }
|
||||
},
|
||||
(decodedText) => {
|
||||
if (!isScanningLocked) {
|
||||
isScanningLocked = true;
|
||||
playBeep(true);
|
||||
verifyToken(decodedText);
|
||||
setTimeout(() => { isScanningLocked = false; }, 2500);
|
||||
}
|
||||
},
|
||||
(errorMessage) => {
|
||||
// Errores normales de lectura frame a frame, se omiten
|
||||
}
|
||||
).then(() => {
|
||||
isCameraRunning = true;
|
||||
btn.innerHTML = '<i class="bi bi-stop-circle me-1"></i> Detener Cámara';
|
||||
btn.classList.replace('btn-outline-primary', 'btn-danger');
|
||||
}).catch(err => {
|
||||
console.error("Error al iniciar cámara:", err);
|
||||
placeholder.classList.remove('d-none');
|
||||
alert("No se pudo acceder a la cámara. Asegúrate de otorgar los permisos en el navegador.");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Entrada manual o con pistola de código de barras
|
||||
function handleManualScan(e) {
|
||||
e.preventDefault();
|
||||
const input = document.getElementById('scannerInput');
|
||||
const val = input.value.trim();
|
||||
if (!val) return;
|
||||
verifyToken(val);
|
||||
input.value = '';
|
||||
}
|
||||
|
||||
// Petición AJAX de verificación al Backend BFF
|
||||
async function verifyToken(token) {
|
||||
const buildingId = document.getElementById('buildingSelect').value;
|
||||
|
||||
try {
|
||||
const resp = await fetch('/reception/verify', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
qr_token: token,
|
||||
building_id: buildingId ? parseInt(buildingId, 10) : null
|
||||
})
|
||||
});
|
||||
|
||||
const data = await resp.json();
|
||||
displayVerificationResult(data);
|
||||
refreshRecentLogs();
|
||||
} catch (err) {
|
||||
console.error('Error verificando:', err);
|
||||
displayVerificationResult({
|
||||
status: 'DENEGADO',
|
||||
message: 'Error de conexión con el validador.',
|
||||
todays_classes: []
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Despliegue visual de resultados en pantalla
|
||||
function displayVerificationResult(data) {
|
||||
const waitingState = document.getElementById('waitingState');
|
||||
const activeState = document.getElementById('activeResultState');
|
||||
const cardHeader = document.getElementById('resultHeader');
|
||||
const statusText = document.getElementById('resultStatusText');
|
||||
const timeBadge = document.getElementById('resultTimeBadge');
|
||||
|
||||
waitingState.classList.add('d-none');
|
||||
activeState.classList.remove('d-none');
|
||||
|
||||
const now = new Date();
|
||||
timeBadge.innerText = now.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||||
|
||||
if (data.status === 'AUTORIZADO') {
|
||||
cardHeader.className = 'card-header py-3 px-4 bg-success text-white border-0 d-flex align-items-center justify-content-between';
|
||||
statusText.innerHTML = '<i class="bi bi-check-circle-fill me-2"></i> ACCESO AUTORIZADO';
|
||||
document.getElementById('matriculaBadge').className = 'badge bg-success rounded-pill px-3 py-1 mb-1';
|
||||
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'ACTIVO';
|
||||
} else if (data.status === 'RESTRINGIDO') {
|
||||
cardHeader.className = 'card-header py-3 px-4 bg-warning text-dark border-0 d-flex align-items-center justify-content-between';
|
||||
statusText.innerHTML = '<i class="bi bi-exclamation-triangle-fill me-2"></i> ACCESO OBSERVADO / RESTRINGIDO';
|
||||
document.getElementById('matriculaBadge').className = 'badge bg-warning text-dark rounded-pill px-3 py-1 mb-1';
|
||||
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'OBSERVADO';
|
||||
} else {
|
||||
cardHeader.className = 'card-header py-3 px-4 bg-danger text-white border-0 d-flex align-items-center justify-content-between';
|
||||
statusText.innerHTML = '<i class="bi bi-x-circle-fill me-2"></i> ACCESO DENEGADO';
|
||||
document.getElementById('matriculaBadge').className = 'badge bg-danger rounded-pill px-3 py-1 mb-1';
|
||||
document.getElementById('matriculaBadge').innerText = data.matricula_status || 'NO REGISTRADO';
|
||||
}
|
||||
|
||||
document.getElementById('userNameText').innerText = data.user_name || 'Desconocido';
|
||||
document.getElementById('userRoleText').innerText = (data.user_role || 'NO DEFINIDO').toUpperCase();
|
||||
document.getElementById('userDniText').innerText = data.user_dni || '--';
|
||||
document.getElementById('userInitial').innerText = (data.user_name || '?')[0].toUpperCase();
|
||||
document.getElementById('scanTimestampText').innerHTML = `<i class="bi bi-clock me-1"></i> Escaneado: ${now.toLocaleTimeString()}`;
|
||||
|
||||
// Renderizado del cronograma de aulas de hoy
|
||||
const classesContainer = document.getElementById('classesContainer');
|
||||
if (data.todays_classes && data.todays_classes.length > 0) {
|
||||
classesContainer.innerHTML = data.todays_classes.map(c => `
|
||||
<div class="card border border-primary-subtle rounded-3 p-3 mb-2 bg-white shadow-sm">
|
||||
<div class="d-flex align-items-start justify-content-between">
|
||||
<div>
|
||||
<span class="badge bg-primary text-white rounded-pill px-2 py-0 small mb-1">${c.commission_name}</span>
|
||||
<h5 class="fw-bold mb-1 text-primary">${c.subject_name}</h5>
|
||||
<div class="text-muted small">
|
||||
<i class="bi bi-person me-1"></i> Docente: <strong>${c.teacher_name || 'A designar'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
<div class="text-end">
|
||||
<span class="badge bg-warning text-dark fs-6 px-3 py-1 rounded-pill fw-bold shadow-sm">
|
||||
<i class="bi bi-door-open me-1"></i> ${c.classroom_name}
|
||||
</span>
|
||||
<div class="fw-semibold text-dark mt-1" style="font-size: 0.85rem;">
|
||||
Piso: <strong>${c.floor || 1}</strong> (${c.building_name})
|
||||
</div>
|
||||
<div class="small text-muted mt-1">
|
||||
<i class="bi bi-clock me-1"></i> ${c.start_time} a ${c.end_time} hs
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
} else {
|
||||
classesContainer.innerHTML = `
|
||||
<div class="alert alert-secondary py-2 px-3 rounded-3 small mb-0">
|
||||
<i class="bi bi-info-circle me-1"></i> No tiene clases presenciales programadas para el día de hoy.
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
}
|
||||
|
||||
// Actualización de la tabla de ingresos recientes
|
||||
async function refreshRecentLogs() {
|
||||
const buildingId = document.getElementById('buildingSelect').value;
|
||||
try {
|
||||
const res = await fetch(`/reception/recent-logs?building_id=${buildingId || ''}`);
|
||||
const data = await res.json();
|
||||
const tbody = document.getElementById('recentLogsBody');
|
||||
if (data.items && data.items.length > 0) {
|
||||
tbody.innerHTML = data.items.map(l => `
|
||||
<tr>
|
||||
<td class="ps-4 fw-semibold">${l.user_name}</td>
|
||||
<td><span class="badge bg-light text-dark border">${l.user_role || 'ALUMNO'}</span></td>
|
||||
<td>${l.user_dni || '--'}</td>
|
||||
<td>${l.building_name}</td>
|
||||
<td>${l.scanned_at ? l.scanned_at.replace('T', ' ').substring(11, 16) + ' hs' : '--'}</td>
|
||||
<td class="text-center">
|
||||
<span class="badge ${l.status === 'AUTORIZADO' ? 'bg-success-subtle text-success' : 'bg-danger-subtle text-danger'}">
|
||||
${l.status === 'AUTORIZADO' ? 'OK' : l.status}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
} catch (e) {
|
||||
console.warn('Error refrescando logs:', e);
|
||||
}
|
||||
}
|
||||
|
||||
// Feedback sonoro opcional vía Web Audio API
|
||||
function playBeep(success) {
|
||||
try {
|
||||
const ctx = new (window.AudioContext || window.webkitAudioContext)();
|
||||
const osc = ctx.createOscillator();
|
||||
const gain = ctx.createGain();
|
||||
osc.connect(gain);
|
||||
gain.connect(ctx.destination);
|
||||
osc.frequency.value = success ? 880 : 330;
|
||||
gain.gain.value = 0.1;
|
||||
osc.start();
|
||||
setTimeout(() => { osc.stop(); }, 120);
|
||||
} catch (e) {}
|
||||
}
|
||||
</script>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,111 @@
|
||||
# Plan de Arquitectura Técnica (SDD-012)
|
||||
|
||||
## Módulo: Portal de Beneficios, Convenios Comerciales y Control de Acceso por QR con IA (UdeCi) y Rol Recepción
|
||||
|
||||
---
|
||||
|
||||
### 1. Diagrama de Arquitectura del Sistema
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
subgraph "Perfiles y Clientes Web"
|
||||
ALUMNO[Estudiante / Docente: Catálogo & Credencial QR]
|
||||
BEDELIA[Bedelía / Admin: Panel ABM de Convenios]
|
||||
RECEPCION[Personal de Recepción: Escáner QR de Acceso]
|
||||
CHAT[UdeCi: Tutor Conversacional con IA]
|
||||
end
|
||||
|
||||
subgraph "Frontend BFF Node.js / Express (:3000)"
|
||||
ROUTES_BENEFITS[/benefits & /benefits/manage]
|
||||
ROUTES_RECEPTION[/reception/scanner]
|
||||
ROUTES_CREDENTIAL[/credential/my-qr]
|
||||
PROXY_API[Axios Interceptors con Bearer Token]
|
||||
end
|
||||
|
||||
subgraph "Backend Core FastAPI (:5000)"
|
||||
ROUTER_BENEFITS[routers/benefits.py]
|
||||
ROUTER_RECEPTION[routers/reception.py]
|
||||
ROUTER_AI[routers/ai_chat.py]
|
||||
SERVICE_LIVE[services/live_context_service.py]
|
||||
SERVICE_QR[services/qr_security_service.py]
|
||||
end
|
||||
|
||||
subgraph "Persistencia PostgreSQL"
|
||||
TB_BENEFITS[(institutional_benefits)]
|
||||
TB_ACCESS_LOGS[(access_logs_qr)]
|
||||
TB_USERS[(users)]
|
||||
TB_RESERVATIONS[(reservations)]
|
||||
end
|
||||
|
||||
ALUMNO -->|1. Consulta beneficios / Mi QR| ROUTES_BENEFITS
|
||||
BEDELIA -->|2. Carga / Edita convenios| ROUTES_BENEFITS
|
||||
RECEPCION -->|3. Escanea QR de alumno| ROUTES_RECEPTION
|
||||
CHAT -->|4. Pregunta por promociones| PROXY_API
|
||||
|
||||
ROUTES_BENEFITS --> PROXY_API
|
||||
ROUTES_RECEPTION --> PROXY_API
|
||||
PROXY_API --> ROUTER_BENEFITS
|
||||
PROXY_API --> ROUTER_RECEPTION
|
||||
PROXY_API --> ROUTER_AI
|
||||
|
||||
ROUTER_BENEFITS --> TB_BENEFITS
|
||||
ROUTER_RECEPTION --> SERVICE_QR
|
||||
SERVICE_QR --> TB_ACCESS_LOGS
|
||||
SERVICE_QR --> TB_USERS
|
||||
SERVICE_QR --> TB_RESERVATIONS
|
||||
ROUTER_AI --> SERVICE_LIVE
|
||||
SERVICE_LIVE --> TB_BENEFITS
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Capas y Módulos a Desarrollar
|
||||
|
||||
#### Capa 1: Persistencia y Modelos SQLAlchemy ORM (`backend/models/`)
|
||||
1. **`models/institutional_benefit.py`**:
|
||||
- Campos: `id`, `title`, `partner_name`, `category`, `discount_label`, `description`, `terms_conditions`, `target_roles`, `building_id`, `coupon_code`, `valid_from`, `valid_until`, `is_active`, `image_url`, `created_by_user_id`, timestamps.
|
||||
- Relaciones con `Building` y `User`.
|
||||
2. **`models/access_log_qr.py`**:
|
||||
- Campos: `id`, `user_id`, `building_id`, `scanned_by_user_id`, `scanned_at`, `status`, `reason`.
|
||||
- Relaciones con `User` y `Building`.
|
||||
|
||||
#### Capa 2: DTOs y Esquemas Pydantic v2 (`backend/schemas/`)
|
||||
1. **`schemas/benefit_dto.py`**:
|
||||
- `BenefitBaseDTO`: Validaciones con `Field(..., min_length=3, max_length=150)`.
|
||||
- `BenefitCreateDTO`: `title`, `partner_name`, `category`, `discount_label`, `description`, `terms_conditions`, `target_roles`, `valid_from`, `valid_until`, etc.
|
||||
- `BenefitUpdateDTO`: Campos opcionales para edición parcial.
|
||||
- `BenefitResponseDTO`: Formato serializado con `model_config = ConfigDict(from_attributes=True)`.
|
||||
2. **`schemas/reception_dto.py`**:
|
||||
- `QRVerificationRequestDTO`: `qr_token: str`, `building_id: int`.
|
||||
- `QRVerificationResponseDTO`: `status: str`, `user_name: str`, `user_dni: str`, `user_role: str`, `matricula_status: str`, `todays_classes: List[ClassScheduleDTO]`, `scanned_at: datetime`.
|
||||
|
||||
#### Capa 3: Endpoints RESTful en FastAPI (`backend/routers/`)
|
||||
1. **`routers/benefits.py`** (`prefix="/api/v1/benefits"`, `tags=["Benefits & Convenios"]`):
|
||||
- `GET /`: Lista de beneficios vigentes con filtros por rol, categoría y sede.
|
||||
- `GET /{id}`: Detalle de un beneficio específico.
|
||||
- `POST /`: Creación de convenio (restringido a `ADMIN`, `BEDELIA`). Retorna `201 Created`.
|
||||
- `PUT /{id}`: Edición de convenio (restringido a `ADMIN`, `BEDELIA`). Retorna `200 OK`.
|
||||
- `PATCH /{id}/toggle-status`: Activa o pausa la publicación. Retorna `200 OK`.
|
||||
- `DELETE /{id}`: Eliminación lógica o física. Retorna `204 No Content`.
|
||||
2. **`routers/reception.py`** (`prefix="/api/v1/reception"`, `tags=["Reception & Access Control"]`):
|
||||
- `POST /verify-qr`: Valida el código QR, genera el `AccessLogQR` y retorna los datos y aulas del día en < 300 ms.
|
||||
- `GET /recent-logs`: Historial de los últimos ingresos escaneados por sede.
|
||||
- `GET /student-qr-token`: Genera el token firmado del alumno para su credencial virtual.
|
||||
|
||||
#### Capa 4: Integración con IA UdeCi y Contexto en Vivo
|
||||
1. **`LiveContextService` (`backend/app/services/live_context_service.py`)**:
|
||||
- Se inyecta la sección `CONVENIOS Y BENEFICIOS ACTIVOS`: lista resumida de promociones por categoría, descuentos y comercios vigentes.
|
||||
- Si un usuario pregunta sobre cafeterías o descuentos, UdeCi responde de inmediato utilizando datos reales de `InstitutionalBenefit`.
|
||||
2. **`GuideService`**:
|
||||
- Agregar guía paso a paso para que Bedelía aprenda a dar de alta convenios (`"¿Cómo publico un nuevo convenio?"`).
|
||||
|
||||
#### Capa 5: Frontend BFF (Express + Nunjucks + Bootstrap 5)
|
||||
1. **Rutas y Controladores (`frontend/src/routes/`)**:
|
||||
- `routes/benefits.js`: `/benefits` (catálogo para alumnos/docentes) y `/benefits/manage` (panel Bedelía).
|
||||
- `routes/reception.js`: `/reception/scanner` (consola de recepción con escáner de cámara).
|
||||
- `routes/credential.js`: `/credential/my-card` (credencial digital interactiva con QR).
|
||||
2. **Vistas Nunjucks**:
|
||||
- `views/benefits/catalog.html`: Grid de tarjetas con estilo marketplace, badges de descuento, buscador en vivo y modal de cupón/canje.
|
||||
- `views/benefits/manage.html`: Tabla de gestión con modales de alta/edición, switches de estado y selector de sede.
|
||||
- `views/reception/scanner.html`: Vista de alta velocidad con visor de cámara (`html5-qrcode`), campo de entrada para pistola USB, tarjeta de validación instantánea y cronograma áulico del día.
|
||||
- `views/credential/card.html`: Credencial universitaria digital con foto, datos de carrera y QR rotativo/seguro.
|
||||
@@ -0,0 +1,93 @@
|
||||
# Especificación de Requisitos de Software (SDD-012)
|
||||
|
||||
## Módulo: Portal de Beneficios, Convenios Comerciales y Control de Acceso por QR con IA (UdeCi) y Rol Recepción
|
||||
**ID de Especificación**: SDD-012
|
||||
**Estado**: Planificado / Aprobación de Arquitectura
|
||||
**Fecha**: 2026-10-27
|
||||
**Autores**: Coordinador de Arquitectura, Bedelía y Tutoría Virtual UniCABA
|
||||
|
||||
---
|
||||
|
||||
### 1. Visión General y Propósito
|
||||
|
||||
El presente requerimiento expande el ecosistema institucional de **Admin Edu-Space (UniCABA)** agregando valor tangible en la vida diaria de estudiantes, docentes y personal de Bedelía/Recepción, a través de dos ejes estratégicos interconectados con la inteligencia artificial **UdeCi**:
|
||||
|
||||
1. **Club de Beneficios y Convenios Institucionales**:
|
||||
- Una herramienta centralizada para que Bedelía y el Administrador carguen, administren y publiquen promociones, convenios y descuentos comerciales (cafeterías, librerías, tecnología, transporte, salud y cultura).
|
||||
- Un catálogo visual y responsive para estudiantes y docentes donde consultar beneficios y generar cupones o validar su pertenencia universitaria.
|
||||
- Integración nativa con **UdeCi** (IA RAG y Live Context): los alumnos y docentes pueden consultar en lenguaje natural los beneficios disponibles, promociones cercanas a su sede y condiciones de canje. UdeCi asiste a Bedelía en la redacción y auditoría de vencimientos de convenios.
|
||||
|
||||
2. **Perfil de Recepción y Control de Acceso Ágil por Código QR**:
|
||||
- Incorporación del rol institucional **`RECEPCION`** (personal de mesa de entrada, seguridad y torniquetes).
|
||||
- **Credencial Digital QR** accesible desde el portal móvil del alumno y docente, con código QR seguro y dinámico.
|
||||
- **Consola de Recepción con Escáner de Alta Velocidad**: al escanear el QR, la pantalla de recepción valida la matrícula en tiempo real, registra el ingreso (*check-in*) y muestra de forma inmediata las clases y aulas físicas asignadas para el día de hoy, permitiendo orientar al alumno en segundos.
|
||||
|
||||
---
|
||||
|
||||
### 2. Requisitos del Sistema en Sintaxis EARS (Español)
|
||||
|
||||
#### 2.1 Requisitos Ubicuos (Ubiquitous Requirements)
|
||||
- **REQ-UBI-01**: EL SISTEMA registrará en `AuditLog` toda creación, edición o cambio de estado de un convenio comercial y todo registro de ingreso institucional escaneado.
|
||||
- **REQ-UBI-02**: EL SISTEMA mantendrá el aislamiento de roles en el catálogo de beneficios: solo se mostrarán promociones vigentes dirigidas al rol específico del usuario (`ALUMNO`, `DOCENTE`, `TODOS`).
|
||||
- **REQ-UBI-03**: EL SISTEMA incorporará los convenios vigentes en la base de contexto en vivo de **UdeCi**, respondiendo consultas en tiempo real sobre promociones sin inventar datos mock.
|
||||
- **REQ-UBI-04**: EL SISTEMA garantizará que el Código QR de la Credencial Digital contenga un token verificable con firma o clave criptográfica institucional para impedir falsificaciones o clonaciones estáticas.
|
||||
|
||||
#### 2.2 Requisitos Basados en Eventos (Event-driven Requirements)
|
||||
- **REQ-EVT-01**: CUANDO un operador con rol `BEDELIA` o `ADMIN` guarde un nuevo convenio con fecha de inicio, fecha de fin, porcentaje de descuento y sede aplicable, EL SISTEMA validará los datos, persistirá el registro en `InstitutionalBenefit` y retornará código `201 Created`.
|
||||
- **REQ-EVT-02**: CUANDO un estudiante o docente consulte a UdeCi sobre descuentos (ej: *"¿Qué promociones hay en cafetería hoy?"* o *"¿Tengo descuento en librerías?"*), EL SISTEMA consultará la tabla de beneficios activos y responderá con los comercios adheridos, descuentos y pasos de canje.
|
||||
- **REQ-EVT-03**: CUANDO un operador de Bedelía solicite a UdeCi asistencia en la redacción de un convenio, EL SISTEMA generará una propuesta con cláusulas claras, términos y condiciones y etiquetas de descuento optimizadas.
|
||||
- **REQ-EVT-04**: CUANDO un alumno o docente acceda a la sección "Mi Credencial", EL SISTEMA generará su credencial virtual con foto, nombre, DNI, carrera/rol y su código QR institucional interactivo.
|
||||
- **REQ-EVT-05**: CUANDO el personal de `RECEPCION` escanee el código QR desde la cámara del dispositivo o lector óptico USB, EL SISTEMA validará la identidad en menos de 300 ms, registrará el evento en `AccessLogQR` y desplegará en verde la foto, estado del alumno y el cronograma áulico del día (aula física, sede, piso y horario).
|
||||
|
||||
#### 2.3 Requisitos de Estado (State-driven Requirements)
|
||||
- **REQ-STA-01**: MIENTRAS un convenio se encuentre fuera del rango de fechas de vigencia (`valid_until < fecha_actual`), EL SISTEMA marcará automáticamente su estado como vencido y lo ocultará del catálogo general de alumnos y docentes.
|
||||
- **REQ-STA-02**: MIENTRAS el personal opere en el perfil `RECEPCION`, EL SISTEMA presentará una interfaz minimalista optimizada para pantalla táctil o kiosco de acceso, bloqueando la navegación a paneles sensibles de notas o configuración.
|
||||
|
||||
#### 2.4 Requisitos de Situaciones No Deseadas (Unwanted Behaviour Requirements)
|
||||
- **REQ-NO-01**: SI el código QR escaneado por Recepción es inválido, manipulado o corresponde a un usuario suspendido o inactivo, ENTONCES EL SISTEMA emitirá una alerta visual roja y sonora de "Acceso Denegado / Verificar en Bedelía", registrando el intento fallido.
|
||||
- **REQ-NO-02**: SI un usuario con rol Alumno intenta acceder al panel de gestión y alta de convenios (`/benefits/manage`), ENTONCES EL SISTEMA denegará el acceso retornando error `403 Forbidden` y redirigiéndolo a su catálogo de beneficios.
|
||||
- **REQ-NO-03**: SI el comercio o sede asociada al convenio se encuentra inactiva, ENTONCES EL SISTEMA suspenderá la visualización del beneficio hasta su regularización.
|
||||
|
||||
#### 2.5 Requisitos Opcionales (Optional Features)
|
||||
- **REQ-OPC-01**: DONDE el convenio comercial cuente con un código o cupón de descuento alfanumérico (ej: `UNICABA-CAFE-20`), EL SISTEMA mostrará un botón interactivo de "Copiar Cupón" y un código de barras / QR específico para mostrar en la caja del comercio.
|
||||
- **REQ-OPC-02**: DONDE el alumno escanee su ingreso y tenga clase en los próximos 15 minutos, EL SISTEMA podrá orientar con un aviso en pantalla: *"¡Bienvenido a Sede Central! Tu clase comienza a las 18:30 en Aula 102 (1º Piso)"*.
|
||||
|
||||
---
|
||||
|
||||
### 3. Modelo de Dominio y Persistencia Propuesta
|
||||
|
||||
#### 3.1 Entidad `InstitutionalBenefit` (Tabla `institutional_benefits`)
|
||||
- `id` (Integer, PK)
|
||||
- `title` (String 150): Nombre de la promoción o convenio (ej: "20% en Cafetería La Estación").
|
||||
- `partner_name` (String 120): Empresa o comercio asociado (ej: "Café Martínez Central").
|
||||
- `category` (String 50): Categoría (`GASTRONOMIA`, `LIBRERIA`, `TECNOLOGIA`, `SALUD_DEPORTE`, `IDIOMAS`, `CULTURA`, `SERVICIOS`).
|
||||
- `discount_label` (String 80): Etiqueta destacada (ej: "20% OFF", "2x1", "$1.500 de ahorro").
|
||||
- `description` (Text): Descripción detallada del convenio.
|
||||
- `terms_conditions` (Text): Cláusulas, días de validez y restricciones.
|
||||
- `target_roles` (String 50): Perfiles habilitados (`ALL`, `ALUMNO`, `DOCENTE`, `BEDELIA`).
|
||||
- `building_id` (Integer FK nullable -> `buildings.id`): Sede aplicable o `None` para todas.
|
||||
- `coupon_code` (String 50, nullable): Código promocional alfanumérico.
|
||||
- `valid_from` (Date): Inicio de vigencia.
|
||||
- `valid_until` (Date, nullable): Fin de vigencia.
|
||||
- `is_active` (Boolean, default True): Switch de publicación inmediata.
|
||||
- `image_url` (String 255, nullable): Imagen o logotipo representativo.
|
||||
- `created_by_user_id` (Integer FK -> `users.id`): Usuario responsable del alta.
|
||||
- `created_at`, `updated_at` (DateTime): Timestamps de auditoría.
|
||||
|
||||
#### 3.2 Entidad `AccessLogQR` (Tabla `access_logs_qr`)
|
||||
- `id` (Integer, PK)
|
||||
- `user_id` (Integer FK -> `users.id`): Alumno o docente que ingresó.
|
||||
- `building_id` (Integer FK -> `buildings.id`): Sede donde se realizó el escaneo.
|
||||
- `scanned_by_user_id` (Integer FK -> `users.id`): Personal de recepción que escaneó.
|
||||
- `scanned_at` (DateTime): Momento exacto del ingreso.
|
||||
- `status` (String 20): `AUTORIZADO`, `DENEGADO`, `RESTRINGIDO`.
|
||||
- `reason` (String 150, nullable): Causa del rechazo o notas operativas.
|
||||
|
||||
---
|
||||
|
||||
### 4. Criterios de Aceptación y Validación
|
||||
1. **ABM Bedelía y Admin**: Capacidad de crear, editar, pausar y eliminar beneficios con validación de fechas y roles.
|
||||
2. **Catálogo para Alumnos y Docentes**: Navegación fluida por tarjetas con filtros por categoría y búsqueda en tiempo real.
|
||||
3. **Integración UdeCi**: Respuestas en lenguaje natural sobre convenios basadas en los datos reales cargados.
|
||||
4. **Credencial QR**: Generación dinámica en el portal del usuario.
|
||||
5. **Consola Recepción**: Escaneo con cámara y visualización en tiempo real de identidad y aulas de cursada del día.
|
||||
@@ -0,0 +1,81 @@
|
||||
# Desglose de Tareas: Portal de Beneficios, Convenios y Control de Acceso QR (SDD-012)
|
||||
|
||||
## Tareas de Implementación
|
||||
|
||||
- [x] **Tarea 1: Modelos de Persistencia SQLAlchemy (`InstitutionalBenefit` y `AccessLogQR`)**
|
||||
- **Estimación**: 25 min
|
||||
- **Acciones**:
|
||||
- Crear `backend/models/institutional_benefit.py` con campos de título, comercio, categoría, descuento, términos, roles objetivo, fechas de vigencia y switch de estado activo.
|
||||
- Crear `backend/models/access_log_qr.py` para trazabilidad de ingresos escaneados por sede y personal de recepción.
|
||||
- Importar y registrar los modelos en `backend/models/__init__.py`.
|
||||
- **Hecho cuando**: Las tablas se crean correctamente en PostgreSQL/SQLite sin errores de clave foránea ni regresiones de inicialización.
|
||||
|
||||
- [x] **Tarea 2: DTOs Pydantic v2 y Endpoints RESTful de Beneficios (`routers/benefits.py`)**
|
||||
- **Estimación**: 30 min
|
||||
- **Acciones**:
|
||||
- Crear `backend/schemas/benefit_dto.py` con validaciones de campos (`min_length`, fechas, roles).
|
||||
- Crear `backend/routers/benefits.py` con operaciones CRUD (`GET /`, `GET /{id}`, `POST /`, `PUT /{id}`, `PATCH /{id}/toggle-status`, `DELETE /{id}`).
|
||||
- Proteger rutas de escritura exigiendo roles `ADMIN` o `BEDELIA`.
|
||||
- Registrar el router en `backend/main.py`.
|
||||
- **Hecho cuando**: Peticiones a `/api/v1/benefits` responden con códigos HTTP semánticos (200, 201, 204, 403, 404, 422) y aparecen en OpenAPI Swagger UI (`/docs`).
|
||||
|
||||
- [x] **Tarea 3: Servicio de Seguridad QR y Endpoints de Recepción (`routers/reception.py`)**
|
||||
- **Estimación**: 30 min
|
||||
- **Acciones**:
|
||||
- Crear `backend/app/services/qr_security_service.py` para generar y verificar tokens de credencial firmados con HMAC-SHA256 institucional.
|
||||
- Crear `backend/schemas/reception_dto.py` para los contratos de verificación de acceso.
|
||||
- Crear `backend/routers/reception.py` con `/api/v1/reception/verify-qr` y `/api/v1/reception/recent-logs`.
|
||||
- Integrar la búsqueda de clases presenciales del día para mostrar el aula y piso asignado al momento de ingresar.
|
||||
- Registrar el router en `backend/main.py`.
|
||||
- **Hecho cuando**: Un escaneo de QR válido responde con `status: AUTORIZADO`, datos del alumno y sus aulas asignadas del día en < 300 ms.
|
||||
|
||||
- [x] **Tarea 4: Integración de Convenios en el Motor Conversacional de UdeCi**
|
||||
- **Estimación**: 20 min
|
||||
- **Acciones**:
|
||||
- Modificar `backend/app/services/live_context_service.py` para inyectar los convenios vigentes en el contexto en vivo de UdeCi.
|
||||
- Actualizar las reglas del System Prompt en `backend/routers/ai_chat.py` para responder consultas sobre descuentos en cafeterías, librerías y beneficios institucionales reales.
|
||||
- **Hecho cuando**: Al consultar a UdeCi *"¿Qué descuentos hay en cafetería?"*, responde citando comercios, porcentaje y condiciones reales de la base de datos.
|
||||
|
||||
- [x] **Tarea 5: Panel de Gestión de Convenios para Bedelía y Admin (Frontend BFF)**
|
||||
- **Estimación**: 30 min
|
||||
- **Acciones**:
|
||||
- Crear controlador `frontend/src/routes/benefits.js` y vista `frontend/views/benefits/manage.html`.
|
||||
- Implementar tabla de convenios con badges de categoría, switches de activación rápida y modal de alta/edición.
|
||||
- Incorporar el enlace en el menú lateral de Bedelía y Administración (`sidebar.html`).
|
||||
- **Hecho cuando**: Bedelía puede dar de alta un convenio con descuento, fechas y sede desde la interfaz web con feedback visual inmediato.
|
||||
|
||||
- [x] **Tarea 6: Catálogo de Beneficios y Credencial Digital QR para Alumnos y Docentes**
|
||||
- **Estimación**: 30 min
|
||||
- **Acciones**:
|
||||
- Crear vista `frontend/views/benefits/catalog.html` con tarjetas estilo marketplace, buscador interactivo y filtro por categoría (Cafetería, Librería, etc.).
|
||||
- Crear vista `frontend/views/credential/card.html` ("Mi Credencial Digital") mostrando foto, datos institucionales y código QR dinámico.
|
||||
- Añadir accesos en el menú de Estudiante y Docente.
|
||||
- **Hecho cuando**: Un estudiante puede explorar los convenios vigentes, abrir el cupón y visualizar su Credencial QR en su teléfono.
|
||||
|
||||
- [x] **Tarea 7: Consola de Escáner de Recepción y Control de Acceso en Vivo**
|
||||
- **Estimación**: 30 min
|
||||
- **Acciones**:
|
||||
- Crear vista `frontend/views/reception/scanner.html` con lector de cámara (`html5-qrcode`) y soporte para pistola de código de barras USB.
|
||||
- Integrar modal/tarjeta de validación instantánea con indicadores visuales (verde/rojo) y cronograma de clases de hoy con sede, aula y piso.
|
||||
- Configurar permisos en el BFF para el rol `RECEPCION` y administradores.
|
||||
- **Hecho cuando**: Al escanear un QR con la cámara, la pantalla muestra de inmediato la foto, el estado de matrícula y el aula donde cursa hoy.
|
||||
|
||||
- [x] **Tarea 8: Suite de Pruebas Automatizadas Backend y Cobertura E2E**
|
||||
- **Estimación**: 20 min
|
||||
- **Acciones**:
|
||||
- Crear `backend/tests/test_benefits_and_reception.py` cubriendo:
|
||||
- CRUD de beneficios y restricciones de roles.
|
||||
- Validación de vigencia de fechas.
|
||||
- Generación y verificación de tokens QR.
|
||||
- Registro de logs de acceso.
|
||||
- Respuestas de UdeCi sobre beneficios en vivo.
|
||||
- Ejecutar `pytest tests/ -v` asegurando 100% de tests pasando.
|
||||
- **Hecho cuando**: Todos los tests de la suite pasan exitosamente sin fallos ni warnings no controlados.
|
||||
|
||||
- [x] **Tarea 9: Bump de Versión, Git Push y Despliegue Continuo en Producción (LXC 10.0.0.217)**
|
||||
- **Estimación**: 20 min
|
||||
- **Acciones**:
|
||||
- Incrementar versión semántica en `package.json`, `app.js`, `__init__.py`, `setup.py`, `CHANGELOG.md` y `MEMORY.md`.
|
||||
- Ejecutar `git push origin dev`.
|
||||
- Desplegar en el contenedor de producción (`10.0.0.217`) y validar HTTP 200 en `/version`.
|
||||
- **Hecho cuando**: Producción corre la nueva versión con los módulos de beneficios y recepción operativos.
|
||||
Reference in New Issue
Block a user