475 lines
19 KiB
Python
475 lines
19 KiB
Python
"""Una función por clave de regla, registradas en `REGISTRO` (sección 10 del brief).
|
||
|
||
Cada función recibe `(contexto, parametros)` y devuelve `AlertaCandidata`s con `evidencia`
|
||
explicable: los valores que dispararon la regla y el umbral aplicado. Los parámetros numéricos
|
||
vienen de `regla_alerta.parametros` (seed/reglas_alerta_v2.json); los valores por omisión de aquí
|
||
solo cubren claves ausentes y quedan registrados en la evidencia.
|
||
|
||
Semántica verificada contra las columnas-oráculo del esquema de origen:
|
||
- A-01: `monto ≥ factor_uma × UMA` por crédito.
|
||
- B-08: `monto_credito > factor × ingresos × meses` (el Excel usa el monto, no el costo).
|
||
- B-06: cada transacción con `titular_origen` en `titulares_que_disparan` (CUENTA no dispara).
|
||
- C-03: en el mismo crédito, `cambios_metodo` cambios de método en `pagos_consecutivos` pagos
|
||
(el enganche cuenta como punto de partida del método) o hueco ≥ `hueco_meses` meses calendario
|
||
entre pagos consecutivos. Se devuelve la transacción que dispara y las involucradas.
|
||
- D-04: transacción de `tipos_transaccion` (PAGO; el enganche no cuenta en el Excel)
|
||
`> factor_ingresos × ingresos` de un cliente con PEP vigente de `tipos_pep`.
|
||
- E-02: país de residencia o nacionalidad en los catálogos `catalogos` (GAFI y paraísos, OR).
|
||
|
||
Reglas con agregados y riesgo (consumen `agregado_cliente`, `evaluacion_riesgo` y
|
||
`perfil_transaccional`, que escribe la Pieza C y aquí solo se leen; sin ellos la regla no dispara
|
||
y devuelve `SinDatos`):
|
||
- A-02: `acumulado_creditos_ventana > factor_uma × UMA` (sin los créditos ya incluidos en un aviso
|
||
acusado: la acumulación se reinicia tras presentar el aviso); se marca cada crédito dispuesto en
|
||
la ventana `(corte − ventana, corte]` del tenant.
|
||
- B-02: `capacidad_pago > capacidad_pago_max` (suma de cuotas / ingresos).
|
||
- B-03: `num_creditos_total > n AND monto_promedio < umbral AND suma_acumulada ≥ umbral`.
|
||
- C-01: `pagos_ultimo_mes > factor × mensualidad_esperada` (perfil transaccional vigente).
|
||
- C-02: `num_creditos_ventana > n`.
|
||
- D-01: `nivel_vigente == "alto"` (última evaluación de riesgo).
|
||
Manuales: B-05, B-07, E-03.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
from collections.abc import Callable, Iterator
|
||
from decimal import Decimal
|
||
from typing import Any
|
||
|
||
from app.engine.rules import AlertaCandidata, ClienteCtx, Contexto, SinDatos, TransaccionCtx
|
||
|
||
Regla = Callable[[Contexto, dict[str, Any]], Iterator[AlertaCandidata | SinDatos]]
|
||
|
||
REGISTRO: dict[str, Regla] = {}
|
||
PENDIENTES_AGREGADOS: frozenset[str] = frozenset() # todas las evaluables están implementadas
|
||
CON_AGREGADOS: frozenset[str] = frozenset({"A-02", "B-02", "B-03", "C-01", "C-02", "D-01"})
|
||
MANUALES: frozenset[str] = frozenset({"B-05", "B-07", "E-03"})
|
||
NOMBRES_CATALOGO = {
|
||
"gafi": "paises_gafi",
|
||
"paises_gafi": "paises_gafi",
|
||
"paraisos_fiscales": "paraisos_fiscales",
|
||
}
|
||
|
||
|
||
def regla(clave: str) -> Callable[[Regla], Regla]:
|
||
def registrar(funcion: Regla) -> Regla:
|
||
REGISTRO[clave] = funcion
|
||
return funcion
|
||
|
||
return registrar
|
||
|
||
|
||
def _dec(valor: Any, por_defecto: str) -> Decimal:
|
||
return Decimal(str(valor if valor is not None else por_defecto))
|
||
|
||
|
||
def _factor_uma(p: dict[str, Any]) -> Decimal | None:
|
||
"""El factor del umbral en UMA sale solo de la configuración de la regla: sin él, la regla no
|
||
dispara (no hay un umbral por omisión en el código)."""
|
||
valor = p.get("factor_uma")
|
||
return Decimal(str(valor)) if valor is not None else None
|
||
|
||
|
||
def _ventana(ctx: Contexto) -> str:
|
||
"""La ventana del tenant como se lee en el detalle de la alerta (la de A-02 y C-02)."""
|
||
return (
|
||
f"{ctx.ventana_meses} meses: ({ctx.inicio_ventana():%d/%m/%Y}, {ctx.fecha_corte:%d/%m/%Y}]"
|
||
)
|
||
|
||
|
||
def _sin_factor_uma(ctx: Contexto) -> Iterator[SinDatos]:
|
||
for cliente_id in ctx.clientes:
|
||
yield SinDatos(cliente_id, "sin parámetro factor_uma")
|
||
|
||
|
||
def _pep_vigente(cliente: ClienteCtx, tipos: set[str]) -> frozenset[str]:
|
||
return frozenset(cliente.pep_tipos & tipos)
|
||
|
||
|
||
# --- Familia A ------------------------------------------------------------------------------
|
||
|
||
|
||
@regla("A-01")
|
||
def a01_umbral_credito(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
if (factor := _factor_uma(p)) is None:
|
||
yield from _sin_factor_uma(ctx)
|
||
return
|
||
umbral = factor * ctx.uma
|
||
for credito in ctx.creditos.values():
|
||
if credito.monto >= umbral:
|
||
yield AlertaCandidata(
|
||
cliente_id=credito.cliente_id,
|
||
credito_id=credito.id,
|
||
evidencia={
|
||
"monto": credito.monto,
|
||
"umbral": umbral,
|
||
"uma": ctx.uma,
|
||
"factor_uma": factor,
|
||
"credito": credito.id_externo,
|
||
},
|
||
fecha_evento=credito.fecha_disposicion,
|
||
)
|
||
|
||
|
||
@regla("A-02")
|
||
def a02_acumulacion_en_ventana(
|
||
ctx: Contexto, p: dict[str, Any]
|
||
) -> Iterator[AlertaCandidata | SinDatos]:
|
||
if (factor := _factor_uma(p)) is None:
|
||
yield from _sin_factor_uma(ctx)
|
||
return
|
||
umbral = factor * ctx.uma
|
||
creditos_por_cliente: dict[int, list] = {}
|
||
for credito in ctx.creditos.values():
|
||
creditos_por_cliente.setdefault(credito.cliente_id, []).append(credito)
|
||
for cliente in ctx.clientes.values():
|
||
agg = cliente.agregado
|
||
if agg is None or agg.acumulado_creditos_ventana is None:
|
||
yield SinDatos(cliente.id, "sin agregado")
|
||
continue
|
||
en_ventana = [
|
||
c
|
||
for c in creditos_por_cliente.get(cliente.id, [])
|
||
if ctx.en_ventana(c.fecha_disposicion)
|
||
]
|
||
# La acumulación se reinicia después de presentar el aviso: los créditos ya reportados
|
||
# salen de la suma y no se vuelven a marcar. Sin reportados, el acumulado es el agregado.
|
||
reportados = [c for c in en_ventana if c.id in ctx.reportados]
|
||
if reportados:
|
||
en_ventana = [c for c in en_ventana if c.id not in ctx.reportados]
|
||
acumulado = sum((c.monto for c in en_ventana), Decimal(0))
|
||
else:
|
||
acumulado = agg.acumulado_creditos_ventana
|
||
if acumulado <= umbral:
|
||
continue
|
||
for credito in en_ventana:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
credito_id=credito.id,
|
||
evidencia={
|
||
"acumulado_creditos_ventana": acumulado,
|
||
"umbral": umbral,
|
||
"uma": ctx.uma,
|
||
"factor_uma": factor,
|
||
"ventana": _ventana(ctx),
|
||
"creditos_en_ventana": [c.id_externo for c in en_ventana],
|
||
"creditos_ya_reportados": [c.id_externo for c in reportados],
|
||
"credito": credito.id_externo,
|
||
"monto": credito.monto,
|
||
},
|
||
fecha_evento=credito.fecha_disposicion,
|
||
)
|
||
|
||
|
||
# --- Familia B ------------------------------------------------------------------------------
|
||
|
||
|
||
@regla("B-01")
|
||
def b01_sin_comprobante(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
for cliente in ctx.clientes.values():
|
||
if cliente.comprobante_ingresos is False:
|
||
yield AlertaCandidata(cliente_id=cliente.id, evidencia={"comprobante_ingresos": False})
|
||
|
||
|
||
@regla("B-02")
|
||
def b02_capacidad_de_pago(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
maximo = _dec(p.get("capacidad_pago_max"), "0.4")
|
||
for cliente in ctx.clientes.values():
|
||
agg = cliente.agregado
|
||
if agg is None:
|
||
yield SinDatos(cliente.id, "sin agregado")
|
||
continue
|
||
if agg.capacidad_pago is None:
|
||
yield SinDatos(cliente.id, "sin ingresos para calcular la capacidad de pago")
|
||
continue
|
||
if agg.capacidad_pago > maximo:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={
|
||
"capacidad_pago": agg.capacidad_pago,
|
||
"capacidad_pago_max": maximo,
|
||
"suma_cuotas": agg.suma_cuotas,
|
||
"ingresos_mensuales_netos": cliente.ingresos_mensuales_netos,
|
||
},
|
||
)
|
||
|
||
|
||
@regla("B-03")
|
||
def b03_estructuracion(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
n = int(p.get("num_creditos_mayor_que", 3))
|
||
if (factor := _factor_uma(p)) is None:
|
||
yield from _sin_factor_uma(ctx)
|
||
return
|
||
umbral = factor * ctx.uma
|
||
for cliente in ctx.clientes.values():
|
||
agg = cliente.agregado
|
||
if agg is None or agg.num_creditos_total is None:
|
||
yield SinDatos(cliente.id, "sin agregado")
|
||
continue
|
||
if (
|
||
agg.num_creditos_total > n
|
||
and (agg.monto_promedio or Decimal(0)) < umbral
|
||
and (agg.suma_acumulada or Decimal(0)) >= umbral
|
||
):
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={
|
||
"num_creditos_total": agg.num_creditos_total,
|
||
"num_creditos_mayor_que": n,
|
||
"monto_promedio": agg.monto_promedio,
|
||
"suma_acumulada": agg.suma_acumulada,
|
||
"umbral": umbral,
|
||
"uma": ctx.uma,
|
||
"factor_uma": factor,
|
||
},
|
||
)
|
||
|
||
|
||
@regla("B-04")
|
||
def b04_inconsistencia_documental(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
for cliente in ctx.clientes.values():
|
||
if cliente.inconsistencia_documentos is True:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id, evidencia={"inconsistencia_documentos": True}
|
||
)
|
||
|
||
|
||
@regla("B-06")
|
||
def b06_terceros(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
titulares = {str(t).upper() for t in p.get("titulares_que_disparan", ["TERCERO"])}
|
||
for t in ctx.transacciones:
|
||
if t.titular_origen and t.titular_origen.upper() in titulares:
|
||
yield AlertaCandidata(
|
||
cliente_id=t.cliente_id,
|
||
credito_id=t.credito_id,
|
||
transaccion_ids=(t.id,),
|
||
evidencia={
|
||
"transaccion_id": t.id,
|
||
"titular_origen": t.titular_origen,
|
||
"titulares_que_disparan": sorted(titulares),
|
||
"fecha_pago": t.fecha_pago,
|
||
"total": t.total,
|
||
"tipo": t.tipo,
|
||
},
|
||
fecha_evento=t.fecha_pago,
|
||
)
|
||
|
||
|
||
@regla("B-08")
|
||
def b08_vehiculo_vs_ingresos(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
factor = _dec(p.get("factor_ingreso_anual"), "1.5")
|
||
meses = _dec(p.get("meses_anualizacion"), "12")
|
||
for credito in ctx.creditos.values():
|
||
cliente = ctx.clientes.get(credito.cliente_id)
|
||
if cliente is None or cliente.ingresos_mensuales_netos is None:
|
||
continue
|
||
umbral = factor * cliente.ingresos_mensuales_netos * meses
|
||
if credito.monto > umbral:
|
||
yield AlertaCandidata(
|
||
cliente_id=credito.cliente_id,
|
||
credito_id=credito.id,
|
||
evidencia={
|
||
"monto": credito.monto,
|
||
"ingresos_mensuales_netos": cliente.ingresos_mensuales_netos,
|
||
"factor_ingreso_anual": factor,
|
||
"meses_anualizacion": meses,
|
||
"umbral": umbral,
|
||
"credito": credito.id_externo,
|
||
},
|
||
fecha_evento=credito.fecha_disposicion,
|
||
)
|
||
|
||
|
||
# --- Familia C ------------------------------------------------------------------------------
|
||
|
||
|
||
@regla("C-01")
|
||
def c01_excede_perfil(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
factor = _dec(p.get("factor"), "1.0")
|
||
for cliente in ctx.clientes.values():
|
||
agg = cliente.agregado
|
||
if agg is None or agg.pagos_ultimo_mes is None:
|
||
yield SinDatos(cliente.id, "sin agregado")
|
||
continue
|
||
if cliente.mensualidad_esperada is None:
|
||
yield SinDatos(cliente.id, "sin perfil transaccional")
|
||
continue
|
||
umbral = factor * cliente.mensualidad_esperada
|
||
if agg.pagos_ultimo_mes > umbral:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={
|
||
"pagos_ultimo_mes": agg.pagos_ultimo_mes,
|
||
"mensualidad_esperada": cliente.mensualidad_esperada,
|
||
"factor": factor,
|
||
"umbral": umbral,
|
||
"mes": f"{agg.fecha_corte:%Y-%m}",
|
||
},
|
||
)
|
||
|
||
|
||
@regla("C-02")
|
||
def c02_frecuencia(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
n = int(p.get("num_creditos_ventana_mayor_que", 1))
|
||
for cliente in ctx.clientes.values():
|
||
agg = cliente.agregado
|
||
if agg is None or agg.num_creditos_ventana is None:
|
||
yield SinDatos(cliente.id, "sin agregado")
|
||
continue
|
||
if agg.num_creditos_ventana > n:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={
|
||
"num_creditos_ventana": agg.num_creditos_ventana,
|
||
"num_creditos_ventana_mayor_que": n,
|
||
"ventana": _ventana(ctx),
|
||
},
|
||
)
|
||
|
||
|
||
def _meses_entre(a, b) -> int:
|
||
return (b.year - a.year) * 12 + (b.month - a.month)
|
||
|
||
|
||
@regla("C-03")
|
||
def c03_patron_de_pagos(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
n_cambios = int(p.get("cambios_metodo", 3))
|
||
n_pagos = int(p.get("pagos_consecutivos", 3))
|
||
hueco = int(p.get("hueco_meses", 3))
|
||
for credito_id, pagos in ctx.transacciones_por_credito().items():
|
||
previa: TransaccionCtx | None = None
|
||
ventana: list[tuple[TransaccionCtx, bool]] = [] # (pago, cambió de método)
|
||
for t in pagos:
|
||
if previa is None or t.tipo.upper() == "ENGANCHE":
|
||
previa = t
|
||
ventana = []
|
||
continue
|
||
cambio = (t.metodo or "").upper() != (previa.metodo or "").upper()
|
||
ventana = (ventana + [(t, cambio)])[-n_pagos:]
|
||
cambios = sum(1 for _, c in ventana if c)
|
||
meses = _meses_entre(previa.fecha_pago, t.fecha_pago)
|
||
if cambios >= n_cambios or meses >= hueco:
|
||
involucradas = [x for x, _ in ventana] if cambios >= n_cambios else [previa, t]
|
||
yield AlertaCandidata(
|
||
cliente_id=t.cliente_id,
|
||
credito_id=credito_id,
|
||
transaccion_ids=tuple(sorted({x.id for x in involucradas} | {t.id})),
|
||
evidencia={
|
||
"transaccion_id": t.id,
|
||
"motivo": "cambios_metodo" if cambios >= n_cambios else "hueco",
|
||
"cambios_en_ventana": cambios,
|
||
"cambios_metodo": n_cambios,
|
||
"pagos_consecutivos": n_pagos,
|
||
"meses_desde_pago_anterior": meses,
|
||
"hueco_meses": hueco,
|
||
"metodos": [(x.metodo or "") for x, _ in ventana],
|
||
"fecha_pago": t.fecha_pago,
|
||
"fecha_pago_anterior": previa.fecha_pago,
|
||
},
|
||
fecha_evento=t.fecha_pago,
|
||
)
|
||
previa = t
|
||
|
||
|
||
# --- Familia D ------------------------------------------------------------------------------
|
||
|
||
|
||
@regla("D-01")
|
||
def d01_riesgo_alto(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata | SinDatos]:
|
||
nivel = str(p.get("nivel", "alto")).lower()
|
||
for cliente in ctx.clientes.values():
|
||
if cliente.nivel_vigente is None:
|
||
yield SinDatos(cliente.id, "sin evaluación de riesgo")
|
||
continue
|
||
if cliente.nivel_vigente.lower() == nivel:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={"nivel_vigente": cliente.nivel_vigente, "nivel": nivel},
|
||
)
|
||
|
||
|
||
def _regla_pep(clave: str, tipo: str, etiqueta: str) -> None:
|
||
@regla(clave)
|
||
def _pep(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
for cliente in ctx.clientes.values():
|
||
if tipo in cliente.pep_tipos:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id, evidencia={"pep": tipo, "condicion": etiqueta}
|
||
)
|
||
|
||
_pep.__name__ = f"{clave.lower().replace('-', '')}_pep_{tipo}"
|
||
|
||
|
||
_regla_pep("D-02", "nacional", "PEP nacional vigente")
|
||
_regla_pep("D-03", "extranjera", "PEP extranjera vigente")
|
||
_regla_pep("D-05", "asimilado", "Familiar directo o asociado cercano de PEP")
|
||
|
||
|
||
@regla("D-04")
|
||
def d04_pep_excede_perfil(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
factor = _dec(p.get("factor_ingresos"), "1.0")
|
||
tipos_pep = {str(t) for t in p.get("tipos_pep", ["nacional", "extranjera"])}
|
||
if "tipos_transaccion" not in p:
|
||
raise ValueError('D-04 exige el parámetro tipos_transaccion (p. ej. ["PAGO"])')
|
||
tipos_tx = {str(t).upper() for t in p["tipos_transaccion"]}
|
||
for t in ctx.transacciones:
|
||
if t.tipo.upper() not in tipos_tx:
|
||
continue
|
||
cliente = ctx.clientes.get(t.cliente_id)
|
||
if cliente is None or cliente.ingresos_mensuales_netos is None:
|
||
continue
|
||
vigentes = _pep_vigente(cliente, tipos_pep)
|
||
if not vigentes:
|
||
continue
|
||
umbral = factor * cliente.ingresos_mensuales_netos
|
||
if t.total > umbral:
|
||
yield AlertaCandidata(
|
||
cliente_id=t.cliente_id,
|
||
credito_id=t.credito_id,
|
||
transaccion_ids=(t.id,),
|
||
evidencia={
|
||
"transaccion_id": t.id,
|
||
"total": t.total,
|
||
"ingresos_mensuales_netos": cliente.ingresos_mensuales_netos,
|
||
"factor_ingresos": factor,
|
||
"umbral": umbral,
|
||
"pep": sorted(vigentes),
|
||
"tipos_transaccion": sorted(tipos_tx),
|
||
"fecha_pago": t.fecha_pago,
|
||
},
|
||
fecha_evento=t.fecha_pago,
|
||
)
|
||
|
||
|
||
# --- Familia E ------------------------------------------------------------------------------
|
||
|
||
|
||
@regla("E-01")
|
||
def e01_coincidencia_confirmada(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
for cliente in ctx.clientes.values():
|
||
if cliente.coincidencia_confirmada:
|
||
yield AlertaCandidata(cliente_id=cliente.id, evidencia={"coincidencia": "confirmada"})
|
||
|
||
|
||
@regla("E-02")
|
||
def e02_jurisdiccion_riesgo(ctx: Contexto, p: dict[str, Any]) -> Iterator[AlertaCandidata]:
|
||
nombres = [
|
||
NOMBRES_CATALOGO.get(str(c), str(c))
|
||
for c in p.get("catalogos", ["gafi", "paraisos_fiscales"])
|
||
]
|
||
paises: dict[str, frozenset[str]] = {
|
||
n: frozenset(x.casefold() for x in ctx.catalogos.get(n, frozenset())) for n in nombres
|
||
}
|
||
for cliente in ctx.clientes.values():
|
||
for campo in ("pais", "nacionalidad"):
|
||
valor = getattr(cliente, campo)
|
||
if not valor:
|
||
continue
|
||
en = [n for n, lista in paises.items() if valor.casefold() in lista]
|
||
if en:
|
||
yield AlertaCandidata(
|
||
cliente_id=cliente.id,
|
||
evidencia={"campo": campo, "valor": valor, "catalogos": en},
|
||
)
|
||
break
|