431 lines
17 KiB
Python
431 lines
17 KiB
Python
"""Router `screening` (Fase 4, PR 2): bandeja de coincidencias, decisión, listas y umbrales.
|
|
|
|
- `GET /screening`: bandeja con filtros por lista, decisión, rango de score y cliente; el conteo de
|
|
pendientes se pinta en la barra lateral (`registrar_contador`).
|
|
Cada fila abre el detalle; las pendientes muestran el botón «Revisar» y todas cotejan la fecha de
|
|
nacimiento y la nacionalidad del cliente junto a las de la entrada de la lista.
|
|
- `GET /screening/<id>`: nombre del cliente frente al de la lista, score, alias, versión y datos
|
|
adicionales de la entrada, más el formulario de decisión; ya decidida, «Siguiente pendiente».
|
|
- `GET /screening/siguiente`: la primera pendiente en el orden de la bandeja; sin pendientes,
|
|
vuelve a la bandeja con «Sin coincidencias pendientes».
|
|
- `POST /screening/<id>/decidir`: `analista` u `oficial`; `auditor` solo lee.
|
|
- `GET /screening/listas`: versiones cargadas con fecha, entradas, hash y umbral; edición del
|
|
umbral solo con rol `oficial` (`POST /screening/listas/<id>/umbral`).
|
|
- `POST /clientes/<id>/screening`: "Volver a consultar" desde el expediente.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Annotated, Any
|
|
from urllib.parse import urlencode
|
|
|
|
from fastapi import APIRouter, Depends, Form, HTTPException, Query, Request, status
|
|
from sqlalchemy import func, or_, select
|
|
from sqlalchemy.orm import Session
|
|
from starlette.responses import HTMLResponse, RedirectResponse, Response
|
|
|
|
from app import db as bd
|
|
from app.auth import requiere_rol
|
|
from app.db import get_db
|
|
from app.engine.screening import normalizar
|
|
from app.importers.lists import LISTAS, NACIONALIDAD, etiqueta_pais
|
|
from app.models import Cliente, Coincidencia, Identificacion, Lista, Usuario
|
|
from app.models.screening import DECISIONES_COINCIDENCIA, FUENTE_DECLARADA_ORIGEN
|
|
from app.models.usuario import Rol
|
|
from app.routers import etiqueta_fuente, registrar_contador, render
|
|
from app.services import screening as servicio
|
|
from app.services.alertas import tenant_de_sesion
|
|
|
|
router = APIRouter(tags=["screening"])
|
|
ROLES_DECIDEN = (Rol.ANALISTA, Rol.OFICIAL)
|
|
POR_PAGINA = 50
|
|
TITULOS = {clave: d.titulo for clave, d in LISTAS.items()}
|
|
|
|
|
|
def _pendientes(request: Request) -> int | None:
|
|
tenant = getattr(request.state, "tenant", None)
|
|
if tenant is None:
|
|
return None
|
|
with bd.SessionLocal() as session:
|
|
return servicio.pendientes(session, tenant)
|
|
|
|
|
|
registrar_contador("/screening", _pendientes)
|
|
|
|
|
|
def _titulo_lista(lista: Lista | None, fuente: str) -> str:
|
|
if lista is None:
|
|
return etiqueta_fuente(fuente)
|
|
return TITULOS.get(lista.nombre, lista.nombre)
|
|
|
|
|
|
def _nombres(session: Session, ids: set[int]) -> dict[int, str]:
|
|
if not ids:
|
|
return {}
|
|
return dict(
|
|
session.execute(
|
|
select(Identificacion.cliente_id, Identificacion.nombre_busqueda).where(
|
|
Identificacion.cliente_id.in_(ids), Identificacion.valid_to.is_(None)
|
|
)
|
|
).all()
|
|
)
|
|
|
|
|
|
def _nacionalidades(session: Session, clientes: list[Cliente]) -> dict[int, str | None]:
|
|
"""Nacionalidad del cliente: la de su identificación vigente o, si no la trae, la de la carga
|
|
(`cliente.pais` guarda la nacionalidad de la plantilla)."""
|
|
ids = {c.id for c in clientes}
|
|
datos = (
|
|
dict(
|
|
session.execute(
|
|
select(Identificacion.cliente_id, Identificacion.datos).where(
|
|
Identificacion.cliente_id.in_(ids), Identificacion.valid_to.is_(None)
|
|
)
|
|
).all()
|
|
)
|
|
if ids
|
|
else {}
|
|
)
|
|
return {c.id: (datos.get(c.id) or {}).get("nacionalidad") or c.pais for c in clientes}
|
|
|
|
|
|
def _fecha_lista(valor: Any) -> str | None:
|
|
"""`detalle.fecha_nacimiento` de la entrada (ISO) como dd/mm/aaaa; un año suelto se queda."""
|
|
if not valor:
|
|
return None
|
|
texto = str(valor)
|
|
partes = texto.split("-")
|
|
if len(partes) == 3 and all(p.isdigit() for p in partes):
|
|
return f"{partes[2]}/{partes[1]}/{partes[0]}"
|
|
return texto
|
|
|
|
|
|
ORDEN_BANDEJA = (Coincidencia.decision.desc(), Coincidencia.score.desc(), Coincidencia.id.desc())
|
|
SIN_PENDIENTES = "Sin coincidencias pendientes"
|
|
|
|
|
|
def _siguiente_pendiente(
|
|
session: Session, tenant_id: int, excepto: int | None = None
|
|
) -> int | None:
|
|
"""La primera coincidencia pendiente en el orden de la bandeja (mayor score primero)."""
|
|
consulta = select(Coincidencia.id).where(
|
|
Coincidencia.tenant_id == tenant_id, Coincidencia.decision == "pendiente"
|
|
)
|
|
if excepto is not None:
|
|
consulta = consulta.where(Coincidencia.id != excepto)
|
|
return session.scalar(consulta.order_by(*ORDEN_BANDEJA[1:]).limit(1))
|
|
|
|
|
|
def _volver(ruta: str, *, aviso: str | None = None, error: str | None = None) -> Response:
|
|
parametros = {k: v for k, v in (("aviso", aviso), ("error", error)) if v}
|
|
sufijo = f"?{urlencode(parametros)}" if parametros else ""
|
|
return RedirectResponse(f"{ruta}{sufijo}", status_code=status.HTTP_303_SEE_OTHER)
|
|
|
|
|
|
# --- Bandeja ----------------------------------------------------------------------------------
|
|
|
|
|
|
@router.get("/screening", include_in_schema=False)
|
|
def bandeja(
|
|
request: Request,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
lista: Annotated[str, Query(max_length=64)] = "",
|
|
decision: Annotated[str, Query(max_length=12)] = "pendiente",
|
|
score_min: Annotated[str, Query(max_length=6)] = "",
|
|
score_max: Annotated[str, Query(max_length=6)] = "",
|
|
q: Annotated[str, Query(max_length=120)] = "",
|
|
pagina: Annotated[int, Query(ge=1)] = 1,
|
|
) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
consulta = (
|
|
select(Coincidencia, Lista, Cliente)
|
|
.outerjoin(Lista, Lista.id == Coincidencia.lista_id)
|
|
.join(Cliente, Cliente.id == Coincidencia.persona_id)
|
|
.where(Coincidencia.tenant_id == tenant.id)
|
|
)
|
|
if lista == FUENTE_DECLARADA_ORIGEN:
|
|
consulta = consulta.where(Coincidencia.fuente == FUENTE_DECLARADA_ORIGEN)
|
|
elif lista:
|
|
consulta = consulta.where(Lista.nombre == lista)
|
|
if decision in DECISIONES_COINCIDENCIA:
|
|
consulta = consulta.where(Coincidencia.decision == decision)
|
|
else:
|
|
decision = ""
|
|
minimo = _numero(score_min)
|
|
maximo = _numero(score_max)
|
|
if minimo is not None:
|
|
consulta = consulta.where(Coincidencia.score >= minimo)
|
|
if maximo is not None:
|
|
consulta = consulta.where(Coincidencia.score <= maximo)
|
|
if q.strip():
|
|
patron = f"%{q.strip()}%"
|
|
nombres_sub = select(Identificacion.cliente_id).where(
|
|
Identificacion.valid_to.is_(None), Identificacion.nombre_busqueda.ilike(patron)
|
|
)
|
|
condiciones = [Cliente.id_externo.ilike(patron), Cliente.id.in_(nombres_sub)]
|
|
if q.strip().isdigit():
|
|
condiciones.append(Cliente.id == int(q.strip()))
|
|
consulta = consulta.where(or_(*condiciones))
|
|
total = db.scalar(select(func.count()).select_from(consulta.subquery())) or 0
|
|
filas = db.execute(
|
|
consulta.order_by(*ORDEN_BANDEJA).offset((pagina - 1) * POR_PAGINA).limit(POR_PAGINA)
|
|
).all()
|
|
nombres = _nombres(db, {c.id for _, _, c in filas})
|
|
nacionalidades = _nacionalidades(db, [c for _, _, c in filas])
|
|
return render(
|
|
request,
|
|
"screening/index.html",
|
|
{
|
|
"filas": [
|
|
{
|
|
"coincidencia": co,
|
|
"lista": li,
|
|
"titulo_lista": _titulo_lista(li, co.fuente),
|
|
"cliente": cl,
|
|
"nombre": nombres.get(cl.id),
|
|
"nacimiento": (
|
|
cl.fecha_nacimiento.strftime("%d/%m/%Y") if cl.fecha_nacimiento else None,
|
|
_fecha_lista((co.detalle or {}).get("fecha_nacimiento")),
|
|
),
|
|
# El país de la entrada con lo que es (nacionalidad o domicilio): no se coteja
|
|
# un domicilio contra una nacionalidad.
|
|
"nacionalidad": (
|
|
nacionalidades.get(cl.id),
|
|
(co.detalle or {}).get("pais"),
|
|
etiqueta_pais(
|
|
li.nombre if li else None, (co.detalle or {}).get("tipo_persona")
|
|
),
|
|
),
|
|
}
|
|
for co, li, cl in filas
|
|
],
|
|
"filtros": {
|
|
"lista": lista,
|
|
"decision": decision,
|
|
"score_min": score_min,
|
|
"score_max": score_max,
|
|
"q": q,
|
|
},
|
|
"listas": [(clave, d.titulo) for clave, d in LISTAS.items()],
|
|
"fuente_chm": FUENTE_DECLARADA_ORIGEN,
|
|
"NACIONALIDAD": NACIONALIDAD,
|
|
"total": total,
|
|
"pagina": pagina,
|
|
"paginas": max(1, -(-total // POR_PAGINA)),
|
|
"pendientes": servicio.pendientes(db, tenant),
|
|
"aviso": request.query_params.get("aviso"),
|
|
"error": request.query_params.get("error"),
|
|
},
|
|
)
|
|
|
|
|
|
def _numero(texto: str) -> float | None:
|
|
texto = (texto or "").strip()
|
|
if not texto:
|
|
return None
|
|
try:
|
|
valor = float(texto)
|
|
except ValueError:
|
|
return None
|
|
return min(max(valor, 0.0), 100.0)
|
|
|
|
|
|
# --- Listas y umbrales ------------------------------------------------------------------------
|
|
|
|
|
|
@router.get("/screening/listas", include_in_schema=False)
|
|
def listas(request: Request, db: Annotated[Session, Depends(get_db)]) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
vigentes = {lista.id for lista in servicio.listas_vigentes(db, tenant).values()}
|
|
conteos = servicio.resumen_por_lista(db, tenant)
|
|
return render(
|
|
request,
|
|
"screening/listas.html",
|
|
{
|
|
"versiones": [
|
|
{
|
|
"lista": lista,
|
|
"titulo": TITULOS.get(lista.nombre, lista.nombre),
|
|
"vigente": lista.id in vigentes,
|
|
"conteo": conteos.get(lista.id, {}),
|
|
"nota": LISTAS[lista.nombre].nota if lista.nombre in LISTAS else "",
|
|
}
|
|
for lista in servicio.versiones(db, tenant)
|
|
],
|
|
"puede_editar": request.state.usuario.rol == Rol.OFICIAL,
|
|
"aviso": request.query_params.get("aviso"),
|
|
"error": request.query_params.get("error"),
|
|
},
|
|
)
|
|
|
|
|
|
@router.post("/screening/listas/{lista_id:int}/umbral", include_in_schema=False)
|
|
def cambiar_umbral(
|
|
lista_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(Rol.OFICIAL))],
|
|
umbral: Annotated[str, Form()] = "",
|
|
justificacion: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
try:
|
|
with db.begin_nested():
|
|
lista = servicio.actualizar_umbral(db, lista_id, umbral, justificacion, usuario.usuario)
|
|
except servicio.ScreeningError as exc:
|
|
return _volver("/screening/listas", error=str(exc))
|
|
except LookupError:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Lista no encontrada.") from None
|
|
db.commit()
|
|
return _volver("/screening/listas", aviso=f"umbral-{lista.id}")
|
|
|
|
|
|
# --- Detalle y decisión -----------------------------------------------------------------------
|
|
|
|
|
|
def _detalle(
|
|
request: Request,
|
|
db: Session,
|
|
coincidencia_id: int,
|
|
*,
|
|
error: str | None = None,
|
|
status_code: int = 200,
|
|
) -> HTMLResponse:
|
|
tenant = tenant_de_sesion(db)
|
|
try:
|
|
coincidencia = servicio.coincidencia_del_tenant(db, tenant, coincidencia_id)
|
|
except servicio.CoincidenciaNoEncontradaError:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Coincidencia no encontrada.") from None
|
|
lista = db.get(Lista, coincidencia.lista_id) if coincidencia.lista_id else None
|
|
persona = db.get(Cliente, coincidencia.persona_id)
|
|
nombre = _nombres(db, {persona.id}).get(persona.id)
|
|
detalle_: dict[str, Any] = dict(coincidencia.detalle or {})
|
|
consultado_desde = detalle_.pop("consultado_desde_cliente_id", None)
|
|
rol_consultado = detalle_.pop("rol_consultado", None)
|
|
campos_fijos = (
|
|
"nombre_en_lista",
|
|
"alias_en_lista",
|
|
"tipo_persona",
|
|
"fecha_nacimiento",
|
|
"pais",
|
|
"coincidio_por_alias",
|
|
)
|
|
adicionales = {k: v for k, v in detalle_.items() if k not in campos_fijos}
|
|
return render(
|
|
request,
|
|
"screening/detalle.html",
|
|
{
|
|
"coincidencia": coincidencia,
|
|
"lista": lista,
|
|
"titulo_lista": _titulo_lista(lista, coincidencia.fuente),
|
|
"persona": persona,
|
|
"nombre": nombre,
|
|
"nombre_normalizado": normalizar(nombre) if nombre else "",
|
|
"nacionalidad": _nacionalidades(db, [persona]).get(persona.id),
|
|
"etiqueta_pais": etiqueta_pais(
|
|
lista.nombre if lista else None, detalle_.get("tipo_persona")
|
|
),
|
|
"texto_normalizado": normalizar(coincidencia.texto_lista),
|
|
"detalle": detalle_,
|
|
"adicionales": adicionales,
|
|
"consultado_desde": consultado_desde,
|
|
"rol_consultado": rol_consultado,
|
|
"es_chm": coincidencia.fuente == FUENTE_DECLARADA_ORIGEN,
|
|
"puede_decidir": request.state.usuario.rol in ROLES_DECIDEN,
|
|
"minimo_justificacion": servicio.LARGO_MINIMO_JUSTIFICACION,
|
|
"historial": _historial_decisiones(db, coincidencia.id),
|
|
# Ya decidida: «Siguiente pendiente» lleva a la próxima o de vuelta a la bandeja.
|
|
"ofrece_siguiente": coincidencia.decision != "pendiente"
|
|
and request.state.usuario.rol in ROLES_DECIDEN,
|
|
"error": error or request.query_params.get("error"),
|
|
"aviso": request.query_params.get("aviso"),
|
|
},
|
|
status_code=status_code,
|
|
)
|
|
|
|
|
|
@router.get("/screening/siguiente", include_in_schema=False)
|
|
def siguiente(
|
|
db: Annotated[Session, Depends(get_db)],
|
|
desde: Annotated[int | None, Query()] = None,
|
|
) -> Response:
|
|
"""La siguiente coincidencia pendiente o, si no queda ninguna, la bandeja con el aviso."""
|
|
tenant = tenant_de_sesion(db)
|
|
proxima = _siguiente_pendiente(db, tenant.id, excepto=desde)
|
|
if proxima is None:
|
|
return _volver("/screening", aviso=SIN_PENDIENTES)
|
|
return RedirectResponse(f"/screening/{proxima}", status_code=status.HTTP_303_SEE_OTHER)
|
|
|
|
|
|
@router.get("/screening/{coincidencia_id:int}", include_in_schema=False)
|
|
def detalle(
|
|
request: Request, coincidencia_id: int, db: Annotated[Session, Depends(get_db)]
|
|
) -> HTMLResponse:
|
|
return _detalle(request, db, coincidencia_id)
|
|
|
|
|
|
def _historial_decisiones(db: Session, coincidencia_id: int) -> list[dict[str, Any]]:
|
|
from app.models import AuditTrail
|
|
|
|
filas = db.scalars(
|
|
select(AuditTrail)
|
|
.where(
|
|
AuditTrail.entidad == "coincidencia",
|
|
AuditTrail.entidad_id == coincidencia_id,
|
|
AuditTrail.accion.like("decidir:%"),
|
|
)
|
|
.order_by(AuditTrail.id.desc())
|
|
).all()
|
|
return [
|
|
{
|
|
"fecha": f.created_at,
|
|
"usuario": f.usuario,
|
|
"decision": f.accion.split(":", 1)[1],
|
|
"antes": (f.antes or {}).get("decision"),
|
|
"motivo": f.motivo,
|
|
}
|
|
for f in filas
|
|
]
|
|
|
|
|
|
@router.post("/screening/{coincidencia_id:int}/decidir", include_in_schema=False)
|
|
def decidir(
|
|
request: Request,
|
|
coincidencia_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_DECIDEN))],
|
|
decision: Annotated[str, Form()] = "",
|
|
justificacion: Annotated[str, Form()] = "",
|
|
) -> Response:
|
|
try:
|
|
with db.begin_nested():
|
|
servicio.decidir(db, coincidencia_id, decision, justificacion, usuario.usuario)
|
|
except servicio.ScreeningError as exc:
|
|
return _detalle(request, db, coincidencia_id, error=str(exc), status_code=400)
|
|
except servicio.CoincidenciaNoEncontradaError:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Coincidencia no encontrada.") from None
|
|
db.commit()
|
|
return _volver(f"/screening/{coincidencia_id}", aviso=decision)
|
|
|
|
|
|
# --- Desde el expediente ----------------------------------------------------------------------
|
|
|
|
|
|
@router.post("/clientes/{cliente_id:int}/screening", include_in_schema=False)
|
|
def consultar_cliente(
|
|
cliente_id: int,
|
|
db: Annotated[Session, Depends(get_db)],
|
|
usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_DECIDEN))],
|
|
) -> Response:
|
|
ruta = f"/clientes/{cliente_id}"
|
|
try:
|
|
with db.begin_nested():
|
|
resumen = servicio.screening_cliente(db, cliente_id, usuario=usuario.usuario)
|
|
except LookupError:
|
|
raise HTTPException(status.HTTP_404_NOT_FOUND, "Cliente no encontrado.") from None
|
|
except servicio.ScreeningError as exc:
|
|
return RedirectResponse(
|
|
f"{ruta}?{urlencode({'error': str(exc)})}#listas", status_code=status.HTTP_303_SEE_OTHER
|
|
)
|
|
db.commit()
|
|
aviso = f"screening-{resumen.creadas}-{resumen.consultados}"
|
|
return RedirectResponse(f"{ruta}?aviso={aviso}#listas", status_code=status.HTTP_303_SEE_OTHER)
|