84 lines
2.7 KiB
Python
84 lines
2.7 KiB
Python
"""Catálogos del SAT (`seed/catalogos/sat/*.csv`) en memoria, para validar y describir claves.
|
|
|
|
Cada CSV lleva una primera línea `#` con su fuente y fecha de extracción. Los catálogos no se
|
|
guardan en la base: son archivos versionados que se cargan una vez por proceso.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import csv
|
|
from functools import cache, lru_cache
|
|
from pathlib import Path
|
|
|
|
CARPETA = Path(__file__).resolve().parents[2] / "seed" / "catalogos" / "sat"
|
|
|
|
TIPO_ALERTA = "tipo_alerta"
|
|
PAIS = "pais"
|
|
ACTIVIDAD_ECONOMICA_FISICA = "actividad_economica_fisica"
|
|
GIRO_MERCANTIL_MORAL = "giro_mercantil_moral"
|
|
CODIGO_POSTAL = "codigo_postal"
|
|
INSTRUMENTO_MONETARIO = "instrumento_monetario"
|
|
MONEDA = "moneda"
|
|
TIPO_OPERACION = "tipo_operacion"
|
|
TIPO_GARANTIA = "tipo_garantia"
|
|
TIPO_INMUEBLE = "tipo_inmueble"
|
|
PRIORIDAD = "prioridad"
|
|
ACTIVIDAD_VULNERABLE = "actividad_vulnerable"
|
|
CATALOGOS = (
|
|
TIPO_ALERTA,
|
|
PAIS,
|
|
ACTIVIDAD_ECONOMICA_FISICA,
|
|
GIRO_MERCANTIL_MORAL,
|
|
CODIGO_POSTAL,
|
|
INSTRUMENTO_MONETARIO,
|
|
MONEDA,
|
|
TIPO_OPERACION,
|
|
TIPO_GARANTIA,
|
|
TIPO_INMUEBLE,
|
|
PRIORIDAD,
|
|
ACTIVIDAD_VULNERABLE,
|
|
)
|
|
|
|
SIN_ALERTA = "100"
|
|
OTRA_ALERTA = "9999"
|
|
CODIGOS_QUE_EXIGEN_DESCRIPCION = frozenset({OTRA_ALERTA})
|
|
|
|
|
|
def _filas(nombre: str) -> list[dict[str, str]]:
|
|
ruta = CARPETA / f"{nombre}.csv"
|
|
with ruta.open(encoding="utf-8", newline="") as archivo:
|
|
lineas = (linea for linea in archivo if not linea.startswith("#"))
|
|
return list(csv.DictReader(lineas))
|
|
|
|
|
|
def fuente(nombre: str) -> str:
|
|
"""La línea de fuente y fecha de extracción del CSV, sin el `#`."""
|
|
with (CARPETA / f"{nombre}.csv").open(encoding="utf-8") as archivo:
|
|
primera = archivo.readline()
|
|
return primera[1:].strip() if primera.startswith("#") else ""
|
|
|
|
|
|
@cache
|
|
def catalogo(nombre: str) -> dict[str, str]:
|
|
"""`{clave: descripcion}` de un catálogo. Para `codigo_postal`, la descripción es
|
|
«MUNICIPIO, ESTADO»."""
|
|
if nombre not in CATALOGOS:
|
|
raise KeyError(f"catálogo del SAT desconocido: {nombre!r}")
|
|
if nombre == CODIGO_POSTAL:
|
|
return {f["clave"]: f"{f['municipio']}, {f['estado']}" for f in _filas(nombre)}
|
|
return {f["clave"]: f["descripcion"] for f in _filas(nombre)}
|
|
|
|
|
|
@lru_cache(maxsize=1)
|
|
def codigos_postales() -> dict[str, tuple[str, str]]:
|
|
"""`{cp: (estado, municipio)}`."""
|
|
return {f["clave"]: (f["estado"], f["municipio"]) for f in _filas(CODIGO_POSTAL)}
|
|
|
|
|
|
def existe(nombre: str, clave: str | int | None) -> bool:
|
|
return clave is not None and str(clave) in catalogo(nombre)
|
|
|
|
|
|
def descripcion(nombre: str, clave: str | int | None) -> str | None:
|
|
return catalogo(nombre).get(str(clave)) if clave is not None else None
|