feat(benefits-reception): add institutional benefits, QR digital card & reception access control (SDD-012 v3.8.39)
This commit is contained in:
@@ -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
|
||||
Reference in New Issue
Block a user