Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a2727f06ad | |||
| b660c77191 | |||
| a15ca94564 | |||
| 9c0bff0cfe | |||
| 8bc0b06e7b | |||
| 830d978a1b | |||
| b89b630c2e |
@@ -11,7 +11,7 @@ WebApi/
|
|||||||
├── main.py crea la app y la levanta en 0.0.0.0:5000
|
├── main.py crea la app y la levanta en 0.0.0.0:5000
|
||||||
├── webapi/
|
├── webapi/
|
||||||
│ ├── __init__.py create_app(): /health y los tres blueprints
|
│ ├── __init__.py create_app(): /health y los tres blueprints
|
||||||
│ ├── indicadores.py rutas de indicadores y figuras, comunes a los tres proyectos
|
│ ├── indicadores.py rutas de indicadores, datos y figuras, comunes a los tres proyectos
|
||||||
│ └── blueprints/
|
│ └── blueprints/
|
||||||
│ ├── cacu.py cacu_bp, prefijo /cacu
|
│ ├── cacu.py cacu_bp, prefijo /cacu
|
||||||
│ ├── cama.py cama_bp, prefijo /cama
|
│ ├── cama.py cama_bp, prefijo /cama
|
||||||
@@ -29,7 +29,8 @@ WebApi/
|
|||||||
Un blueprint por dominio, con rutas de ejemplo (paciente y `predict`).
|
Un blueprint por dominio, con rutas de ejemplo (paciente y `predict`).
|
||||||
Los tres sirven además los indicadores del kit: cada blueprint llama a
|
Los tres sirven además los indicadores del kit: cada blueprint llama a
|
||||||
`registrar_indicadores(blueprint, proyecto, get_<proyecto>_session)` de
|
`registrar_indicadores(blueprint, proyecto, get_<proyecto>_session)` de
|
||||||
`webapi/indicadores.py`, que agrega `/indicadores` y las figuras.
|
`webapi/indicadores.py`, que agrega el catálogo, los periodos, los datos,
|
||||||
|
los metadatos y las figuras.
|
||||||
|
|
||||||
## Flujo de datos
|
## Flujo de datos
|
||||||
|
|
||||||
@@ -49,7 +50,9 @@ GET /<proyecto>/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
|||||||
├─ valida indicador y figura (404 si no existen; figuras_de(medida))
|
├─ valida indicador y figura (404 si no existen; figuras_de(medida))
|
||||||
├─ valida tema y periodos (400 si están mal)
|
├─ valida tema y periodos (400 si están mal)
|
||||||
├─ sesion = get_<proyecto>_session()
|
├─ sesion = get_<proyecto>_session()
|
||||||
├─ sin periodos: periodos_con_reporte(..., tipo=<primer tipo que publica>)
|
├─ sin periodos: periodos_por_defecto(...): los del primer tipo que publica;
|
||||||
|
│ en una figura de un solo periodo (donas, barras), solo el más reciente
|
||||||
|
│ con algo que dibujar
|
||||||
├─ figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
├─ figura_json(sesion, medida, periodos, figura, tablas=tablas, tema=tema)
|
||||||
│ (indicadores_kit lee measure_report y arma el JSON de Plotly)
|
│ (indicadores_kit lee measure_report y arma el JSON de Plotly)
|
||||||
└─ finally: sesion.close()
|
└─ finally: sesion.close()
|
||||||
@@ -58,6 +61,10 @@ GET /<proyecto>/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
|||||||
Response(texto, mimetype="application/json")
|
Response(texto, mimetype="application/json")
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Las rutas de datos, periodos y metadatos siguen los mismos pasos, con
|
||||||
|
`datos_de`, `periodos_de` y `metadatos_de` de
|
||||||
|
`indicadores_kit.serving.datos` en lugar de `figura_json`.
|
||||||
|
|
||||||
La sesión se cierra siempre, en `finally`. Un `KeyError` interno no se
|
La sesión se cierra siempre, en `finally`. Un `KeyError` interno no se
|
||||||
convierte en 404: sube como error 500. Un `LookupError` (periodo sin
|
convierte en 404: sube como error 500. Un `LookupError` (periodo sin
|
||||||
reporte) sí da 404.
|
reporte) sí da 404.
|
||||||
@@ -179,6 +186,9 @@ levanta `webapp` en el puerto 4200.
|
|||||||
| GET | `/tea/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
| GET | `/tea/pacientes/<int:pac_id>` | 200 paciente; 404 `{"error": "not found"}` |
|
||||||
| POST | `/tea/predict` | igual que CaCu |
|
| POST | `/tea/predict` | igual que CaCu |
|
||||||
| GET | `/<proyecto>/indicadores` | 200 lista de indicadores (`proyecto` = `cacu`, `cama` o `tea`) |
|
| GET | `/<proyecto>/indicadores` | 200 lista de indicadores (`proyecto` = `cacu`, `cama` o `tea`) |
|
||||||
|
| GET | `/<proyecto>/indicadores/<indicador>/periodos` | 200 periodos con reporte; 404 |
|
||||||
|
| GET | `/<proyecto>/indicadores/<indicador>/datos` | 200 los números, sin figura; 400 o 404 |
|
||||||
|
| GET | `/<proyecto>/indicadores/<indicador>/metadatos` | 200 ficha metodológica; 404 |
|
||||||
| GET | `/<proyecto>/indicadores/<indicador>/figuras/<figura>` | 200 JSON de la figura; 400 o 404 |
|
| GET | `/<proyecto>/indicadores/<indicador>/figuras/<figura>` | 200 JSON de la figura; 400 o 404 |
|
||||||
|
|
||||||
Las rutas de `pac_id` solo aceptan enteros. Con otro valor (`/tea/pacientes/abc`)
|
Las rutas de `pac_id` solo aceptan enteros. Con otro valor (`/tea/pacientes/abc`)
|
||||||
@@ -192,13 +202,17 @@ curl localhost:5000/tea/pacientes/1
|
|||||||
curl localhost:5000/tea/indicadores
|
curl localhost:5000/tea/indicadores
|
||||||
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos"
|
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos"
|
||||||
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos?periodos=2025-S1,2025-S2&tema=oscuro"
|
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/figuras/fig_c1_grupos?periodos=2025-S1,2025-S2&tema=oscuro"
|
||||||
|
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/periodos
|
||||||
|
curl "localhost:5000/tea/indicadores/K01_evaluacion_3_meses/datos?periodos=2025-S1,2025-S2"
|
||||||
|
curl localhost:5000/tea/indicadores/K01_evaluacion_3_meses/metadatos
|
||||||
curl localhost:5000/cacu/indicadores
|
curl localhost:5000/cacu/indicadores
|
||||||
|
curl localhost:5000/cacu/indicadores/cacu_eu8/datos
|
||||||
curl "localhost:5000/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
curl "localhost:5000/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
||||||
```
|
```
|
||||||
|
|
||||||
`/<proyecto>/indicadores` devuelve, por indicador: `id`, `titulo`,
|
`/<proyecto>/indicadores` devuelve, por indicador: `id`, `titulo`,
|
||||||
`contrato`, `figuras` y `tipos_periodo` (los que publica la definición en
|
`version`, `contrato`, `unidad`, `sentido`, `figuras`, `estratos` y
|
||||||
`extension.publicacion`). Las figuras dependen de la definición: con
|
`tipos_periodo` (los que publica la definición en `extension.publicacion`). Las figuras dependen de la definición: con
|
||||||
ficha (TEA) hay una por contrato (`fig_c1_grupos`, `fig_c2_apiladas`,
|
ficha (TEA) hay una por contrato (`fig_c1_grupos`, `fig_c2_apiladas`,
|
||||||
`fig_c3r_caja`); sin ficha (CaCu, CaMa) es `fig_c1_puntos`, un punto por
|
`fig_c3r_caja`); sin ficha (CaCu, CaMa) es `fig_c1_puntos`, un punto por
|
||||||
periodo.
|
periodo.
|
||||||
@@ -221,6 +235,37 @@ Códigos de la figura:
|
|||||||
| 404 | indicador desconocido; figura que no es del contrato del indicador; el indicador no tiene reportes; algún periodo pedido no tiene reporte |
|
| 404 | indicador desconocido; figura que no es del contrato del indicador; el indicador no tiene reportes; algún periodo pedido no tiene reporte |
|
||||||
| 500 | error interno (por ejemplo un `KeyError`) |
|
| 500 | error interno (por ejemplo un `KeyError`) |
|
||||||
|
|
||||||
|
### Datos, periodos y metadatos
|
||||||
|
|
||||||
|
Para mostrar el número o graficar desde el frontend, sin Plotly. Salen de
|
||||||
|
las mismas filas que las figuras y ya traen la supresión aplicada.
|
||||||
|
|
||||||
|
| Ruta | Qué devuelve |
|
||||||
|
| --- | --- |
|
||||||
|
| `/periodos` | `id`, `version` y `periodos`: por cada periodo con reporte, su `tipo`, sus fechas, su `report_id`, `generado_en` y `fecha_corte` |
|
||||||
|
| `/datos?periodos=&estrato=` | `filas` (una por periodo y grupo), `grupos` y `categorias` con sus etiquetas, `reportes` con la procedencia de cada periodo |
|
||||||
|
| `/metadatos` | la ficha, la unidad, los estándares y las reglas que usa el indicador, con su estado |
|
||||||
|
|
||||||
|
`periodos` se pide igual que en la figura. `estrato` es uno de los
|
||||||
|
`estratos` del indicador. Toda fila de `/datos` trae `periodo`, `grupo`,
|
||||||
|
`estrato` y `suprimido`, y después las columnas de su `contrato`:
|
||||||
|
|
||||||
|
| Contrato | Columnas |
|
||||||
|
| --- | --- |
|
||||||
|
| C1 (proporción) | `numerador`, `denominador`, `valor` (0 a 100), `ic_bajo`, `ic_alto` (Wilson al 95 %), `n_sin_evento`, `n_excluido` |
|
||||||
|
| C2 (distribución) | `categoria`, `n`, `orden` |
|
||||||
|
| C3r (tiempos) | `n`, `mediana`, `q1`, `q3`, `n_sin_evento`, `n_excluido`, `unidad` |
|
||||||
|
|
||||||
|
Una celda suprimida va con `suprimido` en 1 y sus números en `null`. En
|
||||||
|
`reportes`, `periodo_fin` es el primer día que ya no entra en el periodo.
|
||||||
|
|
||||||
|
La forma de estas respuestas es un contrato con el frontend: no se quita
|
||||||
|
ni se renombra un campo; solo se agregan.
|
||||||
|
|
||||||
|
Códigos: 400 si `periodos` está mal formado o `estrato` no es del
|
||||||
|
indicador; 404 si el indicador no existe, no tiene reportes o algún
|
||||||
|
periodo pedido no lo tiene.
|
||||||
|
|
||||||
## Cómo extender
|
## Cómo extender
|
||||||
|
|
||||||
### Agregar una ruta a un blueprint existente
|
### Agregar una ruta a un blueprint existente
|
||||||
|
|||||||
+7
-38
@@ -1,53 +1,22 @@
|
|||||||
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
||||||
|
|
||||||
from importlib import import_module
|
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from sqlmodel import Session, select
|
|
||||||
|
|
||||||
SEMESTRES = ["2025-S1", "2025-S2"]
|
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||||
MESES = ["2025-01", "2025-02", "2025-03"]
|
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||||
|
|
||||||
|
|
||||||
def sembrar_base(proyecto: str, motor) -> None:
|
def sembrar_base(proyecto: str, motor) -> None:
|
||||||
"""Staging sintético del kit, tablas del kit, carga y el indicador de ejemplo calculado.
|
"""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,
|
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para
|
||||||
con los pasos del kit: parámetros, `dim_periodo` (semestres y meses de
|
TEA: cada definición de `measures_de(proyecto)` queda calculada en los
|
||||||
2025) y `<proyecto>_eu8` en `SEMESTRES` y `MESES`.
|
periodos de 2025 que publica (`SEMESTRES`, y los doce meses si publica
|
||||||
|
meses).
|
||||||
"""
|
"""
|
||||||
from indicadores_kit.esquema import crear_esquema
|
from indicadores_kit.demostracion import base_de_prueba
|
||||||
from indicadores_kit.mart.calculo import calcular_measure
|
|
||||||
from indicadores_kit.registry.measures import leer_measure, ruta_de_measure
|
|
||||||
from indicadores_kit.registry.parametros import RUTA_PARAMETROS, cargar_parametros
|
|
||||||
from indicadores_kit.registry.periodos import generar_dim_periodo
|
|
||||||
from indicadores_kit.tablas import tablas_de
|
|
||||||
|
|
||||||
fixtures = import_module(f"indicadores_kit.{proyecto}.fixtures")
|
base_de_prueba(motor, proyecto)
|
||||||
etl = import_module(f"indicadores_kit.{proyecto}.etl")
|
|
||||||
base = import_module(f"core.{proyecto}.base")
|
|
||||||
modelos = import_module(f"core.{proyecto}.models")
|
|
||||||
tablas = tablas_de(proyecto)
|
|
||||||
|
|
||||||
getattr(base, "CaCuModel" if proyecto == "cacu" else "CaMaModel").metadata.create_all(motor)
|
|
||||||
crear_esquema(motor, proyecto)
|
|
||||||
cargar, tabla = (
|
|
||||||
(etl.cargar_citologias, modelos.CitologiaCervical)
|
|
||||||
if proyecto == "cacu"
|
|
||||||
else (etl.cargar_mastografias, modelos.Mastografia)
|
|
||||||
)
|
|
||||||
with Session(motor) as sesion:
|
|
||||||
fixtures.insertar(sesion)
|
|
||||||
cargar(
|
|
||||||
sesion,
|
|
||||||
sesion.exec(select(modelos.Paciente)).all(),
|
|
||||||
sesion.exec(select(tabla)).all(),
|
|
||||||
)
|
|
||||||
cargar_parametros(sesion, RUTA_PARAMETROS, tablas=tablas)
|
|
||||||
generar_dim_periodo(sesion, 2025, 2025, tablas=tablas, tipos=("semestre", "mes"))
|
|
||||||
medida = leer_measure(ruta_de_measure(proyecto, f"{proyecto}_eu8"))
|
|
||||||
for periodo in SEMESTRES + MESES:
|
|
||||||
calcular_measure(sesion, medida, periodo, tablas=tablas, permitir_sin_definir=True)
|
|
||||||
|
|
||||||
|
|
||||||
def cliente_de(proyecto: str, tmp_path_factory):
|
def cliente_de(proyecto: str, tmp_path_factory):
|
||||||
|
|||||||
+126
-8
@@ -29,13 +29,24 @@ def test_listar_indicadores(client):
|
|||||||
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
lista = response.get_json()
|
lista = response.get_json()
|
||||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||||
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||||
medida = DEFINICIONES[INDICADOR]
|
for fila in lista:
|
||||||
assert fila["titulo"] == medida.title
|
medida = DEFINICIONES[fila["id"]]
|
||||||
assert fila["contrato"] == medida.extension.contrato
|
assert fila["titulo"] == medida.title
|
||||||
assert fila["figuras"] == figuras_de(medida) == [FIGURA]
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
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): cacu_eu7_anormal, cacu_eu8 e ind2b no se muestran."""
|
||||||
|
ocultos = {"cacu_eu7_anormal", "cacu_eu8", "ind2b"}
|
||||||
|
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_figura_con_semestres(client):
|
def test_figura_con_semestres(client):
|
||||||
@@ -89,7 +100,7 @@ def test_figura_con_parametros_mal_formados_da_400(client, query):
|
|||||||
(INDICADOR, "fig_no_existe", ""),
|
(INDICADOR, "fig_no_existe", ""),
|
||||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||||
(INDICADOR, FIGURA, "?periodos=2025-11"), # un mes sin reporte
|
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||||
@@ -108,3 +119,110 @@ def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
|||||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
with pytest.raises(KeyError):
|
with pytest.raises(KeyError):
|
||||||
_figura(client, query="?periodos=2025-S1")
|
_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"])
|
||||||
|
# La que compara periodos ya no se publica para una sola distribución.
|
||||||
|
assert _figura(client, "cacu_eu7", "fig_c2_apiladas").status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
# --- El catálogo, los periodos, los datos y los metadatos ---
|
||||||
|
|
||||||
|
CATALOGO = {"id", "titulo", "version", "contrato", "unidad", "sentido", "tipos_periodo", "figuras", "estratos"}
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
|||||||
+113
-8
@@ -29,13 +29,24 @@ def test_listar_indicadores(client):
|
|||||||
|
|
||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
lista = response.get_json()
|
lista = response.get_json()
|
||||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
visibles = [id_ for id_, medida in DEFINICIONES.items() if not medida.extension.publicacion.oculto]
|
||||||
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
assert [fila["id"] for fila in lista] == sorted(visibles)
|
||||||
medida = DEFINICIONES[INDICADOR]
|
for fila in lista:
|
||||||
assert fila["titulo"] == medida.title
|
medida = DEFINICIONES[fila["id"]]
|
||||||
assert fila["contrato"] == medida.extension.contrato
|
assert fila["titulo"] == medida.title
|
||||||
assert fila["figuras"] == figuras_de(medida) == [FIGURA]
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
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_confirmacion_birads45 y cama_eu8 no se muestran."""
|
||||||
|
ocultos = {"cama_confirmacion_birads45", "cama_eu8"}
|
||||||
|
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_figura_con_semestres(client):
|
def test_figura_con_semestres(client):
|
||||||
@@ -89,7 +100,7 @@ def test_figura_con_parametros_mal_formados_da_400(client, query):
|
|||||||
(INDICADOR, "fig_no_existe", ""),
|
(INDICADOR, "fig_no_existe", ""),
|
||||||
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
(INDICADOR, FIGURA, "?periodos=2030-S1"), # sin reporte
|
||||||
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
(INDICADOR, FIGURA, "?periodos=2025-S1,2030-S2"),
|
||||||
(INDICADOR, FIGURA, "?periodos=2025-11"), # un mes sin reporte
|
(INDICADOR, FIGURA, "?periodos=2024-11"), # un mes sin reporte
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
def test_figura_desconocida_o_sin_reporte_da_404(client, indicador, figura, query):
|
||||||
@@ -108,3 +119,97 @@ def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
|||||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
with pytest.raises(KeyError):
|
with pytest.raises(KeyError):
|
||||||
_figura(client, query="?periodos=2025-S1")
|
_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"}
|
||||||
|
|
||||||
|
|
||||||
|
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()
|
||||||
|
|||||||
+48
-8
@@ -9,7 +9,7 @@ PERIODOS = ",".join(fixtures.PERIODOS)
|
|||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def client(tmp_path_factory):
|
def client(tmp_path_factory):
|
||||||
"""Una base de TEA temporal, con los 18 indicadores calculados, por `TEA_DATABASE_URL`."""
|
"""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,
|
# 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.
|
# y test_app.py debe alcanzar a fijar CACU_DATABASE_URL antes.
|
||||||
from persistance.db import get_tea_engine
|
from persistance.db import get_tea_engine
|
||||||
@@ -42,7 +42,8 @@ def test_listar_indicadores(client):
|
|||||||
assert response.status_code == 200
|
assert response.status_code == 200
|
||||||
|
|
||||||
lista = response.get_json()
|
lista = response.get_json()
|
||||||
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
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:
|
for fila in lista:
|
||||||
medida = DEFINICIONES[fila["id"]]
|
medida = DEFINICIONES[fila["id"]]
|
||||||
assert fila["titulo"] == medida.title
|
assert fila["titulo"] == medida.title
|
||||||
@@ -50,15 +51,25 @@ def test_listar_indicadores(client):
|
|||||||
assert fila["figuras"] == figuras_de(medida)
|
assert fila["figuras"] == figuras_de(medida)
|
||||||
|
|
||||||
|
|
||||||
|
def test_los_ocultos_no_salen_en_el_catalogo_pero_responden(client):
|
||||||
|
"""Provisional (oct 2026): K01, K08, M04 y M15 no se muestran; quedan 16 en el catálogo."""
|
||||||
|
ocultos = {"K01_evaluacion_3_meses", "K08_eeg_sueno", "M04_dias_entrevista_ados2", "M15_grado_hipoacusia"}
|
||||||
|
ids = {fila["id"] for fila in client.get("/tea/indicadores").get_json()}
|
||||||
|
|
||||||
|
assert len(ids) == 16
|
||||||
|
assert not ids & ocultos
|
||||||
|
assert {"M21_diagnosticados_con_eeg", "M22_diagnosticados_sin_eeg"} <= ids
|
||||||
|
assert client.get("/tea/indicadores/K01_evaluacion_3_meses/metadatos").status_code == 200
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
@pytest.mark.parametrize("indicador", sorted(DEFINICIONES))
|
||||||
def test_figura_de_cada_indicador(client, indicador):
|
def test_figura_de_cada_indicador(client, indicador):
|
||||||
(figura,) = figuras_de(DEFINICIONES[indicador])
|
for figura in figuras_de(DEFINICIONES[indicador]):
|
||||||
|
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||||
|
|
||||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
assert response.status_code == 200, figura
|
||||||
|
assert response.mimetype == "application/json"
|
||||||
assert response.status_code == 200
|
assert "data" in response.get_json()
|
||||||
assert response.mimetype == "application/json"
|
|
||||||
assert "data" in response.get_json()
|
|
||||||
|
|
||||||
|
|
||||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||||
@@ -121,3 +132,32 @@ def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
|||||||
monkeypatch.setattr(indicadores, "figura_json", falla)
|
monkeypatch.setattr(indicadores, "figura_json", falla)
|
||||||
with pytest.raises(KeyError):
|
with pytest.raises(KeyError):
|
||||||
_figura(client, "K01_evaluacion_3_meses", "fig_c1_grupos", "?periodos=2025-S1")
|
_figura(client, "K01_evaluacion_3_meses", "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/K01_evaluacion_3_meses/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"
|
||||||
|
|||||||
+94
-22
@@ -2,20 +2,33 @@
|
|||||||
|
|
||||||
`registrar_indicadores` agrega a un blueprint:
|
`registrar_indicadores` agrega a un blueprint:
|
||||||
|
|
||||||
GET /indicadores lista de indicadores
|
GET /indicadores catálogo de indicadores
|
||||||
|
GET /indicadores/<id>/periodos periodos con reporte
|
||||||
|
GET /indicadores/<id>/datos?periodos=&estrato= 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=
|
||||||
|
|
||||||
Las definiciones salen del kit (`measures_de`) y las figuras de
|
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
|
`indicadores_kit.serving.figuras`; aquí solo se valida, se abre la sesión y
|
||||||
se traducen los errores a códigos HTTP.
|
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.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
from flask import Blueprint, Response, jsonify, request
|
||||||
from indicadores_kit.registry.measures import Measure, measures_de
|
from indicadores_kit.registry.measures import Measure, measures_de
|
||||||
from indicadores_kit.serving.figuras import TEMAS, figura_json, figuras_de, periodos_con_reporte
|
from indicadores_kit.serving.datos import datos_de, metadatos_de, periodos_de, resumen_de
|
||||||
|
from indicadores_kit.serving.figuras import (
|
||||||
|
TEMAS,
|
||||||
|
figura_json,
|
||||||
|
figuras_de,
|
||||||
|
periodos_con_reporte,
|
||||||
|
periodos_por_defecto,
|
||||||
|
)
|
||||||
from indicadores_kit.tablas import tablas_de
|
from indicadores_kit.tablas import tablas_de
|
||||||
from sqlmodel import Session
|
from sqlmodel import Session
|
||||||
|
|
||||||
@@ -36,6 +49,11 @@ def _error(mensaje: str, codigo: int):
|
|||||||
return jsonify({"error": mensaje}), codigo
|
return jsonify({"error": mensaje}), codigo
|
||||||
|
|
||||||
|
|
||||||
|
def _json(contenido) -> Response:
|
||||||
|
"""Sin `jsonify`, que ordena las llaves: grupos y categorías van en su orden de presentación."""
|
||||||
|
return Response(json.dumps(contenido, ensure_ascii=False), mimetype="application/json")
|
||||||
|
|
||||||
|
|
||||||
def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
def _tipo_de(periodo: str, tipos: list[str]) -> str | None:
|
||||||
"""El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`)."""
|
"""El tipo, entre los que publica el indicador, al que pertenece el periodo (o `None`)."""
|
||||||
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||||
@@ -64,7 +82,7 @@ def periodos_pedidos(texto: str | None, medida: Measure) -> tuple[list[str], str
|
|||||||
def registrar_indicadores(
|
def registrar_indicadores(
|
||||||
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Agrega las dos rutas de indicadores de `proyecto` al blueprint.
|
"""Agrega las rutas de indicadores de `proyecto` al blueprint.
|
||||||
|
|
||||||
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
||||||
se llama en cada petición, no al registrar.
|
se llama en cada petición, no al registrar.
|
||||||
@@ -73,18 +91,71 @@ def registrar_indicadores(
|
|||||||
tablas = tablas_de(proyecto)
|
tablas = tablas_de(proyecto)
|
||||||
|
|
||||||
def listar_indicadores():
|
def listar_indicadores():
|
||||||
return jsonify(
|
# Los marcados `oculto` en su TOML no salen en el catálogo; su id sigue respondiendo.
|
||||||
[
|
return _json([
|
||||||
{
|
resumen_de(id_, medida)
|
||||||
"id": id_,
|
for id_, medida in definiciones.items()
|
||||||
"titulo": medida.title,
|
if not medida.extension.publicacion.oculto
|
||||||
"contrato": medida.extension.contrato,
|
])
|
||||||
"figuras": figuras_de(medida),
|
|
||||||
"tipos_periodo": medida.extension.publicacion.tipos_periodo,
|
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."""
|
||||||
for id_, medida in definiciones.items()
|
if periodos:
|
||||||
]
|
return periodos
|
||||||
)
|
tipo = medida.extension.publicacion.tipos_periodo[0]
|
||||||
|
return periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
|
||||||
|
|
||||||
|
def get_periodos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
periodos = periodos_de(sesion, medida, tablas=tablas)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, "version": medida.version, "periodos": periodos})
|
||||||
|
|
||||||
|
def get_metadatos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
metadatos = metadatos_de(sesion, medida, tablas=tablas)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, **metadatos})
|
||||||
|
|
||||||
|
def get_datos(indicador: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
estrato = request.args.get("estrato") or None
|
||||||
|
if estrato is not None and estrato not in medida.extension.estratos:
|
||||||
|
return _error(
|
||||||
|
f"estrato desconocido {estrato!r}; este indicador tiene {medida.extension.estratos}",
|
||||||
|
400,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
periodos, _ = periodos_pedidos(request.args.get("periodos"), medida)
|
||||||
|
except ValueError as error:
|
||||||
|
return _error(str(error), 400)
|
||||||
|
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
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)
|
||||||
|
except KeyError:
|
||||||
|
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||||
|
raise
|
||||||
|
except LookupError as error:
|
||||||
|
return _error(str(error), 404)
|
||||||
|
finally:
|
||||||
|
sesion.close()
|
||||||
|
return _json({"id": indicador, **datos})
|
||||||
|
|
||||||
def get_figura(indicador: str, figura: str):
|
def get_figura(indicador: str, figura: str):
|
||||||
medida = definiciones.get(indicador)
|
medida = definiciones.get(indicador)
|
||||||
@@ -105,12 +176,10 @@ def registrar_indicadores(
|
|||||||
|
|
||||||
sesion = get_session()
|
sesion = get_session()
|
||||||
try:
|
try:
|
||||||
|
# Sin pedir ninguno: todos, o solo el más reciente si la figura se lee en un periodo.
|
||||||
|
periodos = periodos or periodos_por_defecto(sesion, medida, figura, tablas=tablas)
|
||||||
if not periodos:
|
if not periodos:
|
||||||
# El primer tipo que publica el indicador.
|
return _error("el indicador no tiene reportes calculados", 404)
|
||||||
tipo = medida.extension.publicacion.tipos_periodo[0]
|
|
||||||
periodos = periodos_con_reporte(sesion, medida, tablas=tablas, tipo=tipo)
|
|
||||||
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)
|
||||||
except KeyError:
|
except KeyError:
|
||||||
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
# KeyError también es LookupError: aquí es un error interno (500), no un periodo sin reporte.
|
||||||
@@ -122,6 +191,9 @@ def registrar_indicadores(
|
|||||||
return Response(texto, mimetype="application/json")
|
return Response(texto, mimetype="application/json")
|
||||||
|
|
||||||
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/periodos", "get_periodos", get_periodos)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/datos", "get_datos", get_datos)
|
||||||
|
blueprint.add_url_rule("/indicadores/<indicador>/metadatos", "get_metadatos", get_metadatos)
|
||||||
blueprint.add_url_rule(
|
blueprint.add_url_rule(
|
||||||
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in New Issue
Block a user