711 lines
26 KiB
Python
711 lines
26 KiB
Python
"""Carga de listas públicas (OFAC SDN, ONU, 69-B, PEP) desde `seed/listas/` o `DATA_DIR`,
|
|
versionadas por fecha. Fase 4, PR 2.
|
|
|
|
Un lector por formato normaliza a `Entrada` (`app.engine.screening`): nombre, alias, tipo de
|
|
persona, fecha de nacimiento y país si existen, identificador en la lista y datos adicionales.
|
|
|
|
- **OFAC SDN** (`sdn.csv` + `alt.csv` del Tesoro de EE. UU.): CSV sin encabezado, `-0-` como
|
|
nulo; 12 columnas en SDN (`ent_num, name, type, program, title, call_sign, vess_type, tonnage,
|
|
grt, vess_flag, vess_owner, remarks`) y 5 en ALT (`ent_num, alt_num, alt_type, alt_name,
|
|
remarks`). La fecha de nacimiento se lee de `DOB dd Mon yyyy` en `remarks`.
|
|
- **ONU** (XML consolidado del Consejo de Seguridad): `INDIVIDUALS/INDIVIDUAL` y
|
|
`ENTITIES/ENTITY` con alias, fechas de nacimiento y nacionalidades.
|
|
- **SAT 69-B** (listado completo, CSV latin-1 con dos líneas de preámbulo): solo contribuyentes
|
|
con situación **Definitivo**. Identificador: RFC.
|
|
- **PEP** (`pep_ejemplo_*.csv`, lista de ejemplo generada con Faker): `id, nombre, tipo, cargo,
|
|
pais, desde, fecha_nacimiento, alias`.
|
|
- **Lista de Personas Bloqueadas** de la Unidad de Inteligencia Financiera (`uif_lpb`): no es
|
|
pública; la autoridad la entrega a cada sujeto obligado y **nunca va en el repositorio ni en
|
|
`seed/`**. El oficial de cumplimiento la carga desde `/screening/listas` en un CSV con encabezado
|
|
(`COLUMNAS_LPB`: solo `nombre` es obligatoria); el archivo queda en `DATA_DIR/listas/<empresa>/`,
|
|
sin ruta de descarga, y la pantalla no lista sus entradas.
|
|
|
|
`importar_lista` crea una fila en `lista` (nombre, fuente, fecha de versión, ruta, umbral por
|
|
omisión, número de entradas y SHA-256) y un `lote_carga` de tipo `lista`. Una versión nueva no
|
|
borra la anterior: es otra fila con el mismo `nombre`; la vigente es la de `fecha_version` mayor.
|
|
Las entradas no se guardan en la base: se leen del archivo al consultar (cache en memoria).
|
|
|
|
uv run python -m app.importers.lists --todas # primeras versiones de seed/listas/
|
|
uv run python -m app.importers.lists --lista ofac_sdn \
|
|
--archivo /data/listas/ofac_sdn_2026-11-01.csv
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import csv
|
|
import hashlib
|
|
import io
|
|
import logging
|
|
import re
|
|
import xml.etree.ElementTree as ET
|
|
from collections.abc import Callable, Iterable, Iterator
|
|
from dataclasses import dataclass
|
|
from datetime import date, datetime
|
|
from decimal import Decimal
|
|
from pathlib import Path
|
|
|
|
from sqlalchemy import select
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app import audit
|
|
from app.config import get_settings
|
|
from app.engine.screening import Entrada
|
|
from app.models import Lista, LoteCarga
|
|
from app.services.alertas import autor_de_sesion, tenant_de_sesion
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
RAIZ_REPO = Path(__file__).resolve().parents[2]
|
|
DIR_LISTAS_SEED = RAIZ_REPO / "seed" / "listas"
|
|
NULO_OFAC = "-0-"
|
|
SITUACION_DEFINITIVO = "Definitivo"
|
|
_RE_DOB = re.compile(r"DOB\s+(\d{1,2})\s+([A-Za-z]{3})\s+(\d{4})")
|
|
_MESES = {
|
|
m: i
|
|
for i, m in enumerate(
|
|
("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), 1
|
|
)
|
|
}
|
|
_RE_FECHA_ARCHIVO = re.compile(r"(\d{4}-\d{2}-\d{2})")
|
|
|
|
|
|
class ListaDesconocidaError(ValueError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DefinicionLista:
|
|
nombre: str # clave en `lista.nombre`
|
|
titulo: str
|
|
fuente: str
|
|
umbral_por_defecto: Decimal
|
|
lector: Callable[[Path], list[Entrada]]
|
|
patron_archivo: str # glob dentro de seed/listas/
|
|
nota: str = ""
|
|
# No es pública: solo la carga el oficial desde la pantalla y nunca va en `seed/`.
|
|
protegida: bool = False
|
|
|
|
@property
|
|
def extension(self) -> str:
|
|
return Path(self.patron_archivo).suffix
|
|
|
|
|
|
# Qué es el `pais` de una entrada, según la lista y el tipo de persona: la ONU da la nacionalidad
|
|
# de las personas y el país del domicilio de las entidades; el 69-B, el domicilio fiscal; la lista
|
|
# PEP, el país del cargo. El oficial no debe cotejar un domicilio contra una nacionalidad.
|
|
NACIONALIDAD = "Nacionalidad"
|
|
PAIS_DOMICILIO = "País (domicilio)"
|
|
PAIS_CARGO = "País (cargo)"
|
|
PAIS = "País"
|
|
|
|
|
|
def etiqueta_pais(lista: str | None, tipo_persona: str | None) -> str:
|
|
"""Cómo se rotula el `pais` de una entrada de `lista` (clave en `lista.nombre`)."""
|
|
if lista == "onu":
|
|
return NACIONALIDAD if tipo_persona == "fisica" else PAIS_DOMICILIO
|
|
if lista == "sat_69b":
|
|
return PAIS_DOMICILIO
|
|
if lista == "pep":
|
|
return PAIS_CARGO
|
|
return PAIS
|
|
|
|
|
|
# --- Lectores ---------------------------------------------------------------------------------
|
|
|
|
|
|
def _nulo(valor: str) -> str | None:
|
|
valor = (valor or "").strip()
|
|
return None if not valor or valor == NULO_OFAC else valor
|
|
|
|
|
|
def _fecha_dob(remarks: str | None) -> date | None:
|
|
if not remarks:
|
|
return None
|
|
m = _RE_DOB.search(remarks)
|
|
if not m:
|
|
return None
|
|
dia, mes, anio = m.groups()
|
|
try:
|
|
return date(int(anio), _MESES[mes.title()], int(dia))
|
|
except (KeyError, ValueError):
|
|
return None
|
|
|
|
|
|
def _tipo_persona_ofac(tipo: str | None) -> str | None:
|
|
if tipo is None:
|
|
return "moral" # entidades: OFAC deja el tipo vacío
|
|
tipo = tipo.lower()
|
|
if tipo == "individual":
|
|
return "fisica"
|
|
if tipo == "entity":
|
|
return "moral"
|
|
return None # vessel, aircraft
|
|
|
|
|
|
def ruta_alt_de(ruta_sdn: Path) -> Path | None:
|
|
"""`ofac_sdn_<fecha>.csv` → `ofac_alt_<fecha>.csv` en la misma carpeta, si existe."""
|
|
candidata = ruta_sdn.with_name(ruta_sdn.name.replace("sdn", "alt", 1))
|
|
return candidata if candidata != ruta_sdn and candidata.is_file() else None
|
|
|
|
|
|
def leer_ofac(ruta_sdn: Path, ruta_alt: Path | None = None) -> list[Entrada]:
|
|
alias: dict[str, list[str]] = {}
|
|
ruta_alt = ruta_alt or ruta_alt_de(ruta_sdn)
|
|
if ruta_alt is not None:
|
|
for fila in csv.reader(io.StringIO(ruta_alt.read_text(encoding="latin-1"))):
|
|
if len(fila) < 4:
|
|
continue
|
|
nombre_alias = _nulo(fila[3])
|
|
if nombre_alias:
|
|
alias.setdefault(fila[0].strip(), []).append(nombre_alias)
|
|
entradas = []
|
|
for fila in csv.reader(io.StringIO(ruta_sdn.read_text(encoding="latin-1"))):
|
|
if len(fila) < 12:
|
|
continue
|
|
ent_num = fila[0].strip()
|
|
nombre = _nulo(fila[1])
|
|
if not nombre:
|
|
continue
|
|
remarks = _nulo(fila[11])
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=ent_num,
|
|
nombre=nombre,
|
|
alias=tuple(alias.get(ent_num, ())),
|
|
tipo_persona=_tipo_persona_ofac(_nulo(fila[2])),
|
|
fecha_nacimiento=_fecha_dob(remarks),
|
|
pais=None,
|
|
datos={
|
|
"programa": _nulo(fila[3]),
|
|
"tipo": _nulo(fila[2]) or "entity",
|
|
"titulo": _nulo(fila[4]),
|
|
"observaciones": (remarks or "")[:300] or None,
|
|
},
|
|
)
|
|
)
|
|
return entradas
|
|
|
|
|
|
def _texto(elemento: ET.Element | None, etiqueta: str) -> str | None:
|
|
if elemento is None:
|
|
return None
|
|
valor = elemento.findtext(etiqueta)
|
|
return valor.strip() if valor and valor.strip() else None
|
|
|
|
|
|
def _fecha_onu(individuo: ET.Element) -> date | None:
|
|
for f in individuo.findall("INDIVIDUAL_DATE_OF_BIRTH"):
|
|
fecha = _texto(f, "DATE")
|
|
if fecha:
|
|
try:
|
|
return date.fromisoformat(fecha[:10])
|
|
except ValueError:
|
|
continue
|
|
anio = _texto(f, "YEAR")
|
|
if anio and anio.isdigit():
|
|
return date(int(anio), 1, 1)
|
|
return None
|
|
|
|
|
|
def leer_onu(ruta: Path) -> list[Entrada]:
|
|
raiz = ET.parse(ruta).getroot()
|
|
entradas = []
|
|
for ind in raiz.findall("./INDIVIDUALS/INDIVIDUAL"):
|
|
partes = [
|
|
_texto(ind, etiqueta)
|
|
for etiqueta in ("FIRST_NAME", "SECOND_NAME", "THIRD_NAME", "FOURTH_NAME")
|
|
]
|
|
nombre = " ".join(p for p in partes if p)
|
|
if not nombre:
|
|
continue
|
|
alias = tuple(
|
|
a for a in (_texto(x, "ALIAS_NAME") for x in ind.findall("INDIVIDUAL_ALIAS")) if a
|
|
)
|
|
paises = [p for p in (_texto(x, "VALUE") for x in ind.findall("NATIONALITY")) if p]
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=_texto(ind, "DATAID") or _texto(ind, "REFERENCE_NUMBER") or nombre,
|
|
nombre=nombre,
|
|
alias=alias,
|
|
tipo_persona="fisica",
|
|
fecha_nacimiento=_fecha_onu(ind),
|
|
pais=paises[0] if paises else None,
|
|
datos={
|
|
"programa": _texto(ind, "UN_LIST_TYPE"),
|
|
"referencia": _texto(ind, "REFERENCE_NUMBER"),
|
|
"listado_el": _texto(ind, "LISTED_ON"),
|
|
"observaciones": (_texto(ind, "COMMENTS1") or "")[:300] or None,
|
|
},
|
|
)
|
|
)
|
|
for ent in raiz.findall("./ENTITIES/ENTITY"):
|
|
nombre = _texto(ent, "FIRST_NAME")
|
|
if not nombre:
|
|
continue
|
|
alias = tuple(
|
|
a for a in (_texto(x, "ALIAS_NAME") for x in ent.findall("ENTITY_ALIAS")) if a
|
|
)
|
|
paises = [p for p in (_texto(x, "COUNTRY") for x in ent.findall("ENTITY_ADDRESS")) if p]
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=_texto(ent, "DATAID") or _texto(ent, "REFERENCE_NUMBER") or nombre,
|
|
nombre=nombre,
|
|
alias=alias,
|
|
tipo_persona="moral",
|
|
pais=paises[0] if paises else None,
|
|
datos={
|
|
"programa": _texto(ent, "UN_LIST_TYPE"),
|
|
"referencia": _texto(ent, "REFERENCE_NUMBER"),
|
|
"listado_el": _texto(ent, "LISTED_ON"),
|
|
"observaciones": (_texto(ent, "COMMENTS1") or "")[:300] or None,
|
|
},
|
|
)
|
|
)
|
|
return entradas
|
|
|
|
|
|
def _filas_69b(ruta: Path) -> Iterator[dict[str, str]]:
|
|
lineas = ruta.read_text(encoding="latin-1").splitlines()
|
|
inicio = next(
|
|
(i for i, linea in enumerate(lineas) if "RFC" in linea and "Nombre" in linea), None
|
|
)
|
|
if inicio is None:
|
|
raise ValueError("69-B: no se encontró el encabezado con RFC y Nombre.")
|
|
yield from csv.DictReader(io.StringIO("\n".join(lineas[inicio:])))
|
|
|
|
|
|
def _tipo_persona_rfc(rfc: str) -> str | None:
|
|
rfc = rfc.strip()
|
|
if len(rfc) == 13:
|
|
return "fisica"
|
|
if len(rfc) == 12:
|
|
return "moral"
|
|
return None
|
|
|
|
|
|
def leer_69b(ruta: Path) -> list[Entrada]:
|
|
entradas = []
|
|
for fila in _filas_69b(ruta):
|
|
situacion = (fila.get("Situación del contribuyente") or "").strip()
|
|
if situacion != SITUACION_DEFINITIVO:
|
|
continue
|
|
rfc = (fila.get("RFC") or "").strip()
|
|
nombre = (fila.get("Nombre del Contribuyente") or "").strip()
|
|
if not rfc or not nombre:
|
|
continue
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=rfc,
|
|
nombre=nombre,
|
|
tipo_persona=_tipo_persona_rfc(rfc),
|
|
pais="México",
|
|
datos={
|
|
"situacion": situacion,
|
|
"rfc": rfc,
|
|
"oficio_definitivo": (
|
|
fila.get("Número y fecha de oficio global de definitivos SAT") or ""
|
|
).strip()
|
|
or None,
|
|
"publicacion_dof": (fila.get("Publicación DOF definitivos") or "").strip()
|
|
or None,
|
|
},
|
|
)
|
|
)
|
|
return entradas
|
|
|
|
|
|
def leer_pep(ruta: Path) -> list[Entrada]:
|
|
lineas = [
|
|
linea
|
|
for linea in ruta.read_text(encoding="utf-8").splitlines()
|
|
if not linea.startswith("#")
|
|
]
|
|
entradas = []
|
|
for fila in csv.DictReader(io.StringIO("\n".join(lineas))):
|
|
nombre = (fila.get("nombre") or "").strip()
|
|
if not nombre:
|
|
continue
|
|
fecha = (fila.get("fecha_nacimiento") or "").strip()
|
|
alias = tuple(a.strip() for a in (fila.get("alias") or "").split("|") if a.strip())
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=(fila.get("id") or nombre).strip(),
|
|
nombre=nombre,
|
|
alias=alias,
|
|
tipo_persona="fisica",
|
|
fecha_nacimiento=date.fromisoformat(fecha) if fecha else None,
|
|
pais=(fila.get("pais") or "").strip() or None,
|
|
datos={
|
|
"tipo_pep": (fila.get("tipo") or "").strip() or None,
|
|
"cargo": (fila.get("cargo") or "").strip() or None,
|
|
"desde": (fila.get("desde") or "").strip() or None,
|
|
"lista_de_ejemplo": True,
|
|
},
|
|
)
|
|
)
|
|
return entradas
|
|
|
|
|
|
COLUMNAS_LPB = (
|
|
"nombre",
|
|
"alias",
|
|
"tipo_persona",
|
|
"fecha_nacimiento",
|
|
"rfc",
|
|
"curp",
|
|
"pais",
|
|
"oficio",
|
|
"fecha_oficio",
|
|
)
|
|
|
|
|
|
def _fecha_flexible(texto: str) -> date | None:
|
|
texto = texto.strip()
|
|
if not texto:
|
|
return None
|
|
try:
|
|
if "/" in texto:
|
|
dia, mes, anio = texto[:10].split("/")
|
|
return date(int(anio), int(mes), int(dia))
|
|
return date.fromisoformat(texto[:10])
|
|
except ValueError:
|
|
return None
|
|
|
|
|
|
def leer_lpb(ruta: Path) -> list[Entrada]:
|
|
"""La Lista de Personas Bloqueadas en CSV (UTF-8) con encabezado `COLUMNAS_LPB`.
|
|
|
|
Solo `nombre` es obligatoria. `alias` separa con `|`; las fechas van como AAAA-MM-DD o
|
|
DD/MM/AAAA. El identificador de la entrada es su RFC o su CURP; sin ellos, una huella del
|
|
nombre y la fecha de nacimiento, para que una versión nueva de la lista no repita las
|
|
coincidencias ya dictaminadas."""
|
|
lineas = [
|
|
linea
|
|
for linea in ruta.read_text(encoding="utf-8-sig").splitlines()
|
|
if linea.strip() and not linea.startswith("#")
|
|
]
|
|
lector = csv.DictReader(io.StringIO("\n".join(lineas)))
|
|
if "nombre" not in {(c or "").strip().lower() for c in (lector.fieldnames or [])}:
|
|
return []
|
|
entradas = []
|
|
for bruta in lector:
|
|
fila = {(k or "").strip().lower(): (v or "").strip() for k, v in bruta.items()}
|
|
nombre = fila.get("nombre", "")
|
|
if not nombre:
|
|
continue
|
|
nacimiento = _fecha_flexible(fila.get("fecha_nacimiento", ""))
|
|
rfc, curp = fila.get("rfc", "").upper(), fila.get("curp", "").upper()
|
|
tipo = fila.get("tipo_persona", "").lower()
|
|
huella = hashlib.sha256(
|
|
f"{' '.join(nombre.upper().split())}|{nacimiento or ''}".encode()
|
|
).hexdigest()[:16]
|
|
entradas.append(
|
|
Entrada(
|
|
identificador=rfc or curp or f"lpb-{huella}",
|
|
nombre=nombre,
|
|
alias=tuple(a.strip() for a in fila.get("alias", "").split("|") if a.strip()),
|
|
tipo_persona=tipo if tipo in ("fisica", "moral") else None,
|
|
fecha_nacimiento=nacimiento,
|
|
pais=fila.get("pais") or None,
|
|
datos={
|
|
"rfc": rfc or None,
|
|
"curp": curp or None,
|
|
"oficio": fila.get("oficio") or None,
|
|
"fecha_oficio": fila.get("fecha_oficio") or None,
|
|
"persona_bloqueada": True,
|
|
},
|
|
)
|
|
)
|
|
return entradas
|
|
|
|
|
|
# --- Catálogo de listas -----------------------------------------------------------------------
|
|
|
|
LISTAS: dict[str, DefinicionLista] = {
|
|
"ofac_sdn": DefinicionLista(
|
|
nombre="ofac_sdn",
|
|
titulo="OFAC SDN",
|
|
fuente="Departamento del Tesoro de EE. UU., Specially Designated Nationals (sdn + alt)",
|
|
umbral_por_defecto=Decimal("85"), # 4 falsos positivos (0.4 %) en la cartera de 1,023
|
|
lector=leer_ofac,
|
|
patron_archivo="ofac_sdn_*.csv",
|
|
),
|
|
"onu": DefinicionLista(
|
|
nombre="onu",
|
|
titulo="Consejo de Seguridad de la ONU",
|
|
fuente="Lista consolidada del Consejo de Seguridad de las Naciones Unidas (XML)",
|
|
umbral_por_defecto=Decimal("80"), # nombres transliterados; 0 falsos positivos en cartera
|
|
lector=leer_onu,
|
|
patron_archivo="onu_consolidada_*.xml",
|
|
),
|
|
"sat_69b": DefinicionLista(
|
|
nombre="sat_69b",
|
|
titulo="Artículo 69-B del CFF (SAT)",
|
|
fuente="SAT, listado completo del artículo 69-B; solo situación Definitivo",
|
|
umbral_por_defecto=Decimal("85"), # 0 falsos positivos; 9 con umbral 80
|
|
lector=leer_69b,
|
|
patron_archivo="sat_69b_*.csv",
|
|
),
|
|
"pep": DefinicionLista(
|
|
nombre="pep",
|
|
titulo="PEP (lista de ejemplo)",
|
|
fuente="Lista de ejemplo generada con Faker; no es una fuente oficial",
|
|
umbral_por_defecto=Decimal("80"), # 1 falso positivo en cartera; revisión manual barata
|
|
lector=leer_pep,
|
|
patron_archivo="pep_ejemplo_*.csv",
|
|
nota="lista de ejemplo",
|
|
),
|
|
"uif_lpb": DefinicionLista(
|
|
nombre="uif_lpb",
|
|
titulo="Lista de Personas Bloqueadas (UIF)",
|
|
fuente="Unidad de Inteligencia Financiera, Lista de Personas Bloqueadas; la entrega la "
|
|
"autoridad, no es pública",
|
|
umbral_por_defecto=Decimal("85"),
|
|
lector=leer_lpb,
|
|
patron_archivo="uif_lpb_*.csv", # nunca en seed/: solo la carga el oficial
|
|
nota="protegida",
|
|
protegida=True,
|
|
),
|
|
}
|
|
|
|
|
|
def definicion(nombre: str) -> DefinicionLista:
|
|
try:
|
|
return LISTAS[nombre]
|
|
except KeyError:
|
|
raise ListaDesconocidaError(f"Lista desconocida: {nombre!r}") from None
|
|
|
|
|
|
def fecha_de_archivo(ruta: Path) -> date | None:
|
|
m = _RE_FECHA_ARCHIVO.search(ruta.name)
|
|
return date.fromisoformat(m.group(1)) if m else None
|
|
|
|
|
|
def resolver_ruta(ruta: str | Path) -> Path:
|
|
"""Absoluta tal cual; relativa primero contra el repo y luego contra DATA_DIR."""
|
|
ruta = Path(ruta)
|
|
if ruta.is_absolute():
|
|
return ruta
|
|
for base in (RAIZ_REPO, Path(get_settings().data_dir)):
|
|
candidata = base / ruta
|
|
if candidata.is_file():
|
|
return candidata
|
|
return RAIZ_REPO / ruta
|
|
|
|
|
|
def ruta_para_guardar(ruta: Path) -> str:
|
|
"""Dentro del repo se guarda relativa (portable); fuera, absoluta."""
|
|
try:
|
|
return str(ruta.resolve().relative_to(RAIZ_REPO))
|
|
except ValueError:
|
|
return str(ruta.resolve())
|
|
|
|
|
|
def hash_archivo(ruta: Path) -> str:
|
|
h = hashlib.sha256()
|
|
with ruta.open("rb") as f:
|
|
for bloque in iter(lambda: f.read(1 << 20), b""):
|
|
h.update(bloque)
|
|
return h.hexdigest()
|
|
|
|
|
|
def leer_entradas(nombre: str, ruta: Path) -> list[Entrada]:
|
|
return definicion(nombre).lector(ruta)
|
|
|
|
|
|
# --- Archivos subidos desde la pantalla -------------------------------------------------------
|
|
|
|
MAXIMO_BYTES_LISTA = 25 * 1024 * 1024
|
|
|
|
|
|
class ArchivoDeListaError(ValueError):
|
|
"""El archivo subido no sirve como versión de la lista; el mensaje es apto para pantalla."""
|
|
|
|
|
|
def guardar_archivo_subido(
|
|
tenant_id: int,
|
|
nombre: str,
|
|
fecha_version: date,
|
|
contenido: bytes,
|
|
contenido_alias: bytes | None = None,
|
|
) -> Path:
|
|
"""Guarda el archivo de una versión en `DATA_DIR/listas/<empresa>/` y lo valida leyéndolo con
|
|
el lector de su formato: si no trae ninguna entrada se borra y se rechaza. El nombre lleva la
|
|
fecha y el principio de su huella, así que dos versiones nunca se pisan. Para OFAC, el archivo
|
|
de alias (opcional) se guarda junto, con el nombre que `ruta_alt_de` espera."""
|
|
definicion_ = definicion(nombre)
|
|
if not contenido:
|
|
raise ArchivoDeListaError("El archivo está vacío.")
|
|
if max(len(contenido), len(contenido_alias or b"")) > MAXIMO_BYTES_LISTA:
|
|
raise ArchivoDeListaError(
|
|
f"El archivo pesa más de {MAXIMO_BYTES_LISTA // (1024 * 1024)} MB."
|
|
)
|
|
carpeta = Path(get_settings().data_dir) / "listas" / str(tenant_id)
|
|
carpeta.mkdir(parents=True, exist_ok=True)
|
|
sha = hashlib.sha256(contenido).hexdigest()[:12]
|
|
base = definicion_.patron_archivo.split("*")[0] # `ofac_sdn_`, `uif_lpb_`…
|
|
destino = carpeta / f"{base}{fecha_version.isoformat()}_{sha}{definicion_.extension}"
|
|
escritos = [destino]
|
|
destino.write_bytes(contenido)
|
|
if nombre == "ofac_sdn" and contenido_alias:
|
|
alias = destino.with_name(destino.name.replace("sdn", "alt", 1))
|
|
alias.write_bytes(contenido_alias)
|
|
escritos.append(alias)
|
|
for ruta in escritos:
|
|
ruta.chmod(0o600)
|
|
try:
|
|
entradas = leer_entradas(nombre, destino)
|
|
except (ValueError, KeyError, IndexError, ET.ParseError, UnicodeDecodeError):
|
|
entradas = []
|
|
if not entradas:
|
|
for ruta in escritos:
|
|
ruta.unlink(missing_ok=True)
|
|
raise ArchivoDeListaError(
|
|
"No se reconoció ninguna entrada: el archivo no tiene el formato de "
|
|
f"{definicion_.titulo}."
|
|
)
|
|
return destino
|
|
|
|
|
|
# --- Importación ------------------------------------------------------------------------------
|
|
|
|
|
|
def importar_lista(
|
|
session: Session,
|
|
nombre: str,
|
|
ruta: str | Path,
|
|
*,
|
|
fecha_version: date | None = None,
|
|
usuario: str | None = None,
|
|
umbral: Decimal | None = None,
|
|
) -> Lista | None:
|
|
"""Registra una versión de la lista. No hace commit. Devuelve `None` si ese mismo archivo
|
|
(por hash) ya estaba cargado para esa lista (idempotente)."""
|
|
definicion_ = definicion(nombre)
|
|
archivo = resolver_ruta(ruta)
|
|
if not archivo.is_file():
|
|
raise FileNotFoundError(f"No existe el archivo de la lista {nombre}: {archivo}")
|
|
tenant = tenant_de_sesion(session)
|
|
autor = autor_de_sesion(session, usuario)
|
|
sha = hash_archivo(archivo)
|
|
existente = session.scalar(
|
|
select(Lista).where(
|
|
Lista.tenant_id == tenant.id, Lista.nombre == nombre, Lista.archivo_hash == sha
|
|
)
|
|
)
|
|
if existente is not None:
|
|
logger.info("Lista %s: el archivo ya estaba cargado (lista %s)", nombre, existente.id)
|
|
return None
|
|
entradas = leer_entradas(nombre, archivo)
|
|
fecha_version = fecha_version or fecha_de_archivo(archivo) or date.today()
|
|
lista = Lista(
|
|
tenant_id=tenant.id,
|
|
created_by=autor,
|
|
nombre=nombre,
|
|
fuente=definicion_.fuente[:200],
|
|
fecha_version=fecha_version,
|
|
ruta=ruta_para_guardar(archivo),
|
|
umbral=umbral if umbral is not None else definicion_.umbral_por_defecto,
|
|
entradas=len(entradas),
|
|
archivo_hash=sha,
|
|
)
|
|
session.add(lista)
|
|
session.flush()
|
|
lote = LoteCarga(
|
|
tenant_id=tenant.id,
|
|
created_by=autor,
|
|
tipo="lista",
|
|
archivo_hash=sha,
|
|
filas={"lista": nombre, "entradas": len(entradas), "lista_id": lista.id},
|
|
errores=[],
|
|
usuario=autor,
|
|
)
|
|
session.add(lote)
|
|
session.flush()
|
|
audit.registrar(
|
|
session,
|
|
"lista",
|
|
lista.id,
|
|
"cargar_version",
|
|
despues={
|
|
"nombre": nombre,
|
|
"fecha_version": fecha_version,
|
|
"entradas": len(entradas),
|
|
"archivo_hash": sha,
|
|
"umbral": lista.umbral,
|
|
"ruta": lista.ruta,
|
|
"lote_carga_id": lote.id,
|
|
},
|
|
motivo=f"Versión {fecha_version.isoformat()} de la lista {definicion_.titulo}",
|
|
usuario=autor,
|
|
tenant_id=tenant.id,
|
|
)
|
|
logger.info("Lista %s %s: %s entradas", nombre, fecha_version, len(entradas))
|
|
# La versión vigente de la lista cambia: el índice en memoria de ese nombre deja de valer.
|
|
# Importación perezosa: `app.services.screening` importa este módulo.
|
|
from app.services import screening as servicio_screening
|
|
|
|
servicio_screening.invalidar_indice(nombre)
|
|
return lista
|
|
|
|
|
|
def archivos_seed() -> dict[str, Path]:
|
|
"""La primera versión de cada lista en `seed/listas/` (la de nombre menor por fecha)."""
|
|
salida: dict[str, Path] = {}
|
|
for nombre, definicion_ in LISTAS.items():
|
|
candidatos = sorted(DIR_LISTAS_SEED.glob(definicion_.patron_archivo))
|
|
if candidatos:
|
|
salida[nombre] = candidatos[0]
|
|
return salida
|
|
|
|
|
|
def importar_todas(session: Session, *, usuario: str | None = None) -> dict[str, Lista | None]:
|
|
"""Carga las versiones de `seed/listas/` que falten. No hace commit."""
|
|
return {
|
|
nombre: importar_lista(session, nombre, ruta, usuario=usuario)
|
|
for nombre, ruta in archivos_seed().items()
|
|
}
|
|
|
|
|
|
def main(argv: list[str] | None = None) -> int:
|
|
parser = argparse.ArgumentParser(description="Carga versiones de listas públicas.")
|
|
parser.add_argument("--todas", action="store_true", help="Primeras versiones de seed/listas/")
|
|
parser.add_argument("--lista", choices=sorted(LISTAS), help="Clave de la lista")
|
|
parser.add_argument("--archivo", help="Ruta del archivo (absoluta o relativa al repo/DATA_DIR)")
|
|
parser.add_argument("--fecha", help="Fecha de versión AAAA-MM-DD (por omisión, la del nombre)")
|
|
parser.add_argument("--usuario", default="sistema")
|
|
args = parser.parse_args(argv)
|
|
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
|
if not args.todas and not (args.lista and args.archivo):
|
|
parser.error("Indica --todas o --lista y --archivo.")
|
|
|
|
from app.db import SessionLocal
|
|
|
|
with SessionLocal() as session:
|
|
if args.todas:
|
|
resultado: Iterable[tuple[str, Lista | None]] = importar_todas(
|
|
session, usuario=args.usuario
|
|
).items()
|
|
else:
|
|
fecha = datetime.strptime(args.fecha, "%Y-%m-%d").date() if args.fecha else None
|
|
resultado = [
|
|
(
|
|
args.lista,
|
|
importar_lista(
|
|
session, args.lista, args.archivo, fecha_version=fecha, usuario=args.usuario
|
|
),
|
|
)
|
|
]
|
|
for nombre, lista in resultado:
|
|
if lista is None:
|
|
print(f"{nombre}: sin cambios (ya cargada)")
|
|
else:
|
|
print(f"{nombre}: versión {lista.fecha_version} con {lista.entradas} entradas")
|
|
session.commit()
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|