preliminary release
This commit is contained in:
@@ -32,6 +32,10 @@ ENV CAMA_DATABASE_URL=sqlite:////data/cama.db
|
||||
ENV TEA_DATABASE_URL=sqlite:////data/tea.db
|
||||
ENV GOVERNANCE_DATABASE_URL=sqlite:////data/governance.db
|
||||
ENV MODELS_ARTIFACT_ROOT=/data/artifacts
|
||||
# Aggregate import log and the live indicator queue (webapi.indicadores_vivos).
|
||||
ENV WEBAPI_REPORT_DIR=/data/reportes
|
||||
ENV INDICADORES_DIR=/data/indicadores
|
||||
ENV MLFLOW_DISABLE_AGENT_HINT=1
|
||||
|
||||
RUN chmod +x /app/WebApi/docker-entrypoint.sh
|
||||
|
||||
|
||||
@@ -10,6 +10,13 @@ for url in "$CACU_DATABASE_URL" "$CAMA_DATABASE_URL" "$TEA_DATABASE_URL" "$GOVER
|
||||
esac
|
||||
done
|
||||
|
||||
# The live indicator worker (webapi.indicadores_vivos) shares the image; the
|
||||
# API container runs the migrations, so the worker starts after it.
|
||||
if [ "$1" = "indicadores" ]; then
|
||||
cd /app/WebApi
|
||||
exec uv run --no-sync python -m webapi.indicadores_vivos
|
||||
fi
|
||||
|
||||
# --no-sync: the image's environments were synced at build time; syncing at
|
||||
# startup would try to reach the package index (and pull dev deps).
|
||||
cd /app/Persistance
|
||||
|
||||
@@ -9,6 +9,7 @@ dependencies = [
|
||||
"models[export]",
|
||||
"extraction",
|
||||
"indicadores-kit",
|
||||
"orquestacion",
|
||||
"pandas>=2.0",
|
||||
"openpyxl>=3.1",
|
||||
"sqlalchemy>=2.0",
|
||||
@@ -18,6 +19,7 @@ dependencies = [
|
||||
"Pillow>=10.0",
|
||||
"flask-cors>=4.0",
|
||||
"gunicorn>=23.0",
|
||||
"apache-hamilton>=1.90",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
@@ -32,6 +34,7 @@ persistance = { path = "../Persistance", editable = true }
|
||||
models = { path = "../models", editable = true }
|
||||
extraction = { path = "../Extraction", editable = true }
|
||||
indicadores-kit = { path = "../indicadores_kit", editable = true }
|
||||
orquestacion = { path = "../Orquestacion", editable = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
|
||||
@@ -14,6 +14,10 @@ import pytest
|
||||
# Tests use throwaway SQLite files as "arbitrary SQL sources"; production
|
||||
# excludes sqlite by default (see webapi.imports.connectors.sql_policy).
|
||||
os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postgresql,mssql,oracle")
|
||||
# The import log and the indicator queue write files; keep them out of the tree.
|
||||
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
|
||||
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
|
||||
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
@@ -54,3 +58,46 @@ def _migrate(domain: str) -> None:
|
||||
|
||||
ini = Path(persistance.__file__).parent / domain / "alembic.ini"
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
|
||||
|
||||
# Indicator-route tests (vendored from the fork's WebApi tests): the kit's
|
||||
# demonstration database, seeded into a temporary SQLite file per domain.
|
||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||
|
||||
|
||||
def sembrar_base(proyecto: str, motor) -> None:
|
||||
"""La base de demostración del kit: staging sintético, carga y todos los indicadores calculados.
|
||||
|
||||
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||
meses).
|
||||
"""
|
||||
from indicadores_kit.demostracion import base_de_prueba
|
||||
|
||||
base_de_prueba(motor, proyecto)
|
||||
|
||||
|
||||
def cliente_de(proyecto: str, tmp_path_factory):
|
||||
"""Generador para la fixture `client` de un proyecto: una base SQLite temporal ya sembrada."""
|
||||
from persistance import db
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp(proyecto) / f"{proyecto}.db"
|
||||
obtener_motor = getattr(db, f"get_{proyecto}_engine")
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, f"{proyecto}_database_url", f"sqlite:///{ruta}")
|
||||
obtener_motor.cache_clear()
|
||||
try:
|
||||
sembrar_base(proyecto, obtener_motor())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
obtener_motor().dispose()
|
||||
obtener_motor.cache_clear()
|
||||
|
||||
@@ -0,0 +1,338 @@
|
||||
"""Rutas de indicadores de CACU: base SQLite temporal sembrada con los fixtures del kit."""
|
||||
|
||||
import pytest
|
||||
from conftest import MESES, SEMESTRES, cliente_de
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
|
||||
PROYECTO = "cacu"
|
||||
INDICADOR = "ind1"
|
||||
DEFINICIONES = measures_de(PROYECTO)
|
||||
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||
|
||||
|
||||
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def _x(respuesta) -> list[str]:
|
||||
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get(f"/{PROYECTO}/indicadores")
|
||||
|
||||
assert response.status_code == 200
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Los que su TOML marca `oculto` (p. ej. cacu_riesgo_banda hasta MD-Q5) no salen en el catálogo, pero responden."""
|
||||
ocultos = {nombre for nombre, medida in DEFINICIONES.items() if medida.extension.publicacion.oculto}
|
||||
|
||||
assert ocultos
|
||||
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert ids == set(DEFINICIONES) - ocultos
|
||||
for indicador in ocultos:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
|
||||
|
||||
assert retirados
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
|
||||
|
||||
|
||||
def test_figura_con_semestres(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||
assert set(_x(response)) == set(SEMESTRES)
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||
response = _figura(client)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||
|
||||
|
||||
def test_figura_con_meses(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(MESES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S3",
|
||||
"?periodos=2025-13x",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, query=query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("CACU_NO_EXISTE", FIGURA, ""),
|
||||
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
|
||||
(INDICADOR, "fig_no_existe", ""),
|
||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, query="?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
def test_una_distribucion_sin_periodos_es_la_del_semestre_mas_reciente(client):
|
||||
assert figuras_de(DEFINICIONES["cacu_eu7"]) == ["fig_c2_barras", "fig_c2_donas"]
|
||||
|
||||
por_defecto = _figura(client, "cacu_eu7", "fig_c2_donas")
|
||||
del_ultimo = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={SEMESTRES[-1]}")
|
||||
de_todos = _figura(client, "cacu_eu7", "fig_c2_donas", f"?periodos={','.join(SEMESTRES)}")
|
||||
|
||||
assert por_defecto.get_json() == del_ultimo.get_json()
|
||||
assert len(de_todos.get_json()["data"]) == len(SEMESTRES) * len(por_defecto.get_json()["data"])
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
# --- Los filtros (T-19f) ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?filtro=grupo_edad", "?filtro=:25-34", "?filtro=grupo_edad:25-34,grupo_edad:35-44",
|
||||
"?filtro=grupo_edad:25-34", "?filtro=ronda:1"])
|
||||
def test_un_filtro_mal_escrito_o_no_declarado_da_400(client, query):
|
||||
"""IND1 no declara filtros (EU7 y EU13 sí, desde T-24f): todo `?filtro=` da 400, en datos y en figuras."""
|
||||
for response in (_ruta(client, INDICADOR, "datos", query), _figura(client, query=query)):
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_sin_filtro_los_datos_no_traen_la_llave_filtros(client):
|
||||
assert "filtros" not in _ruta(client, INDICADOR, "datos").get_json()
|
||||
|
||||
|
||||
def test_los_filtros_se_leen_como_estrato_y_valor():
|
||||
from webapi.indicadores import filtros_pedidos
|
||||
|
||||
assert filtros_pedidos(None) == {} and filtros_pedidos("") == {}
|
||||
assert filtros_pedidos("grupo_edad:25-34,ronda:1") == {"grupo_edad": "25-34", "ronda": "1"}
|
||||
with pytest.raises(ValueError, match="mal escrito"):
|
||||
filtros_pedidos("grupo_edad")
|
||||
|
||||
|
||||
# --- La ficha técnica (T-24e) ---
|
||||
|
||||
# Las llaves de /metadatos antes de T-24e: no se quita ni se renombra ninguna.
|
||||
METADATOS = {
|
||||
"id", "titulo", "version", "estado", "contrato", "tipo_calculo", "unidad", "sentido", "descripcion",
|
||||
"tipos_periodo", "figuras", "estratos", "grupos", "categorias", "grupos_de_categoria", "estandares",
|
||||
"ficha", "parametros",
|
||||
} # fmt: skip
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_los_metadatos_traen_referencias_poblaciones_y_figuras_sin_perder_llaves(client, indicador):
|
||||
cuerpo = _ruta(client, indicador, "metadatos").get_json()
|
||||
|
||||
assert set(cuerpo) == METADATOS | {"referencias", "poblaciones", "figuras_detalle"}
|
||||
assert cuerpo["poblaciones"]
|
||||
assert [d["figura"] for d in cuerpo["figuras_detalle"]] == cuerpo["figuras"]
|
||||
if not DEFINICIONES[indicador].extension.publicacion.oculto:
|
||||
assert all(d["descripcion"] and d["como_leer"] for d in cuerpo["figuras_detalle"])
|
||||
assert all(set(p) == {"grupo", "codigo", "descripcion"} and p["descripcion"] for p in cuerpo["poblaciones"])
|
||||
|
||||
|
||||
def test_la_ficha_de_eu7_cita_el_lineamiento_europeo(client):
|
||||
cuerpo = _ruta(client, "cacu_eu7", "metadatos").get_json()
|
||||
|
||||
assert cuerpo["referencias"] == [{
|
||||
"tipo": "citation",
|
||||
"etiqueta": "European Guidelines for QA in Cervical Cancer Screening, 2ª ed. (2008)",
|
||||
"ref": "indicador 7",
|
||||
}] # fmt: skip
|
||||
assert cuerpo["poblaciones"] == [{
|
||||
"grupo": "total",
|
||||
"codigo": "measure-observation",
|
||||
"descripcion": DEFINICIONES["cacu_eu7"].group[0].population[0].description,
|
||||
}] # fmt: skip
|
||||
|
||||
|
||||
# --- EU7 por estrato (T-24f): la dona y sus barras ---
|
||||
|
||||
|
||||
def test_eu7_por_estatus_da_categoria_por_valor_con_etiquetas_y_totales(client):
|
||||
cuerpo = _ruta(client, "cacu_eu7", "datos", "?estrato=estatus_seguimiento").get_json()
|
||||
|
||||
assert cuerpo["estrato"] == "estatus_seguimiento" and cuerpo["valores_estrato"]
|
||||
assert set(cuerpo["etiquetas_estrato"]) == set(cuerpo["valores_estrato"])
|
||||
assert {f["estrato"] for f in cuerpo["filas"]} == set(cuerpo["valores_estrato"])
|
||||
assert {t["estrato"] for t in cuerpo["totales_estrato"]} == set(cuerpo["valores_estrato"])
|
||||
|
||||
|
||||
def test_eu7_se_puede_filtrar_por_grupo_de_edad(client):
|
||||
valor = _ruta(client, "cacu_eu7", "datos", "?estrato=grupo_edad").get_json()["valores_estrato"][0]
|
||||
response = _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filtros"] == {"grupo_edad": valor}
|
||||
|
||||
|
||||
def test_el_catalogo_publica_los_filtros_con_sus_valores(client):
|
||||
"""T-24f (contrato de T-24a §3): con ellos se arma `?filtro=estrato:valor`."""
|
||||
por_id = {fila["id"]: fila for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert por_id[INDICADOR]["filtros"] == [] # IND1 no declara filtros
|
||||
(edad, estatus) = por_id["cacu_eu7"]["filtros"]
|
||||
assert (edad["estrato"], edad["etiqueta"]) == ("grupo_edad", "Grupo de edad")
|
||||
assert [v["valor"] for v in edad["valores"]][-1] == "sin_dato"
|
||||
assert (estatus["estrato"], estatus["etiqueta"]) == ("estatus_seguimiento", "Estatus de seguimiento")
|
||||
assert estatus["valores"] == [
|
||||
{"valor": "PRE_COLPOSCOPIA", "etiqueta": "Pre colposcopia"},
|
||||
{"valor": "POST_COLPOSCOPIA", "etiqueta": "Post colposcopia"},
|
||||
{"valor": "POST_TRATAMIENTO", "etiqueta": "Post tratamiento"},
|
||||
{"valor": "INFO_INSUFICIENTE", "etiqueta": "Información insuficiente"},
|
||||
]
|
||||
valor = edad["valores"][0]["valor"]
|
||||
assert _ruta(client, "cacu_eu7", "datos", f"?filtro=grupo_edad:{valor}").status_code == 200
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Rutas de indicadores de CAMA: base SQLite temporal sembrada con los fixtures del kit."""
|
||||
|
||||
import pytest
|
||||
from conftest import MESES, SEMESTRES, cliente_de
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
|
||||
PROYECTO = "cama"
|
||||
INDICADOR = "cama_confirmacion_birads45"
|
||||
DEFINICIONES = measures_de(PROYECTO)
|
||||
(FIGURA,) = figuras_de(DEFINICIONES[INDICADOR])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
yield from cliente_de(PROYECTO, tmp_path_factory)
|
||||
|
||||
|
||||
def _figura(client, indicador: str = INDICADOR, figura: str = FIGURA, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def _x(respuesta) -> list[str]:
|
||||
return [x for trazo in respuesta.get_json()["data"] for x in trazo["x"]]
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get(f"/{PROYECTO}/indicadores")
|
||||
|
||||
assert response.status_code == 200
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Provisional (oct 2026): cama_birads no se muestra.
|
||||
|
||||
cama_birads lo sustituyen cama_birads_456_paciente y cama_birads_456_mastografia.
|
||||
cama_confirmacion_birads45 vuelve a mostrarse: su tarjeta destacada y su
|
||||
gráfica de tendencia (usuario, 2026-10-16).
|
||||
"""
|
||||
ocultos = {"cama_birads"} # cama_riesgo_banda es propuesta desde T-21h: no se calcula ni se sirve
|
||||
ids = {fila["id"] for fila in client.get(f"/{PROYECTO}/indicadores").get_json()}
|
||||
|
||||
assert ids == set(DEFINICIONES) - ocultos
|
||||
for indicador in ocultos:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 200
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`<proyecto>/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / PROYECTO / "retirados").glob("*.toml")]
|
||||
|
||||
assert retirados
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/{PROYECTO}/indicadores/{indicador}/metadatos").status_code == 404
|
||||
|
||||
|
||||
def test_figura_con_semestres(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(SEMESTRES)}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.mimetype == "application/json"
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES[INDICADOR].title
|
||||
assert set(_x(response)) == set(SEMESTRES)
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_los_semestres_con_reporte(client):
|
||||
response = _figura(client)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(SEMESTRES) # el primer tipo que publica; los meses no entran
|
||||
|
||||
|
||||
def test_figura_con_meses(client):
|
||||
response = _figura(client, query=f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert set(_x(response)) == set(MESES)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S3",
|
||||
"?periodos=2025-13x",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=2025-T1", # un tipo que el indicador no publica
|
||||
"?periodos=2025-S1,2025-03", # tipos mezclados
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, query=query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("CAMA_NO_EXISTE", FIGURA, ""),
|
||||
(INDICADOR, "fig_c3r_caja", ""), # figura de otro contrato
|
||||
(INDICADOR, "fig_no_existe", ""),
|
||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, query="?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Todos los indicadores del proyecto ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura)
|
||||
|
||||
assert response.status_code == 200, (indicador, figura)
|
||||
assert set(response.get_json()) >= {"data", "layout"}
|
||||
|
||||
|
||||
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||
|
||||
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos", "filtros"}
|
||||
|
||||
|
||||
def _ruta(client, indicador: str, ruta: str, query: str = ""):
|
||||
return client.get(f"/{PROYECTO}/indicadores/{indicador}/{ruta}{query}")
|
||||
|
||||
|
||||
def test_el_catalogo_trae_lo_necesario_para_pedir_lo_demas(client):
|
||||
lista = client.get(f"/{PROYECTO}/indicadores").get_json()
|
||||
|
||||
assert all(set(fila) == CATALOGO for fila in lista)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert (fila["version"], fila["unidad"], fila["sentido"]) == (medida.version, medida.basis, medida.improvementNotation)
|
||||
assert fila["estratos"] == medida.extension.estratos
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = _ruta(client, indicador, "periodos")
|
||||
datos = _ruta(client, indicador, "datos")
|
||||
metadatos = _ruta(client, indicador, "metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert all(r.mimetype == "application/json" for r in (periodos, datos, metadatos))
|
||||
assert all(r.get_json()["id"] == indicador for r in (periodos, datos, metadatos))
|
||||
de_semestre = [p["periodo"] for p in periodos.get_json()["periodos"] if p["tipo"] == "semestre"]
|
||||
assert de_semestre == SEMESTRES
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["contrato"], cuerpo["tipo_periodo"], cuerpo["periodos"]) == (medida.extension.contrato, "semestre", SEMESTRES)
|
||||
assert cuerpo["filas"] and all(fila["estrato"] is None for fila in cuerpo["filas"])
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["tipo_calculo"] == medida.scoring
|
||||
|
||||
|
||||
def test_datos_con_meses(client):
|
||||
response = _ruta(client, INDICADOR, "datos", f"?periodos={','.join(MESES)}")
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["tipo_periodo"] == "mes"
|
||||
assert [fila["periodo"] for fila in response.get_json()["filas"]] == MESES
|
||||
|
||||
|
||||
def test_los_datos_dicen_de_que_reporte_salen(client):
|
||||
cuerpo = _ruta(client, INDICADOR, "datos", "?periodos=2025-S1").get_json()
|
||||
periodos = _ruta(client, INDICADOR, "periodos").get_json()["periodos"]
|
||||
|
||||
(reporte,) = cuerpo["reportes"]
|
||||
assert reporte["report_id"] == next(p["report_id"] for p in periodos if p["periodo"] == "2025-S1")
|
||||
assert (reporte["periodo_inicio"], reporte["periodo_fin"]) == ("2025-01-01", "2025-07-01")
|
||||
assert cuerpo["version"] == DEFINICIONES[INDICADOR].version
|
||||
|
||||
|
||||
@pytest.mark.parametrize("query", ["?periodos=2025-S3", "?periodos=2025-S1,2025-03", "?estrato=no_existe"])
|
||||
def test_datos_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _ruta(client, INDICADOR, "datos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "ruta", "query"),
|
||||
[
|
||||
("NO_EXISTE", "datos", ""),
|
||||
("NO_EXISTE", "periodos", ""),
|
||||
("NO_EXISTE", "metadatos", ""),
|
||||
(INDICADOR, "datos", "?periodos=2030-S1"),
|
||||
],
|
||||
)
|
||||
def test_un_indicador_desconocido_o_un_periodo_sin_reporte_da_404(client, indicador, ruta, query):
|
||||
response = _ruta(client, indicador, ruta, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
@@ -1,183 +0,0 @@
|
||||
"""Endpoint tests for `/tea/indicadores`, `/cacu/indicadores` and
|
||||
`/cama/indicadores`: the read side of the bronze/silver/gold pipeline
|
||||
(Persistance/persistance/aristas, indicadores_kit). Seeds one patient,
|
||||
runs the real `cargar`/`registro`/`definiciones`/`calcular` steps, then
|
||||
hits the HTTP layer."""
|
||||
from datetime import date
|
||||
from functools import partial
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("tea")
|
||||
|
||||
from core.tea.models import Pacientes
|
||||
from persistance import db as persistance_db
|
||||
from persistance.tea import (
|
||||
staging_repository, carga_repository, def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository,
|
||||
)
|
||||
from indicadores_kit.tea import etl
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with __import__("sqlmodel").Session(persistance_db.get_tea_engine()) as session:
|
||||
session.add(Pacientes(pac_id_hospital="H-1", pac_fecha_nacimiento=date(2020, 1, 1), pac_sexo="F"))
|
||||
session.commit()
|
||||
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
|
||||
tablas = tablas_de("tea")
|
||||
measures = measures_de("tea")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2024, 2024, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("tea"), tablas=tablas))
|
||||
nombre, medida = next(iter(measures.items()))
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2024, 1, 1), date(2025, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_list_indicadores(client):
|
||||
"""Only the 5 TEA measures not marked `oculto` in their own TOML publish
|
||||
to the catalog (the K01-K08/M02-M19 family is draft/internal); a hidden
|
||||
id still answers `/datos` directly, see `test_indicador_datos_...`."""
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
indicadores = response.get_json()
|
||||
assert isinstance(indicadores, list)
|
||||
assert len(indicadores) == 5
|
||||
assert {"id", "titulo", "contrato", "unidad", "sentido", "tipos_periodo", "estratos", "figuras"} <= indicadores[0].keys()
|
||||
|
||||
|
||||
def test_indicador_datos_returns_valid_json_no_bare_nan(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2024-S1,2024-S2")
|
||||
assert response.status_code == 200
|
||||
# Pandas renders missing scores as NaN; the response must not leak the
|
||||
# bare (invalid-JSON) token -- it has to come through as `null`.
|
||||
assert "NaN" not in response.get_data(as_text=True)
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert set(body["periodos"]) == {"2024-S1", "2024-S2"}
|
||||
assert {row["periodo"] for row in body["filas"]} == {"2024-S1", "2024-S2"}
|
||||
|
||||
|
||||
def test_indicador_datos_without_periodos_defaults_to_available_ones(client):
|
||||
"""Unlike the old endpoint, omitting `periodos` is not an error: it
|
||||
reports whatever periods already have a computed report."""
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["periodos"]
|
||||
|
||||
|
||||
def test_indicador_datos_unknown_indicador_is_404(client):
|
||||
response = client.get("/tea/indicadores/NOPE/datos?periodos=2024-S1")
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_indicador_datos_malformed_periodo_is_400(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=no-es-un-periodo")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_indicador_periodos_endpoint(client):
|
||||
response = client.get("/tea/indicadores/K01_evaluacion_3_meses/periodos")
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["id"] == "K01_evaluacion_3_meses"
|
||||
assert isinstance(body["periodos"], list)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def cacu_client(wire_domain):
|
||||
"""CaCu reproduces a real id mismatch TEA's fixture doesn't: some of its
|
||||
TOML files are named in lowercase (`cacu_biopsias.toml`, the
|
||||
`measures_de` dict key) while their `measure.url` ends in uppercase
|
||||
(`cacu/CACU_BIOPSIAS`, the id `indicador_definicion.indicador` and the
|
||||
catalog publish) -- caught live by driving the WebApp dashboard against
|
||||
a real CaCu indicator, not by the TEA-only fixture above."""
|
||||
wire_domain("cacu")
|
||||
|
||||
from sqlmodel import Session
|
||||
from persistance import db as persistance_db
|
||||
from persistance.cacu import (
|
||||
staging_repository, carga_repository, def_parametro_repository as cacu_def_parametro_repository,
|
||||
dim_periodo_repository, indicador_definicion_repository, calculo_repository, vistas_repository,
|
||||
)
|
||||
from indicadores_kit.cacu import etl, fixtures
|
||||
from indicadores_kit.cdm.etl import lote_de_resultados
|
||||
from indicadores_kit.esquema import ddl_de_vistas
|
||||
from indicadores_kit.registry.parametros import leer_parametros, RUTA_PARAMETROS
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.registry.measures import measures_de, rutas_de_measures
|
||||
from indicadores_kit.serving.definiciones import leer_definiciones
|
||||
from indicadores_kit.mart.calculo import medir_con_unidades
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
|
||||
with Session(persistance_db.get_cacu_engine()) as session:
|
||||
fixtures.insertar(session)
|
||||
session.commit()
|
||||
|
||||
tablas = tablas_de("cacu")
|
||||
staging = staging_repository.leer(etl.STAGING)
|
||||
lote = etl.lote_de_estudios(**staging)
|
||||
carga_repository.guardar_lote(**lote.para_guardar())
|
||||
pacientes = staging_repository.leer({"pacientes": etl.STAGING["pacientes"]})["pacientes"]
|
||||
lote_resultados = lote_de_resultados(
|
||||
pacientes, staging_repository.leer(etl.STAGING_DE_RESULTADOS), etl.FUENTES_DE_RESULTADOS, tablas=tablas,
|
||||
)
|
||||
carga_repository.guardar_lote(**lote_resultados.para_guardar())
|
||||
vistas_repository.construir(ddl_de_vistas("cacu"))
|
||||
|
||||
measures = measures_de("cacu")
|
||||
tipos = sorted({t for m in measures.values() for t in m.extension.publicacion.tipos_periodo})
|
||||
cacu_def_parametro_repository.reemplazar(leer_parametros(RUTA_PARAMETROS, tablas=tablas))
|
||||
dim_periodo_repository.agregar_faltantes(periodos_de_tipos(tipos, 2025, 2025, tablas=tablas))
|
||||
indicador_definicion_repository.reemplazar(leer_definiciones(rutas_de_measures("cacu"), tablas=tablas))
|
||||
for medida in measures.values():
|
||||
for tipo in medida.extension.publicacion.tipos_periodo:
|
||||
for periodo_id in calculo_repository.periodos(tipo, date(2025, 1, 1), date(2026, 1, 1)):
|
||||
medir = partial(medir_con_unidades, measure=medida, periodo_id=periodo_id, tablas=tablas,
|
||||
corte=None, permitir_sin_definir=True)
|
||||
calculo_repository.calcular(medir)
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_indicador_datos_uses_the_toml_key_not_measure_url(cacu_client):
|
||||
"""`cacu_biopsias`'s own `measure.url` ends in `CACU_BIOPSIAS` (uppercase),
|
||||
but `registrar_indicadores` publishes and looks measures up by
|
||||
`measures_de()`'s dict key (the lowercase TOML file stem) throughout, so
|
||||
the mismatch never reaches a client -- unlike the old, since-replaced
|
||||
`webapi.indicadores`, which published the uppercase `measure.url` id and
|
||||
needed its own `_measure_por_indicador` lookup to reconcile the two."""
|
||||
catalogo = cacu_client.get("/cacu/indicadores").get_json()
|
||||
assert any(i["id"] == "cacu_biopsias" for i in catalogo)
|
||||
assert not any(i["id"] == "CACU_BIOPSIAS" for i in catalogo)
|
||||
|
||||
response = cacu_client.get("/cacu/indicadores/cacu_biopsias/datos?periodos=2025-S1,2025-S2")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["filas"]
|
||||
@@ -0,0 +1,177 @@
|
||||
import pytest
|
||||
from indicadores_kit.registry.measures import RAIZ, measures_de
|
||||
from indicadores_kit.serving.figuras import figuras_de
|
||||
from indicadores_kit.tea import fixtures
|
||||
|
||||
DEFINICIONES = measures_de("tea")
|
||||
PERIODOS = ",".join(fixtures.PERIODOS)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
"""Una base de TEA temporal, con los 20 indicadores calculados (16 en el catálogo), por `TEA_DATABASE_URL`."""
|
||||
# Dentro de la fixture: la configuración de Persistance se lee al importarla,
|
||||
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||
from persistance.db import get_tea_engine
|
||||
from persistance.settings import settings
|
||||
|
||||
ruta = tmp_path_factory.mktemp("tea") / "tea.db"
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setattr(settings, "tea_database_url", f"sqlite:///{ruta}")
|
||||
get_tea_engine.cache_clear()
|
||||
try:
|
||||
fixtures.base_de_prueba(get_tea_engine())
|
||||
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as cliente:
|
||||
yield cliente
|
||||
finally:
|
||||
get_tea_engine().dispose()
|
||||
get_tea_engine.cache_clear()
|
||||
|
||||
|
||||
def _figura(client, indicador: str, figura: str, query: str = ""):
|
||||
return client.get(f"/tea/indicadores/{indicador}/figuras/{figura}{query}")
|
||||
|
||||
|
||||
def test_listar_indicadores(client):
|
||||
response = client.get("/tea/indicadores")
|
||||
assert response.status_code == 200
|
||||
|
||||
lista = response.get_json()
|
||||
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||
for fila in lista:
|
||||
medida = DEFINICIONES[fila["id"]]
|
||||
assert fila["titulo"] == medida.title
|
||||
assert fila["contrato"] == medida.extension.contrato
|
||||
assert fila["figuras"] == figuras_de(medida)
|
||||
|
||||
|
||||
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||
"""Provisional (oct 2026): solo se muestran M21, M22 y los tres destacados (M23 a M25)."""
|
||||
visibles = {
|
||||
"M21_diagnosticados_con_eeg",
|
||||
"M22_diagnosticados_sin_eeg",
|
||||
"M23_pacientes_evaluados",
|
||||
"M24_confirmacion_diagnostico",
|
||||
"M25_dias_mchat_diagnostico",
|
||||
}
|
||||
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
|
||||
|
||||
assert ids == visibles
|
||||
for oculto in sorted(set(DEFINICIONES) - visibles):
|
||||
assert client.get(f"/tea/indicadores/{oculto}/metadatos").status_code == 200
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_figura_de_cada_indicador(client, indicador):
|
||||
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||
|
||||
assert response.status_code == 200, figura
|
||||
assert response.mimetype == "application/json"
|
||||
assert "data" in response.get_json()
|
||||
|
||||
|
||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||
(figura,) = figuras_de(DEFINICIONES["M21_diagnosticados_con_eeg"])
|
||||
|
||||
response = _figura(client, "M21_diagnosticados_con_eeg", figura)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["layout"]["title"]["text"] == DEFINICIONES["M21_diagnosticados_con_eeg"].title
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
[
|
||||
"?tema=rojo",
|
||||
"?periodos=2025-1",
|
||||
"?periodos=2025-S1,",
|
||||
"?periodos=abc",
|
||||
"?periodos=,",
|
||||
],
|
||||
)
|
||||
def test_figura_con_parametros_mal_formados_da_400(client, query):
|
||||
response = _figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", query)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("indicador", "figura", "query"),
|
||||
[
|
||||
("K99_no_existe", "fig_c1_grupos", ""),
|
||||
("M21_diagnosticados_con_eeg", "fig_c3r_caja", ""), # figura de otro contrato
|
||||
("M21_diagnosticados_con_eeg", "fig_no_existe", ""),
|
||||
("M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2030-S1"), # sin reporte
|
||||
("M21_diagnosticados_con_eeg", "fig_c1_grupos", f"?periodos={PERIODOS},2030-S2"),
|
||||
],
|
||||
)
|
||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||
response = _figura(client, indicador, figura, query)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_paciente_por_id_entero(client):
|
||||
response = client.get("/tea/pacientes/1")
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["pac_id_hospital"] == "T-01"
|
||||
|
||||
assert client.get("/tea/pacientes/abc").status_code == 404
|
||||
|
||||
|
||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||
from webapi import indicadores
|
||||
|
||||
def falla(*args, **kwargs):
|
||||
raise KeyError("columna")
|
||||
|
||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||
with pytest.raises(KeyError):
|
||||
_figura(client, "M21_diagnosticados_con_eeg", "fig_c1_grupos", "?periodos=2025-S1")
|
||||
|
||||
|
||||
# --- Los periodos, los datos y los metadatos ---
|
||||
|
||||
|
||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||
def test_periodos_datos_y_metadatos_de_cada_indicador(client, indicador):
|
||||
medida = DEFINICIONES[indicador]
|
||||
|
||||
periodos = client.get(f"/tea/indicadores/{indicador}/periodos")
|
||||
datos = client.get(f"/tea/indicadores/{indicador}/datos?periodos={PERIODOS}")
|
||||
metadatos = client.get(f"/tea/indicadores/{indicador}/metadatos")
|
||||
|
||||
assert (periodos.status_code, datos.status_code, metadatos.status_code) == (200, 200, 200)
|
||||
assert [p["periodo"] for p in periodos.get_json()["periodos"]] == sorted(fixtures.PERIODOS)
|
||||
cuerpo = datos.get_json()
|
||||
assert (cuerpo["id"], cuerpo["contrato"]) == (indicador, medida.extension.contrato)
|
||||
assert cuerpo["filas"] and {fila["periodo"] for fila in cuerpo["filas"]} == set(fixtures.PERIODOS)
|
||||
assert {fila["grupo"] for fila in cuerpo["filas"]} <= set(cuerpo["grupos"])
|
||||
assert "data" not in cuerpo and "layout" not in cuerpo # no es una figura
|
||||
assert metadatos.get_json()["ficha"]["codigo"] == medida.extension.ficha.codigo
|
||||
|
||||
|
||||
def test_los_grupos_de_los_datos_van_en_el_orden_de_la_ficha(client):
|
||||
response = client.get(f"/tea/indicadores/M21_diagnosticados_con_eeg/datos?periodos={PERIODOS}")
|
||||
|
||||
grupos = list(response.get_json()["grupos"])
|
||||
assert grupos != sorted(grupos) # el orden de la ficha, no el alfabético
|
||||
assert grupos[-1] == "TOTAL"
|
||||
|
||||
|
||||
def test_un_indicador_retirado_da_404(client):
|
||||
"""T-22a (ADR-MD-009): los retirados (`tea/retirados/` del kit) ni se calculan ni se sirven."""
|
||||
retirados = [ruta.stem for ruta in (RAIZ / "tea" / "retirados").glob("*.toml")]
|
||||
|
||||
assert len(retirados) == 18
|
||||
for indicador in retirados:
|
||||
assert client.get(f"/tea/indicadores/{indicador}/metadatos").status_code == 404
|
||||
@@ -100,7 +100,6 @@ def test_several_edf_files_load_into_eeg_estudio_with_the_file(client):
|
||||
"target": "tea.EegEstudio",
|
||||
"column_mapping": {
|
||||
"id_registro_laboratorio": "eeg_id_registro_laboratorio",
|
||||
"paciente": "eeg_pac_id",
|
||||
"fecha_estudio": "eeg_fecha_estudio",
|
||||
"duracion_min": "eeg_duracion_min",
|
||||
"ritmo_base_frecuencia": "eeg_ritmo_base_frecuencia",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""The Hamilton pipeline computes exactly what Orquestacion's own executor does."""
|
||||
from importlib import import_module
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from sqlmodel import Session
|
||||
|
||||
|
||||
def _seed_and_run(proyecto, tmp_path, run):
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.conexion import apuntar
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
url = f"sqlite:///{tmp_path / f'{proyecto}.db'}"
|
||||
apuntar(proyecto, url)
|
||||
ctx = Contexto(proyecto, 2025, 2025, permitir_sin_definir=True, repos=repositorios_de(proyecto))
|
||||
correr_orquestacion(ctx, solo=["migrar"])
|
||||
with Session(sa.create_engine(url)) as sesion:
|
||||
import_module(f"indicadores_kit.{proyecto}.fixtures").insertar(sesion)
|
||||
sesion.commit()
|
||||
run(ctx)
|
||||
engine = sa.create_engine(url)
|
||||
with engine.connect() as conn:
|
||||
reports = conn.execute(sa.text(
|
||||
"SELECT measure_url, periodo_id, status, tipo FROM measure_report ORDER BY 1, 2, 3, 4")).all()
|
||||
units = conn.execute(sa.text(
|
||||
"SELECT r.measure_url, r.periodo_id, u.grupo, u.unidad_id, u.resultado_id, u.valor_id, u.numero "
|
||||
"FROM measure_report_unidad u JOIN measure_report r USING (report_id) ORDER BY 1, 2, 3, 4, 5")).all()
|
||||
engine.dispose()
|
||||
return reports, units
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proyecto", ["cacu", "tea"])
|
||||
def test_hamilton_matches_the_orquestacion_executor(proyecto, tmp_path_factory):
|
||||
from orquestacion.ejecutor import correr as correr_orquestacion
|
||||
|
||||
from webapi.pipeline import correr as correr_hamilton
|
||||
|
||||
nombres = None
|
||||
|
||||
def by_executor(ctx):
|
||||
nonlocal nombres
|
||||
nombres = [p.arista for p in correr_orquestacion(ctx) if p.arista != "migrar"]
|
||||
|
||||
expected = _seed_and_run(proyecto, tmp_path_factory.mktemp("orquestacion"), by_executor)
|
||||
got = _seed_and_run(proyecto, tmp_path_factory.mktemp("hamilton"),
|
||||
lambda ctx: correr_hamilton(ctx, solo=nombres))
|
||||
assert expected[0] and expected[1]
|
||||
assert got == expected
|
||||
@@ -0,0 +1,159 @@
|
||||
"""The aggregate import log and the live indicator recomputation."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
MAPPING = {
|
||||
"pac_id_hospital": "pac_id_hospital",
|
||||
"pac_sexo": "pac_sexo",
|
||||
"pac_fecha_nacimiento": "pac_fecha_nacimiento",
|
||||
"pac_codigo_postal": "pac_codigo_postal",
|
||||
}
|
||||
|
||||
|
||||
def _csv(rows: list[str]) -> dict:
|
||||
body = "\n".join(["pac_id_hospital,pac_sexo,pac_fecha_nacimiento,pac_codigo_postal", *rows]).encode()
|
||||
return {
|
||||
"source_type": "csv",
|
||||
"target": "cacu.Paciente",
|
||||
"column_mapping": MAPPING,
|
||||
"payload": {"file_base64": base64.b64encode(body).decode(), "options": {"file_name": "Garcia_Lopez.csv"}},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain, tmp_path_factory):
|
||||
wire_domain("cacu")
|
||||
import os
|
||||
|
||||
os.environ["WEBAPI_REPORT_DIR"] = str(tmp_path_factory.mktemp("reportes"))
|
||||
os.environ["INDICADORES_DIR"] = str(tmp_path_factory.mktemp("indicadores"))
|
||||
os.environ["INDICADORES_DESDE"] = "2025"
|
||||
os.environ["INDICADORES_HASTA"] = "2025"
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def _log():
|
||||
from webapi.imports.audit import default_sink
|
||||
|
||||
return default_sink().read()
|
||||
|
||||
|
||||
def test_commit_is_logged_as_aggregates_only(client):
|
||||
rows = [f"RPT-{i},F,1980-01-0{i % 9 + 1},64000" for i in range(4)]
|
||||
rows += [f"RPT-BAD-{i},POSITIVO,15/13/1980,64000" for i in range(6)]
|
||||
rows += ["RPT-RARE,QWERTY,1980-01-01,"]
|
||||
response = client.post("/imports/commit", json={"sources": [_csv(rows)], "on_conflict": "reject"})
|
||||
body = response.get_json()
|
||||
assert response.status_code == 200
|
||||
assert body["results"][0]["created"] == 4
|
||||
assert body["indicadores_en_recalculo"] is True
|
||||
|
||||
record = _log()[-1]
|
||||
assert record["id"] == body["audit_id"]
|
||||
assert (record["operacion"], record["dominio"], record["resultado"]) == ("carga", "cacu", "completada")
|
||||
source = record["fuentes"][0]
|
||||
assert source["origen"] == {"tipo": "csv", "extensiones": [".csv"]}
|
||||
assert source["filas"]["leidas"] == 11
|
||||
assert source["filas"]["insertadas"] == 4
|
||||
assert source["filas"]["rechazadas_en_validacion"] == 7
|
||||
sexo = source["campos"]["pac_sexo"]
|
||||
assert sexo["valores_fuera_de_catalogo"] == {"POSITIVO": 6}
|
||||
assert sexo["valores_fuera_de_catalogo_poco_frecuentes"] == 1
|
||||
assert source["campos"]["pac_fecha_nacimiento"]["formatos_rechazados"] == {"99/99/9999": 6}
|
||||
assert source["campos"]["pac_codigo_postal"]["vacios"] == 1
|
||||
|
||||
raw = json.dumps(record)
|
||||
for secret in ("RPT-", "Garcia", "QWERTY", "15/13/1980"):
|
||||
assert secret not in raw
|
||||
|
||||
|
||||
def test_failed_request_and_validation_are_logged(client):
|
||||
bad = _csv(["RPT-X,F,1980-01-01,64000"])
|
||||
bad["target"] = "cacu.NoExiste"
|
||||
assert client.post("/imports/commit", json={"sources": [bad]}).status_code == 400
|
||||
assert _log()[-1]["resultado"] == "solicitud_invalida"
|
||||
|
||||
assert client.post("/imports/validate", json={"source": _csv(["RPT-V,F,1980-01-01,64000"])}).status_code == 200
|
||||
last = _log()[-1]
|
||||
assert (last["operacion"], last["resultado"]) == ("validacion", "completada")
|
||||
assert last["fuentes"][0]["filas"]["validas"] == 1
|
||||
|
||||
|
||||
def test_report_endpoints(client):
|
||||
body = client.get("/reportes/importaciones").get_json()
|
||||
paciente = body["resumen"]["destinos"]["cacu.Paciente"]
|
||||
assert paciente["cargas_completadas"] == 1
|
||||
assert paciente["filas_en_cargas_completadas"]["insertadas"] == 4
|
||||
assert body["intentos"][0]["operacion"] == "validacion"
|
||||
download = client.get("/reportes/importaciones/descarga")
|
||||
assert len(download.get_data(as_text=True).strip().splitlines()) == len(_log())
|
||||
|
||||
|
||||
def test_indicators_recompute_from_imported_rows(client):
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
|
||||
cola = ColaDeRecalculo()
|
||||
assert client.get("/reportes/indicadores").get_json()["cacu"]["pendiente"] is True
|
||||
assert cola.atender() == ["cacu"]
|
||||
estado = client.get("/reportes/indicadores").get_json()["cacu"]
|
||||
assert estado["estado"] == "ok", estado
|
||||
assert estado["pendiente"] is False
|
||||
assert {p["arista"] for p in estado["pasos"]} >= {"cargar", "calcular"}
|
||||
assert client.get("/cacu/indicadores").get_json()
|
||||
|
||||
assert client.post("/reportes/indicadores/cacu/recalcular").status_code == 202
|
||||
assert client.post("/reportes/indicadores/xx/recalcular").status_code == 404
|
||||
|
||||
|
||||
def test_headerless_file_does_not_leak_its_first_record():
|
||||
"""Without a header row the first record becomes the column names."""
|
||||
from webapi.imports.audit import column_label
|
||||
|
||||
for header in ("pac_id_hospital", "fecha_nacimiento", "cit_vph_genotipo_16", "Sexo", "Código postal"):
|
||||
assert column_label(header) == header
|
||||
for value, shape in (("N-0001", "A-9999"), ("1980-01-01", "9999-99-99"), ("64000", "99999"),
|
||||
("H123", "A999"), ("ana@x.mx", "AAA@A.AA")):
|
||||
assert column_label(value) == shape
|
||||
note = "Paciente refiere dolor pélvico desde hace tres semanas"
|
||||
assert note not in column_label(note)
|
||||
|
||||
|
||||
def test_headerless_csv_logs_shapes(client):
|
||||
body = "N-0001,F,1980-01-01\nN-0002,F,1981-02-02\n".encode()
|
||||
source = {
|
||||
"source_type": "csv", "target": "cacu.Paciente",
|
||||
"column_mapping": {"N-0001": "pac_id_hospital", "F": "pac_sexo", "1980-01-01": "pac_fecha_nacimiento"},
|
||||
"payload": {"file_base64": base64.b64encode(body).decode()},
|
||||
}
|
||||
client.post("/imports/validate", json={"source": source})
|
||||
raw = json.dumps(_log()[-1])
|
||||
assert "N-0001" not in raw and "1980-01-01" not in raw
|
||||
assert "A-9999" in raw
|
||||
|
||||
|
||||
def test_hamilton_pipeline_orders_the_kit_steps_like_the_graph():
|
||||
"""Same steps, same dependency order as Orquestacion's own graph."""
|
||||
from orquestacion.arista import Contexto
|
||||
from orquestacion.aristas import FUENTES, aristas_de
|
||||
from orquestacion.grafo import orden
|
||||
|
||||
from webapi.pipeline import _order, modulo
|
||||
from hamilton import driver
|
||||
|
||||
for proyecto in ("tea", "cacu", "cama"):
|
||||
aristas = aristas_de(proyecto)
|
||||
dr = driver.Builder().with_modules(modulo(Contexto(proyecto, 2025, 2025), aristas)).build()
|
||||
nombres = [a.nombre for a in aristas]
|
||||
hamilton_order = _order(dr, nombres)
|
||||
graph_order = [a.nombre for a in orden(aristas, FUENTES)]
|
||||
assert set(hamilton_order) == set(graph_order)
|
||||
for arista in aristas:
|
||||
for anterior in dr.graph.nodes[arista.nombre].dependencies:
|
||||
assert hamilton_order.index(anterior.name) < hamilton_order.index(arista.nombre)
|
||||
@@ -231,3 +231,20 @@ def test_catalog_for_exposes_field_catalog_and_errors_stay_on_field():
|
||||
assert classified.field == "pac_sexo"
|
||||
assert classified.category == ErrorCategory.OUT_OF_CATALOG
|
||||
assert "no está en el catálogo" in classified.message
|
||||
|
||||
|
||||
def test_catalog_aliases_for_values_the_indicator_kit_uses():
|
||||
"""Hospital spellings the indicator kit's own synthetic sources use must
|
||||
not be rejected at import."""
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenes
|
||||
from webapi.imports.schemas.tea.ordenes_estudio import OrdenesEstudioImportSchema as TeaOrdenes
|
||||
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="CIN1").bx_cin_grado == "LIEBG"
|
||||
assert BiopsiaCervicalImportSchema(pac_id_hospital="H", bx_cin_grado="nic 3").bx_cin_grado == "LIEAG"
|
||||
cito = CitologiaCervicalImportSchema(pac_id_hospital="H", cit_celulas_escamosas="NEGATIVO")
|
||||
assert cito.cit_celulas_escamosas == "NORMAL"
|
||||
assert CamaOrdenes(pac_id_hospital="H", ord_numero_hospital=1, ord_tipo_estudio="MASTOGRAFIA").ord_tipo_estudio == "MASTOGRAFIA"
|
||||
assert TeaOrdenes(ord_tipo_estudio="POTENCIALES_EVOCADOS").ord_tipo_estudio == "POTENCIALES_EVOCADOS_AUDITIVOS"
|
||||
assert TeaOrdenes(ord_tipo_estudio=" evaluacion_psicologica_tea ").ord_tipo_estudio == "EVALUACION_PSICOLOGICA_TEA"
|
||||
|
||||
@@ -7,6 +7,7 @@ from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import OrdenesEstudioImportSchema as CamaOrdenesEstudioImportSchema
|
||||
from webapi.imports.schemas.tea.eeg_estudio import EegEstudioImportSchema
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import EpisodioClinicoImportSchema
|
||||
|
||||
|
||||
# Domains whose Core layer is fully permissive (every field Optional);
|
||||
@@ -30,8 +31,8 @@ def test_every_registered_schema_is_constructible(entity_key):
|
||||
schema_cls()
|
||||
|
||||
|
||||
def test_entity_registry_has_twenty_two_entries():
|
||||
assert len(ENTITY_REGISTRY) == 22
|
||||
def test_entity_registry_has_twenty_four_entries():
|
||||
assert len(ENTITY_REGISTRY) == 24
|
||||
|
||||
|
||||
def test_entity_registry_keys_cover_all_three_domains():
|
||||
@@ -42,12 +43,14 @@ def test_entity_registry_keys_cover_all_three_domains():
|
||||
assert "cacu.BiopsiaCervical" in keys
|
||||
assert "cacu.NotaMedica" in keys
|
||||
assert "cacu.BiometriaHematica" in keys
|
||||
assert "cacu.EpisodioClinico" in keys
|
||||
assert "cama.Paciente" in keys
|
||||
assert "cama.OrdenesEstudio" in keys
|
||||
assert "cama.Mastografia" in keys
|
||||
assert "cama.BiopsiaMama" in keys
|
||||
assert "cama.NotaMedica" in keys
|
||||
assert "cama.BiometriaHematica" in keys
|
||||
assert "cama.EpisodioClinico" in keys
|
||||
assert "tea.Pacientes" in keys
|
||||
assert "tea.OrdenesEstudio" in keys
|
||||
assert "tea.NotaMedica" in keys
|
||||
@@ -90,3 +93,16 @@ def test_cacu_biopsia_cervical_coerces_cin_grado_alias():
|
||||
|
||||
with pytest.raises(ValidationError):
|
||||
BiopsiaCervicalImportSchema(bx_cin_grado="LIEBG") # pac_id_hospital missing
|
||||
|
||||
|
||||
# CaCu EpisodioClinico: requires pac_id_hospital and coerces tipo_episodio/
|
||||
# especialidad_medica through their respective *_ALIAS catalogs.
|
||||
def test_cacu_episodio_clinico_requires_pac_id_hospital_and_coerces_catalogs():
|
||||
with pytest.raises(ValidationError):
|
||||
EpisodioClinicoImportSchema(tipo_episodio="SCREENING") # pac_id_hospital missing
|
||||
|
||||
schema = EpisodioClinicoImportSchema(
|
||||
pac_id_hospital="H-1", tipo_episodio="SCREENING", especialidad_medica="MEDICINA FAMILIAR",
|
||||
)
|
||||
assert schema.tipo_episodio == "TAMIZAJE"
|
||||
assert schema.especialidad_medica == "MEDICINA_FAMILIAR"
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
"""La lista de seguimiento (T-24d): `GET /cacu/seguimiento`, solo en DEV y siempre simulada.
|
||||
|
||||
Sobre la base de demostración del kit (`conftest.cliente_de`). La lista en sí se prueba en el kit
|
||||
(`tests/test_lista_seguimiento.py`); aquí, la ruta: cuándo existe, la forma y los códigos de error.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from conftest import cliente_de
|
||||
|
||||
LLAVES = {"simulado", "corte", "ventana", "filtros", "estatus_disponibles", "reglas", "paginacion", "items"}
|
||||
LLAVES_DEL_ITEM = {"id_seudonimo", "grupo_edad", "estatus", "ultima_citologia", "ultimo_vph",
|
||||
"dias_toma_diagnostico", "prioridad"} # fmt: skip
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.setenv("DEV_REVISION", "prueba")
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def fuera_de_dev(tmp_path_factory):
|
||||
with pytest.MonkeyPatch.context() as mp:
|
||||
mp.delenv("DEV_REVISION", raising=False)
|
||||
yield from cliente_de("cacu", tmp_path_factory)
|
||||
|
||||
|
||||
def test_en_dev_la_lista_tiene_la_forma_del_contrato_y_es_simulada(client):
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31")
|
||||
|
||||
assert response.status_code == 200 and response.mimetype == "application/json"
|
||||
cuerpo = response.get_json()
|
||||
assert set(cuerpo) == LLAVES and cuerpo["simulado"] is True
|
||||
assert cuerpo["items"] and all(set(i) == LLAVES_DEL_ITEM for i in cuerpo["items"])
|
||||
assert all(i["prioridad"] is None for i in cuerpo["items"])
|
||||
assert "pac_id" not in response.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_el_pedido_se_respeta(client):
|
||||
cuerpo = client.get("/cacu/seguimiento?corte=2025-12-31&meses=6&page=1&page_size=2&estatus=PRE_COLPOSCOPIA").get_json()
|
||||
|
||||
assert cuerpo["ventana"]["meses"] == 6 and cuerpo["paginacion"]["page_size"] == 2
|
||||
assert len(cuerpo["items"]) <= 2 and all(i["estatus"]["codigo"] == "PRE_COLPOSCOPIA" for i in cuerpo["items"])
|
||||
assert cuerpo["filtros"] == {"estatus": "PRE_COLPOSCOPIA"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"query",
|
||||
["?corte=2025-13", "?corte=ayer", "?meses=2", "?meses=tres", "?estatus=OTRO", "?page=0", "?page_size=500"],
|
||||
)
|
||||
def test_un_pedido_mal_escrito_o_fuera_de_rango_da_400(client, query):
|
||||
response = client.get(f"/cacu/seguimiento{query}")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_una_pagina_de_mas_da_404(client):
|
||||
response = client.get("/cacu/seguimiento?corte=2025-12-31&page=9999")
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "error" in response.get_json()
|
||||
|
||||
|
||||
def test_fuera_de_dev_la_ruta_no_existe(fuera_de_dev):
|
||||
assert fuera_de_dev.get("/cacu/seguimiento").status_code == 404
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Rows that reference a parent by the source's own id (a biopsy's `mast_id`,
|
||||
a hospital table's `pac_id`) must land on the right parent, whatever order or
|
||||
numbering the parents arrive in."""
|
||||
import base64
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _json(records, target, mapping=None):
|
||||
mapping = mapping or {k: k for k in records[0]}
|
||||
return {"source_type": "json", "target": target, "column_mapping": mapping,
|
||||
"payload": {"file_base64": base64.b64encode(json.dumps(records).encode()).decode()}}
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def client(wire_domain):
|
||||
wire_domain("cama")
|
||||
from webapi import create_app
|
||||
|
||||
app = create_app()
|
||||
app.config.update(TESTING=True)
|
||||
with app.test_client() as test_client:
|
||||
yield test_client
|
||||
|
||||
|
||||
def test_biopsy_keeps_pointing_at_its_mammogram(client):
|
||||
pacientes = [{"pac_id": 70, "pac_id_hospital": "SRC-A", "pac_fecha_nacimiento": "1970-01-01"},
|
||||
{"pac_id": 50, "pac_id_hospital": "SRC-B", "pac_fecha_nacimiento": "1971-01-01"}]
|
||||
# Hospital ids out of insertion order: an auto-numbered table would swap them.
|
||||
mastografias = [{"mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B", "mast_birads": "B4"},
|
||||
{"mast_id": 901, "pac_id": 70, "pac_id_hospital": "SRC-A", "mast_birads": "B1"}]
|
||||
biopsias = [{"bx_id": 1, "mast_id": 902, "pac_id": 50, "pac_id_hospital": "SRC-B"}]
|
||||
sources = [_json(pacientes, "cama.Paciente"), _json(mastografias, "cama.Mastografia"),
|
||||
_json(biopsias, "cama.BiopsiaMama", {"mast_id": "mast_id", "pac_id": "pac_id", "pac_id_hospital": "pac_id_hospital"})]
|
||||
body = client.post("/imports/commit", json={"sources": sources}).get_json()
|
||||
assert all(r["rejected"] == 0 for r in body["results"]), body
|
||||
|
||||
from persistance.cama import biopsia_mama_repository, mastografia_repository, paciente_repository
|
||||
|
||||
pacientes = {p.pac_id_hospital: p.pac_id for p in paciente_repository.list()}
|
||||
assert pacientes == {"SRC-A": 70, "SRC-B": 50}
|
||||
biopsia = biopsia_mama_repository.list()[0]
|
||||
mamografia = mastografia_repository.get(biopsia.mast_id)
|
||||
assert mamografia.pac_id == biopsia.pac_id == 50
|
||||
|
||||
|
||||
def test_natural_key_wins_over_a_foreign_internal_id(client):
|
||||
"""The patient came from a CSV without ids; the hospital table sends its own pac_id."""
|
||||
pacientes = [{"pac_id_hospital": "CSV-1", "pac_fecha_nacimiento": "1980-01-01"}]
|
||||
client.post("/imports/commit", json={"sources": [_json(pacientes, "cama.Paciente")]})
|
||||
notas = [{"pac_id": 999, "pac_id_hospital": "CSV-1", "nm_id_hospital": "N-1"}]
|
||||
result = client.post("/imports/commit", json={"sources": [_json(notas, "cama.NotaMedica")]}).get_json()["results"][0]
|
||||
assert result["created"] == 1, result
|
||||
assert result["linked"] == {"pac_id": 1}
|
||||
|
||||
from persistance.cama import nota_medica_repository, paciente_repository
|
||||
|
||||
paciente = next(p for p in paciente_repository.list() if p.pac_id_hospital == "CSV-1")
|
||||
nota = next(n for n in nota_medica_repository.list() if n.nm_id_hospital == "N-1")
|
||||
assert nota.pac_id == paciente.pac_id != 999
|
||||
@@ -10,7 +10,9 @@ from webapi.blueprints.cama import cama_bp
|
||||
from webapi.blueprints.data import data_bp
|
||||
from webapi.blueprints.governance import governance_bp
|
||||
from webapi.blueprints.imports import imports_bp
|
||||
from webapi.blueprints.reportes import reportes_bp
|
||||
from webapi.blueprints.tea import tea_bp
|
||||
from webapi.seguimiento import blueprint_de_seguimiento, en_dev
|
||||
|
||||
|
||||
class IsoJSONProvider(DefaultJSONProvider):
|
||||
@@ -74,5 +76,11 @@ def create_app() -> Flask:
|
||||
app.register_blueprint(imports_bp, url_prefix="/imports")
|
||||
app.register_blueprint(data_bp, url_prefix="/data")
|
||||
app.register_blueprint(governance_bp, url_prefix="/governance")
|
||||
app.register_blueprint(reportes_bp, url_prefix="/reportes")
|
||||
# Patient-level follow-up list: only in DEV, with simulated data.
|
||||
if en_dev():
|
||||
from persistance.db import get_cacu_session
|
||||
|
||||
app.register_blueprint(blueprint_de_seguimiento(get_cacu_session), url_prefix="/cacu")
|
||||
|
||||
return app
|
||||
|
||||
@@ -6,6 +6,7 @@ from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from extraction import BBox, ExtractionError
|
||||
from extraction.readers import reader_for
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.imports.connectors import ConnectorError, build_connector, catalog, connector_class, kind_for_filename
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.pdf import PdfConnector
|
||||
@@ -18,6 +19,7 @@ from webapi.imports.services.import_service import (
|
||||
serialize_errors,
|
||||
validate_source,
|
||||
)
|
||||
from webapi.indicadores_vivos import ColaDeRecalculo
|
||||
from webapi.imports.services.introspection_service import (
|
||||
detect_pdf,
|
||||
document_report,
|
||||
@@ -83,6 +85,15 @@ def _form_json(key: str, default=None):
|
||||
raise BadRequest(f"{key} must be JSON: {exc}") from exc
|
||||
|
||||
|
||||
def _outcome(exc: Exception) -> str:
|
||||
"""How an attempt that raised is logged."""
|
||||
if isinstance(exc, ImportRequestError) and str(exc).startswith("the database refused"):
|
||||
return "rechazada_por_la_base"
|
||||
if isinstance(exc, (BadRequest, ConnectorError, ExtractionError, ImportRequestError)):
|
||||
return "solicitud_invalida"
|
||||
return "fallida"
|
||||
|
||||
|
||||
# -- catalog -------------------------------------------------------------------
|
||||
|
||||
|
||||
@@ -267,7 +278,17 @@ def document_page_image():
|
||||
|
||||
@imports_bp.post("/validate")
|
||||
def validate():
|
||||
result = validate_source(_require(_json_body(), "source"))
|
||||
source = _require(_json_body(), "source")
|
||||
audit = import_audit.ImportAudit("validacion")
|
||||
try:
|
||||
result = validate_source(source, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
return jsonify(
|
||||
{
|
||||
"total_rows": result.total_rows,
|
||||
@@ -284,14 +305,26 @@ def commit():
|
||||
With `merge_duplicates`, rows of different sources sharing a natural key
|
||||
are combined into one record before writing."""
|
||||
body = _json_body()
|
||||
results = commit_sources(
|
||||
_require(body, "sources"),
|
||||
on_conflict=body.get("on_conflict", "reject"),
|
||||
merge=bool(body.get("merge_duplicates", False)),
|
||||
)
|
||||
on_conflict = body.get("on_conflict", "reject")
|
||||
merge = bool(body.get("merge_duplicates", False))
|
||||
audit = import_audit.ImportAudit("carga", {"on_conflict": on_conflict, "merge_duplicates": merge})
|
||||
try:
|
||||
results = commit_sources(_require(body, "sources"), on_conflict=on_conflict, merge=merge, audit=audit)
|
||||
except Exception as exc:
|
||||
audit.fail(exc, _outcome(exc))
|
||||
raise
|
||||
else:
|
||||
audit.succeed()
|
||||
finally:
|
||||
import_audit.record(audit)
|
||||
written = sum(r.created + r.updated for r in results)
|
||||
if written and audit.domain:
|
||||
ColaDeRecalculo().solicitar(audit.domain)
|
||||
return jsonify(
|
||||
{
|
||||
"ok": all(r.rejected == 0 for r in results),
|
||||
"audit_id": audit.id,
|
||||
"indicadores_en_recalculo": bool(written and audit.domain),
|
||||
"results": [
|
||||
{
|
||||
"target": r.target,
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Aggregate reports: the log of import attempts and the state of the live
|
||||
indicator recomputation. Nothing here returns row-level data."""
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
|
||||
from webapi.imports import audit as import_audit
|
||||
from webapi.indicadores_vivos import DOMINIOS, ColaDeRecalculo
|
||||
|
||||
reportes_bp = Blueprint("reportes", __name__)
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones")
|
||||
def importaciones():
|
||||
"""Totals per target over every logged attempt, plus the latest attempts
|
||||
(`?limite=50`, newest first; `?dominio=cacu` to filter)."""
|
||||
records = import_audit.default_sink().read()
|
||||
domain = request.args.get("dominio")
|
||||
if domain:
|
||||
records = [r for r in records if r.get("dominio") == domain]
|
||||
try:
|
||||
limit = max(0, int(request.args.get("limite", 50)))
|
||||
except ValueError:
|
||||
return jsonify({"error": "limite debe ser un número"}), 400
|
||||
return jsonify({"resumen": import_audit.summarize(records), "intentos": list(reversed(records))[:limit]})
|
||||
|
||||
|
||||
@reportes_bp.get("/importaciones/descarga")
|
||||
def importaciones_descarga():
|
||||
"""The raw log, one JSON object per line."""
|
||||
sink = import_audit.default_sink()
|
||||
body = sink.path.read_bytes() if sink.path.exists() else b""
|
||||
return Response(
|
||||
body,
|
||||
mimetype="application/x-ndjson",
|
||||
headers={"Content-Disposition": "attachment; filename=importaciones.jsonl"},
|
||||
)
|
||||
|
||||
|
||||
@reportes_bp.get("/indicadores")
|
||||
def indicadores_estado():
|
||||
"""Per domain: state of the last recomputation and whether another is pending."""
|
||||
return jsonify(ColaDeRecalculo().estado())
|
||||
|
||||
|
||||
@reportes_bp.post("/indicadores/<dominio>/recalcular")
|
||||
def indicadores_recalcular(dominio: str):
|
||||
if dominio not in DOMINIOS:
|
||||
return jsonify({"error": f"dominio desconocido: {dominio}"}), 404
|
||||
ColaDeRecalculo().solicitar(dominio)
|
||||
return jsonify({"pendiente": True}), 202
|
||||
@@ -0,0 +1,341 @@
|
||||
"""Aggregate log of every import attempt (validations and commits).
|
||||
|
||||
Each attempt becomes one JSON line in `importaciones.jsonl` under
|
||||
`WEBAPI_REPORT_DIR`. A record only carries counts, field names, source
|
||||
column names and value *shapes* ("9999-99-99" for a date in an unexpected
|
||||
format): never a row, a file name, a connection string or an identifier.
|
||||
A rejected catalog value is written verbatim only when at least
|
||||
`WEBAPI_REPORT_MIN_COUNT` rows share it, so a rare (identifying) value never
|
||||
appears.
|
||||
|
||||
`ImportAudit` collects the facts while the import runs; an `AuditSink`
|
||||
decides where the finished record goes.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
from abc import ABC, abstractmethod
|
||||
from collections import Counter, defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Iterable
|
||||
|
||||
from webapi.imports.schemas.classify import ErrorCategory
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from webapi.imports.schemas.service import BatchValidationResult
|
||||
from webapi.imports.services.import_service import ImportSource
|
||||
|
||||
SCHEMA_VERSION = 1
|
||||
_SHAPE_MAX = 40
|
||||
_MESSAGE_MAX = 300
|
||||
_QUOTED = re.compile(r"'[^']*'|\"[^\"]*\"")
|
||||
# A "column name" that is really a value: a file without a header row makes
|
||||
# its first record the header. Dates, numbers, codes such as "N-0001", long
|
||||
# text or prose are logged by shape only.
|
||||
_VALUE_LIKE = re.compile(r"^[\d\s./:-]+$|\d{4,}|^[A-Za-z]{0,3}[-_ ]?\d+$|@")
|
||||
|
||||
|
||||
def report_dir() -> Path:
|
||||
return Path(os.environ.get("WEBAPI_REPORT_DIR", "reportes"))
|
||||
|
||||
|
||||
def min_count() -> int:
|
||||
return int(os.environ.get("WEBAPI_REPORT_MIN_COUNT", "5"))
|
||||
|
||||
|
||||
def value_shape(value: Any) -> str:
|
||||
"""Letters become `A`, digits `9`; punctuation and spaces stay. Tells the
|
||||
format of a value without its content."""
|
||||
text = str(value)
|
||||
shape = "".join("9" if c.isdigit() else "A" if c.isalpha() else c for c in text[:_SHAPE_MAX])
|
||||
return shape + ("…" if len(text) > _SHAPE_MAX else "")
|
||||
|
||||
|
||||
def column_label(name: Any) -> str:
|
||||
"""A source column name as it can be logged: verbatim when it looks like a
|
||||
header, its shape when it looks like data."""
|
||||
text = str(name).strip()
|
||||
if len(text) > _SHAPE_MAX or text.count(" ") > 3 or _VALUE_LIKE.search(text):
|
||||
return value_shape(text)
|
||||
return text
|
||||
|
||||
|
||||
def sanitize_message(message: str) -> str:
|
||||
"""Error messages from drivers and parsers may quote values (MySQL's
|
||||
"Duplicate entry 'N-0001'"); quoted text is dropped."""
|
||||
return _QUOTED.sub("'…'", str(message))[:_MESSAGE_MAX]
|
||||
|
||||
|
||||
def _blank(value: Any) -> bool:
|
||||
return value is None or (isinstance(value, str) and not value.strip())
|
||||
|
||||
|
||||
def _source_origin(source: ImportSource) -> dict[str, Any]:
|
||||
"""What kind of source it was, without names, hosts or credentials."""
|
||||
payload = source.payload
|
||||
origin: dict[str, Any] = {"tipo": source.source_type}
|
||||
files = payload.get("files")
|
||||
if isinstance(files, list):
|
||||
names = [f.get("name") or "" for f in files if isinstance(f, dict)]
|
||||
else:
|
||||
names = [(payload.get("options") or {}).get("file_name") or payload.get("file_name") or ""]
|
||||
extensions = sorted({Path(n).suffix.lower() for n in names if Path(n).suffix})
|
||||
if extensions:
|
||||
origin["extensiones"] = extensions
|
||||
if isinstance(files, list):
|
||||
origin["archivos"] = len(files)
|
||||
if source.source_type == "sql":
|
||||
server = payload.get("server") if isinstance(payload.get("server"), dict) else {}
|
||||
scheme = str(payload.get("connection_string") or "").split(":", 1)[0].split("+", 1)[0]
|
||||
origin["motor"] = server.get("engine") or scheme or None
|
||||
origin["consulta_propia"] = bool(payload.get("query"))
|
||||
return origin
|
||||
|
||||
|
||||
@dataclass
|
||||
class _FieldStats:
|
||||
with_value: int = 0
|
||||
empty: int = 0
|
||||
errors: Counter = field(default_factory=Counter)
|
||||
shapes: Counter = field(default_factory=Counter)
|
||||
catalog_values: Counter = field(default_factory=Counter)
|
||||
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
out: dict[str, Any] = {"con_valor": self.with_value, "vacios": self.empty}
|
||||
if self.errors:
|
||||
out["errores"] = dict(self.errors)
|
||||
if self.shapes:
|
||||
out["formatos_rechazados"] = dict(self.shapes.most_common(10))
|
||||
frequent = {v: n for v, n in self.catalog_values.most_common(20) if n >= threshold}
|
||||
if frequent:
|
||||
out["valores_fuera_de_catalogo"] = frequent
|
||||
rare = sum(n for n in self.catalog_values.values() if n < threshold)
|
||||
if rare:
|
||||
out["valores_fuera_de_catalogo_poco_frecuentes"] = rare
|
||||
return out
|
||||
|
||||
|
||||
class _SourceAudit:
|
||||
def __init__(self, source: ImportSource):
|
||||
self.source = source
|
||||
self.fields: dict[str, _FieldStats] = defaultdict(_FieldStats)
|
||||
self.rows: dict[str, Any] = {"leidas": 0}
|
||||
self.links: dict[str, int] = {}
|
||||
self.warnings: Counter = Counter()
|
||||
|
||||
def observe_rows(self, rows: Iterable[dict[str, Any] | None]) -> None:
|
||||
mapped = set(self.source.column_mapping.values()) | set(self.source.defaults)
|
||||
merged = 0
|
||||
for row in rows:
|
||||
self.rows["leidas"] += 1
|
||||
if row is None:
|
||||
merged += 1
|
||||
continue
|
||||
for name in mapped:
|
||||
stats = self.fields[name]
|
||||
if _blank(row.get(name)):
|
||||
stats.empty += 1
|
||||
else:
|
||||
stats.with_value += 1
|
||||
if merged:
|
||||
self.rows["combinadas_con_otra_fuente"] = merged
|
||||
|
||||
def observe_validation(self, validation: BatchValidationResult) -> None:
|
||||
self.rows["validas"] = validation.valid_count
|
||||
self.rows["rechazadas_en_validacion"] = validation.error_count
|
||||
for row_errors in validation.rejected:
|
||||
for error in row_errors.errors:
|
||||
stats = self.fields[error.field]
|
||||
stats.errors[error.category.value] += 1
|
||||
if _blank(error.raw_value):
|
||||
continue
|
||||
if error.category is ErrorCategory.OUT_OF_CATALOG and len(str(error.raw_value)) <= _SHAPE_MAX:
|
||||
stats.catalog_values[str(error.raw_value).strip().upper()] += 1
|
||||
elif error.category in (ErrorCategory.TYPE_INVALID, ErrorCategory.UNKNOWN, ErrorCategory.OUT_OF_CATALOG):
|
||||
stats.shapes[value_shape(error.raw_value)] += 1
|
||||
|
||||
def observe_write(self, *, created: int, updated: int, conflicts: int, linked: dict[str, int]) -> None:
|
||||
self.rows.update(insertadas=created, actualizadas=updated, rechazadas_por_conflicto=conflicts)
|
||||
self.links = dict(linked)
|
||||
|
||||
def observe_warnings(self, warnings: Iterable[dict[str, Any]]) -> None:
|
||||
for warning in warnings:
|
||||
self.warnings[f"{warning.get('category')}:{warning.get('field')}"] += 1
|
||||
|
||||
def as_dict(self, threshold: int) -> dict[str, Any]:
|
||||
spec_fields = self.source.spec.schema.model_fields
|
||||
required = {name for name, info in spec_fields.items() if info.is_required()}
|
||||
mapped = set(self.source.column_mapping.values())
|
||||
fixed = set(self.source.defaults)
|
||||
out: dict[str, Any] = {
|
||||
"destino": self.source.target,
|
||||
"origen": _source_origin(self.source),
|
||||
"mapeo": {
|
||||
"columnas_origen": sorted(column_label(c) for c in self.source.column_mapping),
|
||||
"campos_mapeados": sorted(mapped),
|
||||
"campos_con_valor_fijo": sorted(fixed),
|
||||
"campos_sin_mapear": sorted(set(spec_fields) - mapped - fixed),
|
||||
"requeridos_sin_mapear": sorted(required - mapped - fixed),
|
||||
},
|
||||
"filas": self.rows,
|
||||
"campos": {name: stats.as_dict(threshold) for name, stats in sorted(self.fields.items())},
|
||||
}
|
||||
if self.links:
|
||||
out["vinculos_resueltos"] = self.links
|
||||
if self.warnings:
|
||||
out["advertencias"] = dict(self.warnings)
|
||||
return out
|
||||
|
||||
|
||||
class ImportAudit:
|
||||
"""The aggregate record of one attempt. `operation` is "validacion" or "carga"."""
|
||||
|
||||
def __init__(self, operation: str, options: dict[str, Any] | None = None):
|
||||
self.id = str(uuid.uuid4())
|
||||
self.operation = operation
|
||||
self.options = options or {}
|
||||
self.started = time.monotonic()
|
||||
self.date = datetime.now(timezone.utc)
|
||||
self.sources: list[_SourceAudit] = []
|
||||
self.outcome = "en_curso"
|
||||
self.error: dict[str, str] | None = None
|
||||
|
||||
def source(self, source: ImportSource) -> _SourceAudit:
|
||||
audit = _SourceAudit(source)
|
||||
self.sources.append(audit)
|
||||
return audit
|
||||
|
||||
def succeed(self, outcome: str = "completada") -> None:
|
||||
self.outcome = outcome
|
||||
|
||||
def fail(self, exc: BaseException, outcome: str = "fallida") -> None:
|
||||
self.outcome = outcome
|
||||
self.error = {"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}
|
||||
|
||||
@property
|
||||
def domain(self) -> str | None:
|
||||
return self.sources[0].source.domain if self.sources else None
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
threshold = min_count()
|
||||
record: dict[str, Any] = {
|
||||
"version": SCHEMA_VERSION,
|
||||
"id": self.id,
|
||||
"fecha": self.date.isoformat(timespec="seconds"),
|
||||
"operacion": self.operation,
|
||||
"dominio": self.domain,
|
||||
"resultado": self.outcome,
|
||||
"duracion_s": round(time.monotonic() - self.started, 2),
|
||||
"opciones": self.options,
|
||||
"fuentes": [s.as_dict(threshold) for s in self.sources],
|
||||
}
|
||||
if self.error:
|
||||
record["error"] = self.error
|
||||
totals = Counter()
|
||||
for s in self.sources:
|
||||
for key, value in s.rows.items():
|
||||
totals[key] += value
|
||||
record["totales"] = dict(totals)
|
||||
return record
|
||||
|
||||
|
||||
class AuditSink(ABC):
|
||||
@abstractmethod
|
||||
def write(self, record: dict[str, Any]) -> None: ...
|
||||
|
||||
@abstractmethod
|
||||
def read(self) -> list[dict[str, Any]]: ...
|
||||
|
||||
|
||||
class JsonlAuditSink(AuditSink):
|
||||
"""One JSON object per line; appends are locked so several gunicorn
|
||||
workers can share the file."""
|
||||
|
||||
def __init__(self, path: Path):
|
||||
self.path = path
|
||||
|
||||
def write(self, record: dict[str, Any]) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
line = json.dumps(record, ensure_ascii=False, default=str) + "\n"
|
||||
with open(self.path, "a", encoding="utf-8") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
handle.write(line)
|
||||
finally:
|
||||
fcntl.flock(handle, fcntl.LOCK_UN)
|
||||
|
||||
def read(self) -> list[dict[str, Any]]:
|
||||
if not self.path.exists():
|
||||
return []
|
||||
records = []
|
||||
with open(self.path, encoding="utf-8") as handle:
|
||||
for line in handle:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
records.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return records
|
||||
|
||||
|
||||
def default_sink() -> AuditSink:
|
||||
return JsonlAuditSink(report_dir() / "importaciones.jsonl")
|
||||
|
||||
|
||||
def record(audit: ImportAudit, sink: AuditSink | None = None) -> None:
|
||||
"""Writes the record; a full disk must not turn a successful import into an error."""
|
||||
try:
|
||||
(sink or default_sink()).write(audit.as_dict())
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def summarize(records: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
"""Totals per target over every logged attempt: how many rows arrived,
|
||||
how many were written, and which fields failed most and how."""
|
||||
by_target: dict[str, dict[str, Any]] = {}
|
||||
attempts = Counter()
|
||||
for rec in records:
|
||||
attempts[f"{rec.get('operacion')}:{rec.get('resultado')}"] += 1
|
||||
for src in rec.get("fuentes", []):
|
||||
target = by_target.setdefault(
|
||||
src["destino"],
|
||||
{"intentos": 0, "cargas_completadas": 0, "filas": Counter(), "errores_por_campo": defaultdict(Counter),
|
||||
"formatos_rechazados": defaultdict(Counter), "requeridos_sin_mapear": Counter(), "origenes": Counter()},
|
||||
)
|
||||
target["intentos"] += 1
|
||||
if rec.get("operacion") == "carga" and rec.get("resultado") == "completada":
|
||||
target["cargas_completadas"] += 1
|
||||
for key, value in src.get("filas", {}).items():
|
||||
target["filas"][key] += value
|
||||
target["origenes"][src.get("origen", {}).get("tipo") or "?"] += 1
|
||||
for name in src.get("mapeo", {}).get("requeridos_sin_mapear", []):
|
||||
target["requeridos_sin_mapear"][name] += 1
|
||||
for name, stats in src.get("campos", {}).items():
|
||||
target["errores_por_campo"][name].update(stats.get("errores", {}))
|
||||
target["formatos_rechazados"][name].update(stats.get("formatos_rechazados", {}))
|
||||
return {
|
||||
"intentos": dict(attempts),
|
||||
"ultimo": records[-1]["fecha"] if records else None,
|
||||
"destinos": {
|
||||
key: {
|
||||
"intentos": t["intentos"],
|
||||
"cargas_completadas": t["cargas_completadas"],
|
||||
"filas_en_cargas_completadas": dict(t["filas"]),
|
||||
"origenes": dict(t["origenes"]),
|
||||
"requeridos_sin_mapear": dict(t["requeridos_sin_mapear"]),
|
||||
"errores_por_campo": {k: dict(v) for k, v in t["errores_por_campo"].items() if v},
|
||||
"formatos_rechazados": {k: dict(v.most_common(10)) for k, v in t["formatos_rechazados"].items() if v},
|
||||
}
|
||||
for key, t in sorted(by_target.items())
|
||||
},
|
||||
}
|
||||
@@ -17,6 +17,9 @@ _RESULTADO_VPH_CATALOG = Catalog(ResultadoVPH)
|
||||
|
||||
|
||||
class CitologiaCervicalImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
cit_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: Optional[int] = None
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Import schema for `core.cacu.models.EpisodioClinico`.
|
||||
|
||||
`nm_id` and `episodio_anterior_id` are true internal surrogate foreign keys
|
||||
with no natural-key sibling column on this table (unlike `pac_id`/
|
||||
`pac_id_hospital` or `ord_id`/`ord_numero_hospital`), so `LinkResolver` has
|
||||
no way to fill them from an external source. They stay out of this schema;
|
||||
per the model's own docstring, linking an episode to the note/order it came
|
||||
from and to its predecessor is the job of the not-yet-built IND-02/IND-03
|
||||
episode-correlation logic, not a plain field-mapping import.
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cacu.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
@@ -12,6 +12,9 @@ _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: int
|
||||
|
||||
@@ -15,6 +15,9 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Import schema for `core.cama.models.EpisodioClinico`. Same structure as
|
||||
`webapi.imports.schemas.cacu.episodio_clinico.EpisodioClinicoImportSchema`
|
||||
(see its docstring for why `nm_id`/`episodio_anterior_id` are excluded).
|
||||
"""
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.cama.enums import ESPECIALIDAD_ALIAS, Especialidad, TIPO_EPISODIO_ALIAS, TipoEpisodio
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, HospitalId, coerce_date, required_str
|
||||
|
||||
_TIPO_EPISODIO_CATALOG = Catalog(TipoEpisodio, TIPO_EPISODIO_ALIAS)
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad, ESPECIALIDAD_ALIAS)
|
||||
|
||||
|
||||
class EpisodioClinicoImportSchema(ImportSchema):
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
tipo_episodio: CatalogValue(_TIPO_EPISODIO_CATALOG) = None
|
||||
cie10_codigo: Optional[str] = None
|
||||
especialidad_medica: CatalogValue(_ESPECIALIDAD_CATALOG) = None
|
||||
evento_fecha: Optional[date] = None
|
||||
ventana_inicio: Optional[date] = None
|
||||
ventana_fin: Optional[date] = None
|
||||
|
||||
@field_validator("pac_id_hospital", mode="before")
|
||||
@classmethod
|
||||
def _required_pac_id_hospital(cls, v):
|
||||
return required_str(v, field_name="pac_id_hospital")
|
||||
|
||||
@field_validator("evento_fecha", "ventana_inicio", "ventana_fin", mode="before")
|
||||
@classmethod
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
@@ -12,6 +12,9 @@ _BIRADS_CATALOG = Catalog(BIRADS, BIRADS_ALIAS)
|
||||
|
||||
|
||||
class MastografiaImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
mast_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_id: Optional[int] = None
|
||||
|
||||
@@ -12,6 +12,9 @@ _TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
|
||||
|
||||
class OrdenesEstudioImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
ord_id: Optional[int] = None
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
ord_numero_hospital: int
|
||||
|
||||
@@ -15,6 +15,9 @@ _SEXO_BIOLOGICO_CATALOG = Catalog(SexoBiologico, SEXO_BIOLOGICO_ALIAS)
|
||||
|
||||
|
||||
class PacienteImportSchema(ImportSchema):
|
||||
# The source's own id, kept so rows that reference it by id (not by a
|
||||
# natural key) still point at this record.
|
||||
pac_id: Optional[int] = None
|
||||
pac_id_hospital: HospitalId
|
||||
pac_sexo: CatalogValue(_SEXO_BIOLOGICO_CATALOG) = None
|
||||
# IND-01: required, since age at each event of interest is derived from it.
|
||||
|
||||
@@ -31,14 +31,6 @@ def optional_str(v: Any) -> Any:
|
||||
return text or None
|
||||
|
||||
|
||||
def rounded_int(v: Any) -> Any:
|
||||
"""A minutes/count field stored as an `int` column, whose source may
|
||||
report a float (e.g. a duration measured to tenths of a minute)."""
|
||||
if v is None or (isinstance(v, str) and v.strip() == ""):
|
||||
return None
|
||||
return round(float(v))
|
||||
|
||||
|
||||
_DAY_FIRST_FORMATS = ("%d/%m/%Y", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d")
|
||||
|
||||
|
||||
|
||||
@@ -13,11 +13,13 @@ from pydantic import BaseModel
|
||||
from core.cacu.models import BiometriaHematica as CacuBiometriaHematica
|
||||
from core.cacu.models import BiopsiaCervical as CacuBiopsiaCervical
|
||||
from core.cacu.models import CitologiaCervical as CacuCitologiaCervical
|
||||
from core.cacu.models import EpisodioClinico as CacuEpisodioClinico
|
||||
from core.cacu.models import NotaMedica as CacuNotaMedica
|
||||
from core.cacu.models import OrdenesEstudio as CacuOrdenesEstudio
|
||||
from core.cacu.models import Paciente as CacuPaciente
|
||||
from core.cama.models import BiometriaHematica as CamaBiometriaHematica
|
||||
from core.cama.models import BiopsiaMama as CamaBiopsiaMama
|
||||
from core.cama.models import EpisodioClinico as CamaEpisodioClinico
|
||||
from core.cama.models import Mastografia as CamaMastografia
|
||||
from core.cama.models import NotaMedica as CamaNotaMedica
|
||||
from core.cama.models import OrdenesEstudio as CamaOrdenesEstudio
|
||||
@@ -35,11 +37,13 @@ from core.tea.models import PotencialesEvocadosAuditivos as TeaPotencialesEvocad
|
||||
from persistance.cacu import biometria_hematica_repository as cacu_biometria_hematica_repository
|
||||
from persistance.cacu import biopsia_cervical_repository as cacu_biopsia_cervical_repository
|
||||
from persistance.cacu import citologia_cervical_repository as cacu_citologia_cervical_repository
|
||||
from persistance.cacu import episodio_clinico_repository as cacu_episodio_clinico_repository
|
||||
from persistance.cacu import nota_medica_repository as cacu_nota_medica_repository
|
||||
from persistance.cacu import ordenes_estudio_repository as cacu_ordenes_estudio_repository
|
||||
from persistance.cacu import paciente_repository as cacu_paciente_repository
|
||||
from persistance.cama import biometria_hematica_repository as cama_biometria_hematica_repository
|
||||
from persistance.cama import biopsia_mama_repository as cama_biopsia_mama_repository
|
||||
from persistance.cama import episodio_clinico_repository as cama_episodio_clinico_repository
|
||||
from persistance.cama import mastografia_repository as cama_mastografia_repository
|
||||
from persistance.cama import nota_medica_repository as cama_nota_medica_repository
|
||||
from persistance.cama import ordenes_estudio_repository as cama_ordenes_estudio_repository
|
||||
@@ -62,6 +66,9 @@ from webapi.imports.schemas.cacu.biometria_hematica import (
|
||||
)
|
||||
from webapi.imports.schemas.cacu.biopsia_cervical import BiopsiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.citologia_cervical import CitologiaCervicalImportSchema
|
||||
from webapi.imports.schemas.cacu.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CacuEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cacu.nota_medica import NotaMedicaImportSchema as CacuNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cacu.ordenes_estudio import (
|
||||
OrdenesEstudioImportSchema as CacuOrdenesEstudioImportSchema,
|
||||
@@ -71,6 +78,9 @@ from webapi.imports.schemas.cama.biometria_hematica import (
|
||||
BiometriaHematicaImportSchema as CamaBiometriaHematicaImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.biopsia_mama import BiopsiaMamaImportSchema
|
||||
from webapi.imports.schemas.cama.episodio_clinico import (
|
||||
EpisodioClinicoImportSchema as CamaEpisodioClinicoImportSchema,
|
||||
)
|
||||
from webapi.imports.schemas.cama.mastografia import MastografiaImportSchema
|
||||
from webapi.imports.schemas.cama.nota_medica import NotaMedicaImportSchema as CamaNotaMedicaImportSchema
|
||||
from webapi.imports.schemas.cama.ordenes_estudio import (
|
||||
@@ -147,6 +157,14 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=cacu_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cacu.EpisodioClinico": EntitySpec(
|
||||
schema=CacuEpisodioClinicoImportSchema,
|
||||
model=CacuEpisodioClinico,
|
||||
repository=cacu_episodio_clinico_repository,
|
||||
# No hospital-visible identifier of its own, like EvaluacionPsicologica
|
||||
# or PartoNeonatal; a patient can have several episodes.
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.Paciente": EntitySpec(
|
||||
schema=CamaPacienteImportSchema,
|
||||
model=CamaPaciente,
|
||||
@@ -183,6 +201,12 @@ ENTITY_REGISTRY: dict[str, EntitySpec] = {
|
||||
repository=cama_biometria_hematica_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"cama.EpisodioClinico": EntitySpec(
|
||||
schema=CamaEpisodioClinicoImportSchema,
|
||||
model=CamaEpisodioClinico,
|
||||
repository=cama_episodio_clinico_repository,
|
||||
conflict_fields=None,
|
||||
),
|
||||
"tea.OrdenesEstudio": EntitySpec(
|
||||
schema=TeaOrdenesEstudioImportSchema,
|
||||
model=TeaOrdenesEstudio,
|
||||
|
||||
@@ -17,7 +17,7 @@ from core.tea.enums import (
|
||||
TipoGrafoelemento,
|
||||
)
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str, rounded_int
|
||||
from webapi.imports.schemas.coercion import edf_file, Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_FUENTE_INTERPRETACION_EEG_CATALOG = Catalog(FuenteInterpretacionEeg)
|
||||
_ESTADO_REGISTRO_EEG_CATALOG = Catalog(EstadoRegistroEeg)
|
||||
@@ -32,7 +32,7 @@ _CONCLUSION_EEG_CATALOG = Catalog(ConclusionEeg)
|
||||
|
||||
class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_ord_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[str] = None
|
||||
eeg_pac_id: Optional[int] = None
|
||||
eeg_reporte_disponible: Optional[int] = None
|
||||
eeg_fuente_interpretacion: CatalogValue(_FUENTE_INTERPRETACION_EEG_CATALOG) = None
|
||||
eeg_fecha_nacimiento_archivo: Optional[date] = None
|
||||
@@ -45,7 +45,7 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_privacion_sueno: Optional[int] = None
|
||||
eeg_sedacion: Optional[int] = None
|
||||
eeg_sedacion_farmaco: Optional[str] = None
|
||||
eeg_duracion_min: Optional[int] = None
|
||||
eeg_duracion_min: Optional[float] = None
|
||||
eeg_calidad_tecnica: CatalogValue(_CALIDAD_TECNICA_EEG_CATALOG) = None
|
||||
eeg_descripcion_senal: Optional[str] = None
|
||||
eeg_ritmo_base_frecuencia: Optional[float] = None
|
||||
@@ -70,7 +70,7 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
eeg_estudio: Optional[bytes] = None
|
||||
|
||||
@field_validator(
|
||||
"eeg_ord_id", "eeg_pac_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_ord_id", "eeg_medico_interpreta", "eeg_sedacion_farmaco",
|
||||
"eeg_descripcion_senal", "eeg_localizacion", "eeg_conclusion_texto",
|
||||
"eeg_id_registro_laboratorio", "eeg_pdf_ruta", "eeg_nlp_version",
|
||||
mode="before",
|
||||
@@ -84,11 +84,6 @@ class EegEstudioImportSchema(ImportSchema):
|
||||
def _coerce_dates(cls, v):
|
||||
return coerce_date(v)
|
||||
|
||||
@field_validator("eeg_duracion_min", mode="before")
|
||||
@classmethod
|
||||
def _coerce_duracion_min(cls, v):
|
||||
return rounded_int(v)
|
||||
|
||||
@field_validator("eeg_estudio", mode="before")
|
||||
@classmethod
|
||||
def _valid_edf(cls, v):
|
||||
|
||||
@@ -5,12 +5,12 @@ from typing import Optional
|
||||
|
||||
from pydantic import field_validator
|
||||
|
||||
from core.tea.enums import Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from core.tea.enums import TIPO_ESTUDIO_ALIAS, Especialidad, EstatusEstudio, TipoEstudio, VentanaMadurativa
|
||||
from webapi.imports.schemas.base import ImportSchema
|
||||
from webapi.imports.schemas.coercion import Catalog, CatalogValue, coerce_date, optional_str
|
||||
|
||||
_ESPECIALIDAD_CATALOG = Catalog(Especialidad)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio)
|
||||
_TIPO_ESTUDIO_CATALOG = Catalog(TipoEstudio, TIPO_ESTUDIO_ALIAS)
|
||||
_ESTATUS_ESTUDIO_CATALOG = Catalog(EstatusEstudio)
|
||||
_VENTANA_MADURATIVA_CATALOG = Catalog(VentanaMadurativa)
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ from typing import Any, Iterator
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from persistance.repository import ConflictPolicy
|
||||
from webapi.imports.audit import ImportAudit
|
||||
from webapi.imports.connectors import Connector, ConnectorError, build_connector
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
@@ -130,8 +131,16 @@ def _jsonable(value: Any) -> Any:
|
||||
return str(value)
|
||||
|
||||
|
||||
def validate_source(raw_source: dict[str, Any]) -> BatchValidationResult:
|
||||
return ImportSource.parse(raw_source).validate()
|
||||
def validate_source(raw_source: dict[str, Any], audit: ImportAudit | None = None) -> BatchValidationResult:
|
||||
source = ImportSource.parse(raw_source)
|
||||
if audit is None:
|
||||
return source.validate()
|
||||
tracked = audit.source(source)
|
||||
rows = list(source.rows())
|
||||
tracked.observe_rows(rows)
|
||||
validation = validate_rows(source.spec.schema, rows)
|
||||
tracked.observe_validation(validation)
|
||||
return validation
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -215,7 +224,9 @@ def _key_part(value: Any) -> Any:
|
||||
return str(value).strip().upper()
|
||||
|
||||
|
||||
def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -> list[SourceCommitResult]:
|
||||
def commit_sources(
|
||||
raw_sources: Any, *, on_conflict: str, merge: bool = False, audit: ImportAudit | None = None
|
||||
) -> list[SourceCommitResult]:
|
||||
"""Writes a batch in one transaction. With `merge`, rows of different
|
||||
sources sharing a natural key are combined first (see `merge_duplicates`)."""
|
||||
try:
|
||||
@@ -224,6 +235,7 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
raise ImportRequestError(f"invalid on_conflict: {on_conflict!r}") from exc
|
||||
|
||||
sources = _parse_batch(raw_sources)
|
||||
tracked = [audit.source(source) for source in sources] if audit else []
|
||||
if policy is ConflictPolicy.UPSERT:
|
||||
keyless = sorted({s.target for s in sources if not s.spec.conflict_fields})
|
||||
if keyless:
|
||||
@@ -234,6 +246,10 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
rows: list[list[dict[str, Any] | None]] = [list(source.rows()) for source in sources]
|
||||
merged, merge_warnings = merge_duplicates(sources, rows) if merge else ({}, {})
|
||||
validated = [(source, validate_rows(source.spec.schema, source_rows)) for source, source_rows in zip(sources, rows)]
|
||||
for position, source_audit in enumerate(tracked):
|
||||
source_audit.observe_rows(rows[position])
|
||||
source_audit.observe_validation(validated[position][1])
|
||||
source_audit.observe_warnings(merge_warnings.get(position, []))
|
||||
|
||||
session = sources[0].spec.repository.open_session()
|
||||
links = LinkResolver(session)
|
||||
@@ -279,6 +295,11 @@ def commit_sources(raw_sources: Any, *, on_conflict: str, merge: bool = False) -
|
||||
merged=merged.get(position, 0),
|
||||
warnings=merge_warnings.get(position, []),
|
||||
)
|
||||
if tracked:
|
||||
tracked[position].observe_write(
|
||||
created=write.created_count, updated=write.updated_count,
|
||||
conflicts=write.rejected_count, linked=linked,
|
||||
)
|
||||
session.commit()
|
||||
except SQLAlchemyError as exc:
|
||||
session.rollback()
|
||||
|
||||
@@ -55,7 +55,12 @@ def dependency_rank(target_key: str) -> int:
|
||||
class LinkResolver:
|
||||
"""Looks up parent primary keys by natural key within the batch's session,
|
||||
so parents written earlier in the same uncommitted transaction are found.
|
||||
A missing parent leaves the FK null, which Core allows."""
|
||||
|
||||
The natural key wins over an id the source sent: a hospital table carries
|
||||
the hospital's internal ids, which only match ours when the parent was
|
||||
loaded with its own id. An id is kept as sent only when there is no
|
||||
natural key or its parent isn't loaded; a missing parent leaves the FK
|
||||
null, which Core allows."""
|
||||
|
||||
def __init__(self, session: Session):
|
||||
self._session = session
|
||||
@@ -65,12 +70,13 @@ class LinkResolver:
|
||||
linked = []
|
||||
for link in links_for(target_key):
|
||||
value = row.get(link.via_field)
|
||||
if row.get(link.fk_field) is not None or value is None:
|
||||
if value is None:
|
||||
continue
|
||||
pk = self._lookup(link, value)
|
||||
if pk is not None:
|
||||
if row.get(link.fk_field) != pk:
|
||||
linked.append(link.fk_field)
|
||||
row[link.fk_field] = pk
|
||||
linked.append(link.fk_field)
|
||||
return linked
|
||||
|
||||
def _lookup(self, link: ForeignKeyLink, value: Any) -> Any:
|
||||
|
||||
+43
-11
@@ -2,17 +2,22 @@
|
||||
|
||||
`registrar_indicadores` agrega a un blueprint:
|
||||
|
||||
GET /indicadores catálogo de indicadores
|
||||
GET /indicadores catálogo de indicadores (con sus `filtros`)
|
||||
GET /indicadores/<id>/periodos periodos con reporte
|
||||
GET /indicadores/<id>/datos?periodos=&estrato= los números, sin figura
|
||||
GET /indicadores/<id>/datos?periodos=&estrato=&filtro= los números, sin figura
|
||||
GET /indicadores/<id>/metadatos ficha metodológica
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=&filtro=
|
||||
|
||||
Las definiciones salen del kit (`measures_de`), los datos de
|
||||
`indicadores_kit.serving.datos` y las figuras de
|
||||
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||
se traducen los errores a códigos HTTP. La forma de cada respuesta es un
|
||||
contrato con el frontend: no se quita ni se renombra un campo.
|
||||
|
||||
`?filtro=estrato:valor[,estrato:valor]` (T-19f) cuenta lo mismo solo con las
|
||||
unidades que tienen esos valores: el mismo contrato, y en `/datos` la llave
|
||||
`filtros`. Solo se aceptan los filtros que el indicador declara
|
||||
(`extension.filtros`) y los valores de su catálogo; si no, 400.
|
||||
"""
|
||||
|
||||
import json
|
||||
@@ -21,7 +26,8 @@ from collections.abc import Callable
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.registry.measures import Measure, measures_de
|
||||
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.contratos import FiltroNoDeclarado
|
||||
from indicadores_kit.serving.datos import datos_de, filtros_de, metadatos_de, periodos_de, resumen_de
|
||||
from indicadores_kit.serving.figuras import (
|
||||
TEMAS,
|
||||
figura_json,
|
||||
@@ -59,6 +65,21 @@ def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||
|
||||
|
||||
def filtros_pedidos(texto: str | None) -> dict[str, str]:
|
||||
"""`estrato:valor[,estrato:valor]` -> `{estrato: valor}`. Vacío si no se pidió; `ValueError` si viene mal escrito."""
|
||||
if not texto:
|
||||
return {}
|
||||
filtros = {}
|
||||
for parte in texto.split(","):
|
||||
estrato, separador, valor = parte.partition(":")
|
||||
if not separador or not estrato or not valor:
|
||||
raise ValueError(f"filtro mal escrito {parte!r}; use estrato:valor")
|
||||
if estrato in filtros:
|
||||
raise ValueError(f"el filtro {estrato!r} va dos veces")
|
||||
filtros[estrato] = valor
|
||||
return filtros
|
||||
|
||||
|
||||
def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str | None]:
|
||||
"""Los periodos de `?periodos=` y su tipo. Sin parámetro (o vacío): `([], None)`.
|
||||
|
||||
@@ -92,11 +113,16 @@ def registrar_indicadores(
|
||||
|
||||
def listar_indicadores():
|
||||
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||
return _json([
|
||||
resumen_de(id_, medida)
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
# `filtros` (T-24f): los que admite cada uno, con sus valores del catálogo, para armar `?filtro=`.
|
||||
sesion = get_session()
|
||||
try:
|
||||
return _json([
|
||||
{**resumen_de(id_, medida), "filtros": filtros_de(sesion, medida)}
|
||||
for id_, medida in definiciones.items()
|
||||
if not medida.extension.publicacion.oculto
|
||||
])
|
||||
finally:
|
||||
sesion.close()
|
||||
|
||||
def _periodos_o_los_que_haya(sesion: Session, medida: Measure, periodos: list[str]) -> list[str]:
|
||||
"""Los pedidos; sin pedir ninguno, los que tienen reporte del primer tipo que publica."""
|
||||
@@ -139,6 +165,7 @@ def registrar_indicadores(
|
||||
)
|
||||
try:
|
||||
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -147,7 +174,9 @@ def registrar_indicadores(
|
||||
periodos = _periodos_o_los_que_haya(sesion, medida, periodos)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato)
|
||||
datos = datos_de(sesion, medida, periodos, tablas=tablas, estrato=estrato, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
@@ -171,6 +200,7 @@ def registrar_indicadores(
|
||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||
try:
|
||||
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||
filtros = filtros_pedidos(request.args.get("filtro"))
|
||||
except ValueError as error:
|
||||
return _error(str(error), 400)
|
||||
|
||||
@@ -180,7 +210,9 @@ def registrar_indicadores(
|
||||
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||
if not periodos:
|
||||
return _error("el indicador no tiene reportes calculados", 404)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||
texto = figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema, filtros=filtros or None)
|
||||
except FiltroNoDeclarado as error:
|
||||
return _error(str(error), 400)
|
||||
except KeyError:
|
||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||
raise
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Recomputes a domain's indicators after its staging tables change.
|
||||
|
||||
A successful import asks for a recomputation (`ColaDeRecalculo.solicitar`),
|
||||
which only drops a marker file. A separate process (`python -m
|
||||
webapi.indicadores_vivos`, the `indicadores` compose service) picks the
|
||||
markers up and runs that domain's pipeline with Hamilton (`webapi.pipeline`):
|
||||
catalogs -> staging to facts -> views -> registry -> definitions -> reports.
|
||||
Requests that arrive while a domain is running are folded into one more run.
|
||||
|
||||
State lives in files under `INDICADORES_DIR`: `pendiente/<dominio>` markers
|
||||
and `estado.json`; each run is also appended, as counts only, to
|
||||
`indicadores.jsonl` in the import report directory.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message
|
||||
|
||||
DOMINIOS = ("cacu", "cama", "tea")
|
||||
_SUMMARY_MAX = 400
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now(timezone.utc).isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _short(value: Any) -> str:
|
||||
text = str(value)
|
||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||
|
||||
|
||||
class ColaDeRecalculo:
|
||||
"""Marker-file queue and status of the indicator recomputations."""
|
||||
|
||||
def __init__(self, base: Path | None = None):
|
||||
self.base = Path(base or os.environ.get("INDICADORES_DIR", "indicadores"))
|
||||
|
||||
@property
|
||||
def _pending(self) -> Path:
|
||||
return self.base / "pendiente"
|
||||
|
||||
@property
|
||||
def _status_path(self) -> Path:
|
||||
return self.base / "estado.json"
|
||||
|
||||
def solicitar(self, dominio: str) -> None:
|
||||
if dominio not in DOMINIOS:
|
||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||
self._pending.mkdir(parents=True, exist_ok=True)
|
||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
||||
|
||||
def pendientes(self) -> list[str]:
|
||||
if not self._pending.exists():
|
||||
return []
|
||||
return sorted(p.name for p in self._pending.iterdir() if p.name in DOMINIOS)
|
||||
|
||||
def tomar(self, dominio: str) -> bool:
|
||||
"""Consumes the marker; a request made from now on queues one more run."""
|
||||
try:
|
||||
(self._pending / dominio).unlink()
|
||||
return True
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def estado(self) -> dict[str, Any]:
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
pending = set(self.pendientes())
|
||||
return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMINIOS}
|
||||
|
||||
def _guardar_estado(self, dominio: str, entrada: dict[str, Any]) -> None:
|
||||
self.base.mkdir(parents=True, exist_ok=True)
|
||||
lock = self.base / ".estado.lock"
|
||||
with open(lock, "w") as handle:
|
||||
fcntl.flock(handle, fcntl.LOCK_EX)
|
||||
try:
|
||||
status = json.loads(self._status_path.read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
status = {}
|
||||
status[dominio] = entrada
|
||||
tmp = self._status_path.with_suffix(".tmp")
|
||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
tmp.replace(self._status_path)
|
||||
|
||||
def correr(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrar`: the API migrates on startup)."""
|
||||
from orquestacion import Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
|
||||
from webapi.pipeline import correr
|
||||
|
||||
desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5))
|
||||
hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year))
|
||||
inicio = _now()
|
||||
started = time.monotonic()
|
||||
self._guardar_estado(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Contexto(dominio, desde, hasta, permitir_sin_definir=True)
|
||||
nombres = [a.nombre for a in aristas_de(dominio) if a.nombre != "migrar"]
|
||||
pasos = correr(ctx, solo=nombres)
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"arista": p.arista, "segundos": round(p.segundos, 2), "resumen": _short(p.resumen)} for p in pasos],
|
||||
)
|
||||
except Exception as exc: # the worker must survive a failing domain
|
||||
log.exception("recálculo de %s falló", dominio)
|
||||
entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))})
|
||||
entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2))
|
||||
self._guardar_estado(dominio, entrada)
|
||||
try:
|
||||
JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada})
|
||||
except OSError:
|
||||
pass
|
||||
return entrada
|
||||
|
||||
def atender(self) -> list[str]:
|
||||
"""Runs every pending domain once; returns the ones it ran."""
|
||||
ran = []
|
||||
for dominio in self.pendientes():
|
||||
if self.tomar(dominio):
|
||||
self.correr(dominio)
|
||||
ran.append(dominio)
|
||||
return ran
|
||||
|
||||
|
||||
def main() -> None:
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
|
||||
cola = ColaDeRecalculo()
|
||||
interval = float(os.environ.get("INDICADORES_INTERVALO_S", "20"))
|
||||
if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1":
|
||||
for dominio in DOMINIOS:
|
||||
cola.solicitar(dominio)
|
||||
stopping = False
|
||||
|
||||
def _stop(*_):
|
||||
nonlocal stopping
|
||||
stopping = True
|
||||
|
||||
signal.signal(signal.SIGTERM, _stop)
|
||||
signal.signal(signal.SIGINT, _stop)
|
||||
log.info("indicadores en vivo: revisando cada %.0f s en %s", interval, cola.base)
|
||||
while not stopping:
|
||||
for dominio in cola.atender():
|
||||
log.info("%s: %s", dominio, cola.estado()[dominio].get("estado"))
|
||||
for _ in range(int(interval * 10)):
|
||||
if stopping:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Runs a domain's indicator pipeline with Hamilton.
|
||||
|
||||
The steps are the kit's own transformations as Orquestacion declares them
|
||||
(`orquestacion.aristas.aristas_de`): each one names the table groups it reads
|
||||
and writes, and moves data only through the database. Here every step becomes
|
||||
a Hamilton node whose inputs are the steps that write what it reads, so
|
||||
Hamilton orders and runs the graph; nothing of Orquestacion's own executor is
|
||||
used. Steps left out of `solo` are given as overrides and don't run.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import time
|
||||
from dataclasses import dataclass
|
||||
from types import ModuleType
|
||||
from typing import Any, Callable, Sequence
|
||||
|
||||
from hamilton import ad_hoc_utils, driver
|
||||
from orquestacion.arista import Arista, Contexto
|
||||
from orquestacion.aristas import aristas_de
|
||||
from orquestacion.repositorios import repositorios_de
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Paso:
|
||||
"""What a step left: its short summary and how long it took. `None` summary: not run."""
|
||||
|
||||
arista: str
|
||||
resumen: Any
|
||||
segundos: float
|
||||
|
||||
|
||||
def _node(arista: Arista, ctx: Contexto, inputs: Sequence[str]) -> Callable[..., Paso]:
|
||||
def run(**_upstream: Paso) -> Paso:
|
||||
started = time.monotonic()
|
||||
return Paso(arista.nombre, arista.correr(ctx), time.monotonic() - started)
|
||||
|
||||
run.__name__ = arista.nombre
|
||||
run.__doc__ = arista.descripcion
|
||||
run.__annotations__ = {name: Paso for name in inputs} | {"return": Paso}
|
||||
run.__signature__ = inspect.Signature(
|
||||
[inspect.Parameter(name, inspect.Parameter.KEYWORD_ONLY, annotation=Paso) for name in inputs],
|
||||
return_annotation=Paso,
|
||||
)
|
||||
return run
|
||||
|
||||
|
||||
def modulo(ctx: Contexto, aristas: Sequence[Arista]) -> ModuleType:
|
||||
"""The Hamilton module of a domain: one function per step."""
|
||||
writer = {vertex: arista.nombre for arista in aristas for vertex in arista.escribe}
|
||||
nodes = []
|
||||
for arista in aristas:
|
||||
inputs = sorted({writer[v] for v in arista.lee if v in writer and writer[v] != arista.nombre})
|
||||
nodes.append(_node(arista, ctx, inputs))
|
||||
return ad_hoc_utils.create_temporary_module(*nodes)
|
||||
|
||||
|
||||
def correr(ctx: Contexto, *, solo: Sequence[str] | None = None) -> list[Paso]:
|
||||
"""Runs the domain's steps (all, or only `solo`) in dependency order."""
|
||||
if ctx.repos is None:
|
||||
ctx = Contexto(ctx.proyecto, ctx.anio_inicio, ctx.anio_fin, ctx.corte, ctx.permitir_sin_definir,
|
||||
ctx.parametros, repos=repositorios_de(ctx.proyecto))
|
||||
aristas = aristas_de(ctx.proyecto)
|
||||
nombres = [a.nombre for a in aristas]
|
||||
wanted = [n for n in nombres if solo is None or n in solo]
|
||||
skipped = {n: Paso(n, None, 0.0) for n in nombres if n not in wanted}
|
||||
dr = driver.Builder().with_modules(modulo(ctx, aristas)).build()
|
||||
results = dr.execute(wanted, overrides=skipped)
|
||||
return [results[n] for n in _order(dr, wanted)]
|
||||
|
||||
|
||||
def _order(dr: driver.Driver, wanted: Sequence[str]) -> list[str]:
|
||||
"""Topological order of the requested steps, for reporting."""
|
||||
graph = dr.graph
|
||||
order: list[str] = []
|
||||
seen: set[str] = set()
|
||||
|
||||
def visit(name: str) -> None:
|
||||
if name in seen:
|
||||
return
|
||||
seen.add(name)
|
||||
for dependency in graph.nodes[name].dependencies:
|
||||
visit(dependency.name)
|
||||
if name in wanted:
|
||||
order.append(name)
|
||||
|
||||
for name in wanted:
|
||||
visit(name)
|
||||
return order
|
||||
@@ -0,0 +1,68 @@
|
||||
"""La lista de seguimiento de CaCu (T-24d): `GET /cacu/seguimiento`, solo en DEV.
|
||||
|
||||
GET /cacu/seguimiento?corte=AAAA-MM-DD&meses=&estatus=&page=&page_size=
|
||||
|
||||
Es dato por paciente: **solo se registra en DEV** (con `DEV_REVISION`, que define el despliegue de
|
||||
`deploy/dev`) y con datos simulados; toda respuesta lleva `simulado: true`. Fuera de DEV la ruta no
|
||||
existe (404). La lista la arma el kit (`indicadores_kit.serving.seguimiento`); aquí solo se valida,
|
||||
se abre la sesión y se traducen los errores. El contrato: `_docs/contratos/cacu_seguimiento_y_estratos.md` §2.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
from collections.abc import Callable
|
||||
from datetime import date
|
||||
|
||||
from flask import Blueprint, Response, jsonify, request
|
||||
from indicadores_kit.serving.seguimiento import PaginaFuera, PedidoInvalido, seguimiento_de
|
||||
from sqlmodel import Session
|
||||
|
||||
FECHA = re.compile(r"\d{4}-\d{2}-\d{2}")
|
||||
SAL_POR_OMISION = "dev-simulado" # los datos de DEV son simulados; con datos reales, la sal sale del entorno
|
||||
|
||||
|
||||
def en_dev() -> bool:
|
||||
"""Si esta WebApi corre en el despliegue de DEV (`deploy/dev/compose.yml` define `DEV_REVISION`)."""
|
||||
return bool(os.environ.get("DEV_REVISION"))
|
||||
|
||||
|
||||
def blueprint_de_seguimiento(get_session: Callable[[], Session]) -> Blueprint:
|
||||
"""El blueprint de la lista, para registrarlo con `url_prefix="/cacu"` solo en DEV."""
|
||||
blueprint = Blueprint("cacu_seguimiento", __name__)
|
||||
|
||||
@blueprint.get("/seguimiento")
|
||||
def get_seguimiento():
|
||||
try:
|
||||
pedido = _pedido(request.args)
|
||||
except ValueError as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
sesion = get_session()
|
||||
try:
|
||||
cuerpo = seguimiento_de(sesion, sal=os.environ.get("SEGUIMIENTO_SAL", SAL_POR_OMISION), **pedido)
|
||||
except PedidoInvalido as error:
|
||||
return jsonify({"error": str(error)}), 400
|
||||
except PaginaFuera as error:
|
||||
return jsonify({"error": str(error)}), 404
|
||||
finally:
|
||||
sesion.close()
|
||||
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
||||
|
||||
return blueprint
|
||||
|
||||
|
||||
def _pedido(args) -> dict:
|
||||
"""Los parámetros de la consulta, con su tipo. `ValueError` si uno viene mal escrito."""
|
||||
pedido = {}
|
||||
if corte := args.get("corte"):
|
||||
if not FECHA.fullmatch(corte):
|
||||
raise ValueError(f"corte mal escrito {corte!r}; use AAAA-MM-DD")
|
||||
pedido["corte"] = date.fromisoformat(corte)
|
||||
for nombre in ("meses", "page", "page_size"):
|
||||
if (texto := args.get(nombre)) not in (None, ""):
|
||||
if not texto.isdigit():
|
||||
raise ValueError(f"{nombre} debe ser un entero; llegó {texto!r}")
|
||||
pedido[nombre] = int(texto)
|
||||
if estatus := args.get("estatus"):
|
||||
pedido["estatus"] = estatus
|
||||
return pedido
|
||||
Reference in New Issue
Block a user