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