diff --git a/app/routers/cartera.py b/app/routers/cartera.py
new file mode 100644
index 0000000..e4243c2
--- /dev/null
+++ b/app/routers/cartera.py
@@ -0,0 +1,129 @@
+"""Router `cartera`: listado de clientes con filtros (nivel de riesgo, estado de relación,
+búsqueda por `id_externo`), conteos y paginación. Fase 3 (Pieza D).
+
+El nivel vigente de cada cliente es la última `evaluacion_riesgo` (la escribe la Pieza C; aquí
+solo se lee, en bloque, para filtrar y contar con la cartera completa en menos de un segundo).
+`None` se muestra como "sin evaluar".
+"""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, HTTPException, Query, Request, status
+from pydantic import ValidationError
+from sqlalchemy import func, select
+from sqlalchemy.orm import Session
+from starlette.responses import HTMLResponse
+
+from app.db import get_db
+from app.models import Cliente, EvaluacionRiesgo
+from app.routers import render
+from app.schemas.alertas import FiltrosCartera
+from app.services.alertas import alertas_abiertas_por_cliente, tenant_de_sesion
+
+router = APIRouter(tags=["cartera"])
+
+NIVELES = ("bajo", "medio", "alto")
+SIN_EVALUAR = "sin_evaluar"
+
+
+def niveles_vigentes(session: Session, tenant_id: int) -> dict[int, str]:
+ """`cliente_id → nivel` de la última evaluación de cada cliente del tenant (lectura)."""
+ ultima = (
+ select(EvaluacionRiesgo.cliente_id, func.max(EvaluacionRiesgo.id).label("id"))
+ .where(EvaluacionRiesgo.tenant_id == tenant_id)
+ .group_by(EvaluacionRiesgo.cliente_id)
+ .subquery()
+ )
+ filas = session.execute(
+ select(EvaluacionRiesgo.cliente_id, EvaluacionRiesgo.nivel).join(
+ ultima, EvaluacionRiesgo.id == ultima.c.id
+ )
+ )
+ return {cliente_id: nivel for cliente_id, nivel in filas}
+
+
+def _filtros(
+ nivel: str | None = Query(default=None),
+ estado_relacion: str | None = Query(default=None),
+ q: str | None = Query(default=None),
+ pagina: int = Query(default=1, ge=1),
+) -> FiltrosCartera:
+ try:
+ return FiltrosCartera(nivel=nivel, estado_relacion=estado_relacion, q=q, pagina=pagina)
+ except ValidationError as exc:
+ raise HTTPException(status.HTTP_422_UNPROCESSABLE_CONTENT, exc.errors()) from None
+
+
+@router.get("/cartera", include_in_schema=False)
+def cartera(
+ request: Request,
+ db: Annotated[Session, Depends(get_db)],
+ filtros: Annotated[FiltrosCartera, Depends(_filtros)],
+) -> HTMLResponse:
+ tenant = tenant_de_sesion(db)
+ niveles = niveles_vigentes(db, tenant.id)
+ abiertas = alertas_abiertas_por_cliente(db, tenant)
+
+ consulta = select(Cliente).where(Cliente.tenant_id == tenant.id)
+ if filtros.estado_relacion:
+ consulta = consulta.where(Cliente.estado_relacion == filtros.estado_relacion)
+ if filtros.q:
+ consulta = consulta.where(Cliente.id_externo.contains(filtros.q))
+ clientes = db.scalars(consulta.order_by(Cliente.id)).all()
+
+ if filtros.nivel == SIN_EVALUAR:
+ clientes = [c for c in clientes if c.id not in niveles]
+ elif filtros.nivel:
+ clientes = [c for c in clientes if niveles.get(c.id) == filtros.nivel]
+
+ total_tenant = db.scalar(select(func.count(Cliente.id)).where(Cliente.tenant_id == tenant.id))
+ conteos = {
+ "clientes": total_tenant,
+ "filtrados": len(clientes),
+ "por_nivel": {n: sum(1 for v in niveles.values() if v == n) for n in NIVELES},
+ "sin_evaluar": total_tenant - len(niveles),
+ "alertas_abiertas": sum(abiertas.values()),
+ }
+ estados_relacion = sorted(
+ {
+ e
+ for (e,) in db.execute(
+ select(Cliente.estado_relacion).where(Cliente.tenant_id == tenant.id).distinct()
+ )
+ if e
+ }
+ )
+
+ paginas = max(1, -(-len(clientes) // filtros.por_pagina))
+ pagina = min(filtros.pagina, paginas)
+ inicio = (pagina - 1) * filtros.por_pagina
+ visibles = clientes[inicio : inicio + filtros.por_pagina]
+ filas = [
+ {
+ "id": c.id,
+ "id_externo": c.id_externo,
+ "tipo_persona": c.tipo_persona,
+ "estado": c.estado,
+ "perfil_actividad": c.perfil_actividad,
+ "estado_relacion": c.estado_relacion,
+ "nivel": niveles.get(c.id),
+ "alertas_abiertas": abiertas.get(c.id, 0),
+ }
+ for c in visibles
+ ]
+ return render(
+ request,
+ "cartera/lista.html",
+ {
+ "filas": filas,
+ "filtros": filtros,
+ "conteos": conteos,
+ "estados_relacion": estados_relacion,
+ "niveles": NIVELES,
+ "pagina": pagina,
+ "paginas": paginas,
+ "por_pagina": filtros.por_pagina,
+ },
+ )
diff --git a/app/routers/clientes.py b/app/routers/clientes.py
new file mode 100644
index 0000000..44cf805
--- /dev/null
+++ b/app/routers/clientes.py
@@ -0,0 +1,156 @@
+"""Router `clientes`: ficha mínima de lectura del cliente y alta de alertas manuales (Fase 3).
+
+El expediente completo (documentos, declaración, beneficiario controlador) es Fase 4 y tiene su
+espacio marcado en la plantilla. El nivel vigente sale de `services.riesgo.nivel_vigente` cuando
+la Pieza C lo publique; mientras, de la última `evaluacion_riesgo` (lectura).
+"""
+
+from __future__ import annotations
+
+from typing import Annotated
+
+from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
+from pydantic import ValidationError
+from sqlalchemy import select
+from sqlalchemy.orm import Session
+from starlette.responses import HTMLResponse, RedirectResponse, Response
+
+from app.auth import requiere_rol
+from app.db import get_db
+from app.engine.rules_catalog import MANUALES
+from app.models import (
+ Alerta,
+ Cliente,
+ Coincidencia,
+ Credito,
+ Pep,
+ ReglaAlerta,
+ Transaccion,
+ Usuario,
+)
+from app.models.usuario import Rol
+from app.routers import render
+from app.routers.cartera import niveles_vigentes
+from app.schemas.alertas import AlertaManualEntrada
+from app.services import riesgo as servicio_riesgo
+from app.services.alertas import (
+ ReglaNoEncontradaError,
+ ReglaNoManualError,
+ levantar_manual,
+ reglas_vigentes,
+ tenant_de_sesion,
+)
+
+router = APIRouter(tags=["clientes"])
+TRANSACCIONES_RECIENTES = 5
+ROLES_ALERTA_MANUAL = (Rol.ANALISTA, Rol.OFICIAL)
+
+
+def nivel_vigente(session: Session, tenant_id: int, cliente_id: int) -> str | None:
+ """Contrato con la Pieza C si existe; si no, la última `evaluacion_riesgo`."""
+ funcion = getattr(servicio_riesgo, "nivel_vigente", None)
+ if callable(funcion):
+ return funcion(session, cliente_id)
+ return niveles_vigentes(session, tenant_id).get(cliente_id)
+
+
+def _cliente(db: Session, tenant_id: int, cliente_id: int) -> Cliente:
+ cliente = db.get(Cliente, cliente_id)
+ if cliente is None or cliente.tenant_id != tenant_id:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, "Cliente no encontrado.")
+ return cliente
+
+
+def _ficha(
+ request: Request, db: Session, cliente_id: int, *, status_code: int = 200, **extra
+) -> HTMLResponse:
+ tenant = tenant_de_sesion(db)
+ cliente = _cliente(db, tenant.id, cliente_id)
+ peps = db.scalars(
+ select(Pep).where(Pep.persona_id == cliente.id, Pep.valid_to.is_(None)).order_by(Pep.id)
+ ).all()
+ coincidencias = db.scalars(
+ select(Coincidencia).where(Coincidencia.persona_id == cliente.id).order_by(Coincidencia.id)
+ ).all()
+ creditos = db.scalars(
+ select(Credito)
+ .where(Credito.cliente_id == cliente.id)
+ .order_by(Credito.fecha_disposicion.desc())
+ ).all()
+ recientes = {
+ cr.id: db.scalars(
+ select(Transaccion)
+ .where(Transaccion.credito_id == cr.id)
+ .order_by(Transaccion.fecha_pago.desc(), Transaccion.id.desc())
+ .limit(TRANSACCIONES_RECIENTES)
+ ).all()
+ for cr in creditos
+ }
+ alertas = db.execute(
+ select(Alerta, ReglaAlerta)
+ .join(ReglaAlerta, ReglaAlerta.id == Alerta.regla_id)
+ .where(Alerta.cliente_id == cliente.id)
+ .order_by(Alerta.id.desc())
+ ).all()
+ reglas_manuales = [
+ r
+ for r in reglas_vigentes(db, tenant)
+ if r.clave in MANUALES and r.tipo_evaluacion == "manual"
+ ]
+ usuario = request.state.usuario
+ return render(
+ request,
+ "clientes/ficha.html",
+ {
+ "cliente": cliente,
+ "nivel": nivel_vigente(db, tenant.id, cliente.id),
+ "peps": peps,
+ "coincidencias": coincidencias,
+ "creditos": creditos,
+ "recientes": recientes,
+ "alertas": alertas,
+ "reglas_manuales": sorted(reglas_manuales, key=lambda r: r.clave),
+ "puede_levantar": usuario.rol in ROLES_ALERTA_MANUAL,
+ **extra,
+ },
+ status_code=status_code,
+ )
+
+
+@router.get("/clientes/{cliente_id}", include_in_schema=False)
+def ficha(
+ request: Request, cliente_id: int, db: Annotated[Session, Depends(get_db)]
+) -> HTMLResponse:
+ return _ficha(request, db, cliente_id, aviso=request.query_params.get("aviso"))
+
+
+@router.post("/clientes/{cliente_id}/alertas-manuales", include_in_schema=False)
+def alerta_manual(
+ request: Request,
+ cliente_id: int,
+ db: Annotated[Session, Depends(get_db)],
+ usuario: Annotated[Usuario, Depends(requiere_rol(*ROLES_ALERTA_MANUAL))],
+ regla_clave: Annotated[str, Form()] = "",
+ descripcion: Annotated[str, Form()] = "",
+) -> Response:
+ tenant = tenant_de_sesion(db)
+ _cliente(db, tenant.id, cliente_id)
+ try:
+ entrada = AlertaManualEntrada(regla_clave=regla_clave, descripcion=descripcion)
+ alerta = levantar_manual(
+ db, entrada.regla_clave, cliente_id, entrada.descripcion, usuario.usuario
+ )
+ except (ValidationError, ReglaNoEncontradaError, ReglaNoManualError) as exc:
+ db.rollback()
+ if isinstance(exc, ValidationError):
+ mensaje = (
+ "Elige una regla manual (B-05, B-07 o E-03) y describe el hecho "
+ "en al menos 10 caracteres."
+ )
+ else:
+ mensaje = f"No se puede levantar: {exc}"
+ return _ficha(request, db, cliente_id, error=mensaje, status_code=400)
+ db.commit()
+ return RedirectResponse(
+ f"/clientes/{cliente_id}?aviso=alerta-{alerta.id}", status_code=status.HTTP_303_SEE_OTHER
+ )
diff --git a/app/templates/cartera/lista.html b/app/templates/cartera/lista.html
new file mode 100644
index 0000000..5a90b0e
--- /dev/null
+++ b/app/templates/cartera/lista.html
@@ -0,0 +1,74 @@
+{% extends "base.html" %}
+{% from "_componentes/tarjeta.html" import tarjeta %}
+{% from "_componentes/badges.html" import badge, badge_nivel %}
+{% from "_componentes/tabla.html" import tabla %}
+
+{% block titulo %}Cartera{% endblock %}
+
+{% block contenido %}
+ {{ conteos.clientes }} clientes · {{ conteos.alertas_abiertas }} alertas abiertasCartera
+
{{ fila.id_externo }}
+ {% elif col.clave == "nivel" %}{% if fila.nivel %}{{ badge_nivel(fila.nivel) }}{% else %}{{ badge("Sin evaluar") }}{% endif %}
+ {% elif col.clave == "tipo_persona" %}{{ "Física" if fila.tipo_persona == "fisica" else "Moral" }}
+ {% else %}{{ "—" if fila[col.clave] is none else fila[col.clave] }}{% endif %}
+{% endcall %}
+{% if paginas > 1 %}
+
+{% endif %}
+{% endcall %}
+{% endblock %}
diff --git a/app/templates/clientes/ficha.html b/app/templates/clientes/ficha.html
new file mode 100644
index 0000000..da51f4e
--- /dev/null
+++ b/app/templates/clientes/ficha.html
@@ -0,0 +1,98 @@
+{% extends "base.html" %}
+{% from "_componentes/tarjeta.html" import tarjeta %}
+{% from "_componentes/badges.html" import badge, badge_nivel, badge_estado_alerta, badge_nivel_alerta %}
+{% from "_componentes/tabla.html" import tabla %}
+{% from "_componentes/aviso.html" import aviso as aviso_en_linea %}
+
+{% block titulo %}Cliente {{ cliente.id_externo }}{% endblock %}
+
+{% block contenido %}
+{{ cliente.id_externo }}+ {{ "Persona física" if cliente.tipo_persona == "fisica" else "Persona moral" }} + · Riesgo vigente: {% if nivel %}{{ badge_nivel(nivel) }}{% else %}{{ badge("Sin evaluar") }}{% endif %} + · Ver clasificación de riesgo +
+Sin banderas.
{% endif %} +{{ cr.id_externo }} · ${{ "{:,.2f}".format(cr.monto) }} · {{ cr.status }} · {{ cr.fecha_disposicion.strftime("%d/%m/%Y") if cr.fecha_disposicion else "—" }} · {{ cr.tipo_vehiculo or "" }} {{ cr.marca or "" }} {{ cr.anio or "" }}Sin créditos.
+{% endfor %} +{% endcall %} + +{% call tarjeta("Alertas", subtitulo=alertas | length ~ " en total") %} +{% set columnas = [{"clave": "regla", "titulo": "Regla"}, {"clave": "nivel", "titulo": "Nivel"}, {"clave": "estado", "titulo": "Estado"}, {"clave": "vence_el", "titulo": "Vence"}, {"clave": "credito", "titulo": "Crédito"}, {"clave": "responsable", "titulo": "Responsable"}] %} +{% call(fila, col) tabla(columnas, alertas, vacio="Sin alertas.") %} + {% set alerta, regla = fila[0], fila[1] %} + {% if col.clave == "regla" %}{{ regla.clave }} {{ regla.nombre }} · {{ regla.version }} + {% elif col.clave == "nivel" %}{{ badge_nivel_alerta(alerta.nivel) }} + {% elif col.clave == "estado" %}{{ badge_estado_alerta(alerta.estado) }} + {% elif col.clave == "vence_el" %}{{ alerta.vence_el.strftime("%d/%m/%Y") if alerta.vence_el else "—" }} + {% elif col.clave == "credito" %}{{ alerta.credito_id or "—" }} + {% else %}{{ alerta.responsable or "—" }}{% endif %} +{% endcall %} +{% endcall %} + +{% call tarjeta("Levantar alerta manual", subtitulo="B-05, B-07 y E-03: sin fórmula en el esquema; las levanta el analista u oficial") %} +{% if puede_levantar %} + +{% else %} +{{ badge("Solo analista u oficial", "neutro") }} Tu rol ({{ usuario.rol }}) solo consulta.
+{% endif %} +{% endcall %} + +{% call tarjeta("Expediente completo", subtitulo="Fase 4") %} +{{ badge("fase 4") }} Documentos versionados, declaración por cuenta propia o de un tercero y beneficiario controlador se incorporan en la Fase 4 del brief.
+{% endcall %} +{% endblock %} diff --git a/tests/test_auth.py b/tests/test_auth.py index fd4bad7..ca901bf 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -20,7 +20,7 @@ from app.db import crear_engine, crear_session_factory from app.main import crear_app from app.models import AuditTrail, Base, Tenant, Usuario from app.models.usuario import Rol -from app.routers import plantillas +from app.routers import NAVEGACION, plantillas from app.services.tenant import NOMBRE_TENANT_DEMO from seed.usuarios_demo import sembrar @@ -235,7 +235,12 @@ def test_inicio_muestra_tenant_regimen_actividad_y_los_ocho_pasos(cliente: TestC assert "Cartera" in lateral # Lo que aún no existe va deshabilitado y dice en qué fase llega; Inicio ya es enlace. - assert lateral.count('aria-disabled="true"') == 9 + # deshabilitados = pasos sin ruta GET montada (cambia conforme las fases entregan routers) + habilitados = lateral.count('class="nav__enlace"') + lateral.count( + 'class="nav__enlace es-activo"' + ) + assert lateral.count('aria-disabled="true"') == len(NAVEGACION) - habilitados + assert habilitados >= 2 # inicio y cartera, como mínimo assert "fase 4" in lateral assert 'href="/inicio"' in lateral assert 'href="/expediente"' not in lateral diff --git a/tests/test_routers_autoregistro.py b/tests/test_routers_autoregistro.py index bdeff85..9e49764 100644 --- a/tests/test_routers_autoregistro.py +++ b/tests/test_routers_autoregistro.py @@ -83,7 +83,10 @@ def test_un_router_queda_detras_de_sesion_salvo_que_se_declare_publico( def test_montar_routers_ignora_los_modulos_sin_router() -> None: montados = app.routers.montar_routers(FastAPI()) - assert montados == ["auth", "inicio"] + # Los stubs de fases posteriores (sin `router`) no se montan; los módulos con router, sí. + assert montados == sorted(montados) + assert {"auth", "inicio"} <= set(montados) + assert not {"riesgo", "laboratorio", "evidencia", "expediente", "operaciones"} & set(montados) def test_main_no_registra_routers_a_mano() -> None: