Rutas de indicadores de CaCu: /cacu y /tea comparten webapi/indicadores.py
registrar_indicadores(blueprint, proyecto, get_session) agrega GET /indicadores (con tipos_periodo) y GET /indicadores/<id>/figuras/<figura>. TEA pasa a ese módulo; los periodos se validan contra los tipos que publica cada definición (semestre, mes, ...) y las figuras salen de figuras_de(medida). Pruebas de CaCu con SQLite temporal sembrada con los fixtures del kit. Pruebas: Core 25 passed; Persistance 31 passed; indicadores_kit 564 passed, 2 skipped; WebApi 55 passed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -11,19 +11,24 @@ 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
|
||||||
│ └── 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
|
||||||
│ └── tea.py tea_bp, prefijo /tea (indicadores y figuras)
|
│ └── tea.py tea_bp, prefijo /tea
|
||||||
├── tests/
|
├── tests/
|
||||||
|
│ ├── conftest.py siembra una base de CaCu con los fixtures del kit
|
||||||
│ ├── test_app.py /health y rutas de CaCu, con SQLite temporal
|
│ ├── test_app.py /health y rutas de CaCu, con SQLite temporal
|
||||||
|
│ ├── test_cacu.py indicadores de CaCu, con SQLite temporal
|
||||||
│ └── test_tea.py rutas de TEA, con SQLite temporal y 18 indicadores
|
│ └── test_tea.py rutas de TEA, con SQLite temporal y 18 indicadores
|
||||||
├── Dockerfile imagen; el contexto es la raíz del repo padre
|
├── Dockerfile imagen; el contexto es la raíz del repo padre
|
||||||
└── docker-entrypoint.sh migra las tres bases y arranca main.py
|
└── docker-entrypoint.sh migra las tres bases y arranca main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
Un blueprint por dominio. CaCu y CaMa tienen rutas de ejemplo (paciente y
|
Un blueprint por dominio, con rutas de ejemplo (paciente y `predict`).
|
||||||
`predict`). TEA, además, sirve los indicadores del kit.
|
TEA y CaCu sirven además los indicadores del kit: cada blueprint llama a
|
||||||
|
`registrar_indicadores(blueprint, proyecto, get_<proyecto>_session)` de
|
||||||
|
`webapi/indicadores.py`, que agrega `/indicadores` y las figuras.
|
||||||
|
|
||||||
## Flujo de datos
|
## Flujo de datos
|
||||||
|
|
||||||
@@ -35,16 +40,16 @@ request -> blueprint -> repositorio de Persistance -> modelo -> JSON
|
|||||||
|
|
||||||
El repositorio abre y cierra su propia sesión.
|
El repositorio abre y cierra su propia sesión.
|
||||||
|
|
||||||
Ruta de figura de TEA:
|
Ruta de figura (la misma para `/cacu` y `/tea`):
|
||||||
|
|
||||||
```
|
```
|
||||||
GET /tea/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
GET /<proyecto>/indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||||
│
|
│
|
||||||
├─ valida indicador y figura (404 si no existen)
|
├─ 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_tea_session()
|
├─ sesion = get_<proyecto>_session()
|
||||||
├─ sin periodos: busca los periodos con reporte en measure_report
|
├─ sin periodos: periodos_con_reporte(..., tipo=<primer tipo que publica>)
|
||||||
├─ figura_json_tea(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()
|
||||||
│
|
│
|
||||||
@@ -81,13 +86,15 @@ SQLite **relativo al directorio actual**.
|
|||||||
| `TEA_DATABASE_URL` | `sqlite:///tea.db` |
|
| `TEA_DATABASE_URL` | `sqlite:///tea.db` |
|
||||||
|
|
||||||
Atención: con el valor por defecto, `alembic` en `Persistance/` escribe
|
Atención: con el valor por defecto, `alembic` en `Persistance/` escribe
|
||||||
`Persistance/tea.db` y la API en `WebApi/` abre `WebApi/tea.db`. Son dos
|
`Persistance/<proyecto>.db` y la API en `WebApi/` abre `WebApi/<proyecto>.db`.
|
||||||
bases distintas. La API crea la segunda vacía y falla con
|
Son dos bases distintas. La API crea la segunda vacía y falla con
|
||||||
`no such table: measure_report`. Use siempre una ruta absoluta
|
`no such table: measure_report`. Use siempre una ruta absoluta
|
||||||
(`sqlite:////` con cuatro barras) y la misma en todos los pasos:
|
(`sqlite:////` con cuatro barras) y la misma en todos los pasos, en cada
|
||||||
|
proyecto que vaya a servir:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea.db
|
export TEA_DATABASE_URL=sqlite:////ruta/absoluta/tea.db
|
||||||
|
export CACU_DATABASE_URL=sqlite:////ruta/absoluta/cacu.db
|
||||||
```
|
```
|
||||||
|
|
||||||
### Correr en local
|
### Correr en local
|
||||||
@@ -120,8 +127,28 @@ uv run python -m indicadores_kit.correr tea K01_evaluacion_3_meses 2025-S1 2025-
|
|||||||
uv run python main.py # http://localhost:5000
|
uv run python main.py # http://localhost:5000
|
||||||
```
|
```
|
||||||
|
|
||||||
Cada `correr` agrega un reporte; no borra los anteriores. Para CaCu y
|
Cada `correr` agrega un reporte; no borra los anteriores.
|
||||||
CaMa, migre con su `alembic.ini` y su variable de entorno.
|
|
||||||
|
**CaCu** sigue los mismos pasos con su `alembic.ini`, su variable
|
||||||
|
de entorno y el ETL de su proyecto (`python -m indicadores_kit.cacu.etl`).
|
||||||
|
`correr` solo agrega semestres a `dim_periodo`; para tener también meses,
|
||||||
|
prepare los dos tipos y calcule con los pasos del kit:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
uv run python -c "
|
||||||
|
from datetime import date
|
||||||
|
from indicadores_kit.pasos import calcular_periodos, preparar_registro
|
||||||
|
from indicadores_kit.registry.measures import leer_measure, ruta_de_measure
|
||||||
|
preparar_registro('cacu', 2025, 2025, tipos=('semestre', 'mes'))
|
||||||
|
medida = leer_measure(ruta_de_measure('cacu', 'cacu_eu8'))
|
||||||
|
for tipo in ('semestre', 'mes'):
|
||||||
|
calcular_periodos('cacu', medida, tipo, date(2025, 1, 1), date(2026, 1, 1), permitir_sin_definir=True)
|
||||||
|
"
|
||||||
|
uv run python main.py
|
||||||
|
```
|
||||||
|
|
||||||
|
El id es `cacu_eu8`. En `tests/conftest.py` está la
|
||||||
|
secuencia completa con los fixtures del kit.
|
||||||
|
|
||||||
### Correr con Docker
|
### Correr con Docker
|
||||||
|
|
||||||
@@ -149,8 +176,8 @@ levanta `webapp` en el puerto 4200.
|
|||||||
| POST | `/cama/predict` | igual que CaCu |
|
| POST | `/cama/predict` | igual que CaCu |
|
||||||
| 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 | `/tea/indicadores` | 200 lista de indicadores |
|
| GET | `/<proyecto>/indicadores` | 200 lista de indicadores (`proyecto` = `cacu` o `tea`) |
|
||||||
| GET | `/tea/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`)
|
||||||
Flask no encuentra la ruta y da 404.
|
Flask no encuentra la ruta y da 404.
|
||||||
@@ -163,16 +190,24 @@ 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/cacu/indicadores
|
||||||
|
curl "localhost:5000/cacu/indicadores/cacu_eu8/figuras/fig_c1_puntos?periodos=2025-01,2025-02,2025-03"
|
||||||
```
|
```
|
||||||
|
|
||||||
`/tea/indicadores` devuelve, por indicador: `id`, `titulo`, `contrato` y
|
`/<proyecto>/indicadores` devuelve, por indicador: `id`, `titulo`,
|
||||||
`figuras`. Cada contrato (`C1`, `C2`, `C3r`) tiene una figura
|
`contrato`, `figuras` y `tipos_periodo` (los que publica la definición en
|
||||||
(`fig_c1_grupos`, `fig_c2_apiladas`, `fig_c3r_caja`).
|
`extension.publicacion`). Las figuras dependen de la definición: con
|
||||||
|
ficha (TEA) hay una por contrato (`fig_c1_grupos`, `fig_c2_apiladas`,
|
||||||
|
`fig_c3r_caja`); sin ficha (CaCu) es `fig_c1_puntos`, un punto por
|
||||||
|
periodo.
|
||||||
|
|
||||||
Parámetros de la figura:
|
Parámetros de la figura:
|
||||||
|
|
||||||
- `periodos`: lista separada por comas, con formato `AAAA-S1` o `AAAA-S2`.
|
- `periodos`: lista separada por comas, todos de un mismo tipo y de un tipo
|
||||||
Sin el parámetro se usan todos los periodos con reporte.
|
que el indicador publique: `AAAA-S1` o `AAAA-S2` (semestre), `AAAA-MM`
|
||||||
|
(mes), y así los demás de `registry/periodos.py`. Sin el parámetro se
|
||||||
|
usan todos los periodos con reporte del primer tipo que publica la
|
||||||
|
definición.
|
||||||
- `tema`: `claro` (por defecto) u `oscuro`.
|
- `tema`: `claro` (por defecto) u `oscuro`.
|
||||||
|
|
||||||
Códigos de la figura:
|
Códigos de la figura:
|
||||||
@@ -180,7 +215,7 @@ Códigos de la figura:
|
|||||||
| Código | Causa |
|
| Código | Causa |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| 200 | JSON de la figura |
|
| 200 | JSON de la figura |
|
||||||
| 400 | `tema` desconocido, o `periodos` mal formado (incluye una coma al final) |
|
| 400 | `tema` desconocido, o `periodos` mal formado: coma al final, tipo que el indicador no publica, tipos mezclados |
|
||||||
| 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`) |
|
||||||
|
|
||||||
@@ -229,7 +264,8 @@ def client():
|
|||||||
yield client
|
yield client
|
||||||
```
|
```
|
||||||
|
|
||||||
Patrón de `tests/test_tea.py` (TEA, con `monkeypatch` de `settings`):
|
Patrón de `tests/test_tea.py` y `test_cacu.py` (con `monkeypatch` de `settings`;
|
||||||
|
CaCu lo arma en `tests/conftest.py`):
|
||||||
|
|
||||||
```python
|
```python
|
||||||
from persistance.db import get_tea_engine
|
from persistance.db import get_tea_engine
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
"""Lo común de las pruebas de indicadores de CaCu y CaMa."""
|
||||||
|
|
||||||
|
from importlib import import_module
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from sqlmodel import Session, select
|
||||||
|
|
||||||
|
SEMESTRES = ["2025-S1", "2025-S2"]
|
||||||
|
MESES = ["2025-01", "2025-02", "2025-03"]
|
||||||
|
|
||||||
|
|
||||||
|
def sembrar_base(proyecto: str, motor) -> None:
|
||||||
|
"""Staging sintético del kit, tablas del kit, carga y el indicador de ejemplo calculado.
|
||||||
|
|
||||||
|
Lo mismo que hace `indicadores_kit.tea.fixtures.base_de_prueba` para TEA,
|
||||||
|
con los pasos del kit: parámetros, `dim_periodo` (semestres y meses de
|
||||||
|
2025) y `<proyecto>_eu8` en `SEMESTRES` y `MESES`.
|
||||||
|
"""
|
||||||
|
from indicadores_kit.esquema import crear_esquema
|
||||||
|
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")
|
||||||
|
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):
|
||||||
|
"""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,110 @@
|
|||||||
|
"""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 measures_de
|
||||||
|
from indicadores_kit.serving.figuras import figuras_de
|
||||||
|
|
||||||
|
PROYECTO = "cacu"
|
||||||
|
INDICADOR = "cacu_eu8"
|
||||||
|
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()
|
||||||
|
assert [fila["id"] for fila in lista] == sorted(DEFINICIONES)
|
||||||
|
fila = next(fila for fila in lista if fila["id"] == INDICADOR)
|
||||||
|
medida = DEFINICIONES[INDICADOR]
|
||||||
|
assert fila["titulo"] == medida.title
|
||||||
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
|
assert fila["figuras"] == figuras_de(medida) == [FIGURA]
|
||||||
|
assert fila["tipos_periodo"] == ["semestre", "mes"]
|
||||||
|
|
||||||
|
|
||||||
|
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_c2_apiladas", ""), # 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=2025-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")
|
||||||
+6
-6
@@ -1,6 +1,6 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from indicadores_kit.registry.measures import measures_de
|
from indicadores_kit.registry.measures import measures_de
|
||||||
from indicadores_kit.serving.figuras_tea import FIGURAS_TEA
|
from indicadores_kit.serving.figuras import figuras_de
|
||||||
from indicadores_kit.tea import fixtures
|
from indicadores_kit.tea import fixtures
|
||||||
|
|
||||||
DEFINICIONES = measures_de("tea")
|
DEFINICIONES = measures_de("tea")
|
||||||
@@ -47,12 +47,12 @@ def test_listar_indicadores(client):
|
|||||||
medida = DEFINICIONES[fila["id"]]
|
medida = DEFINICIONES[fila["id"]]
|
||||||
assert fila["titulo"] == medida.title
|
assert fila["titulo"] == medida.title
|
||||||
assert fila["contrato"] == medida.extension.contrato
|
assert fila["contrato"] == medida.extension.contrato
|
||||||
assert fila["figuras"] == sorted(FIGURAS_TEA[medida.extension.contrato])
|
assert fila["figuras"] == figuras_de(medida)
|
||||||
|
|
||||||
|
|
||||||
@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_TEA[DEFINICIONES[indicador].extension.contrato]
|
(figura,) = figuras_de(DEFINICIONES[indicador])
|
||||||
|
|
||||||
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
response = _figura(client, indicador, figura, f"?periodos={PERIODOS}&tema=oscuro")
|
||||||
|
|
||||||
@@ -62,7 +62,7 @@ def test_figura_de_cada_indicador(client, indicador):
|
|||||||
|
|
||||||
|
|
||||||
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
def test_figura_sin_periodos_usa_todos_los_reportes(client):
|
||||||
(figura,) = FIGURAS_TEA["C1"]
|
(figura,) = figuras_de(DEFINICIONES["K01_evaluacion_3_meses"])
|
||||||
|
|
||||||
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
response = _figura(client, "K01_evaluacion_3_meses", figura)
|
||||||
|
|
||||||
@@ -113,11 +113,11 @@ def test_paciente_por_id_entero(client):
|
|||||||
|
|
||||||
|
|
||||||
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
def test_un_keyerror_interno_no_se_vuelve_404(client, monkeypatch):
|
||||||
from webapi.blueprints import tea
|
from webapi import indicadores
|
||||||
|
|
||||||
def falla(*args, **kwargs):
|
def falla(*args, **kwargs):
|
||||||
raise KeyError("columna")
|
raise KeyError("columna")
|
||||||
|
|
||||||
monkeypatch.setattr(tea, "figura_json_tea", 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")
|
||||||
|
|||||||
@@ -2,9 +2,13 @@ from flask import Blueprint, jsonify
|
|||||||
|
|
||||||
from models.cacu import CaCuModel
|
from models.cacu import CaCuModel
|
||||||
from persistance.cacu import paciente_repository
|
from persistance.cacu import paciente_repository
|
||||||
|
from persistance.db import get_cacu_session
|
||||||
|
from webapi.indicadores import registrar_indicadores
|
||||||
|
|
||||||
cacu_bp = Blueprint("cacu", __name__)
|
cacu_bp = Blueprint("cacu", __name__)
|
||||||
|
|
||||||
|
registrar_indicadores(cacu_bp, "cacu", get_cacu_session)
|
||||||
|
|
||||||
|
|
||||||
@cacu_bp.get("/pacientes/<int:pac_id>")
|
@cacu_bp.get("/pacientes/<int:pac_id>")
|
||||||
def get_paciente(pac_id: int):
|
def get_paciente(pac_id: int):
|
||||||
|
|||||||
@@ -1,95 +1,13 @@
|
|||||||
import re
|
from flask import Blueprint, jsonify
|
||||||
|
|
||||||
from flask import Blueprint, Response, jsonify, request
|
|
||||||
from sqlmodel import Session, select
|
|
||||||
|
|
||||||
from indicadores_kit.registry.measures import measures_de
|
|
||||||
from indicadores_kit.serving.figuras_tea import FIGURAS_TEA, TEMAS, figura_json_tea
|
|
||||||
from indicadores_kit.tea.tablas import TABLAS
|
|
||||||
from models.tea import TeaModel
|
from models.tea import TeaModel
|
||||||
from persistance.db import get_tea_session
|
from persistance.db import get_tea_session
|
||||||
from persistance.tea import pacientes_repository
|
from persistance.tea import pacientes_repository
|
||||||
|
from webapi.indicadores import registrar_indicadores
|
||||||
|
|
||||||
tea_bp = Blueprint("tea", __name__)
|
tea_bp = Blueprint("tea", __name__)
|
||||||
|
|
||||||
# Las 18 definiciones de TEA, por id (nombre del archivo). Son fijas: se leen una vez.
|
registrar_indicadores(tea_bp, "tea", get_tea_session)
|
||||||
DEFINICIONES = measures_de("tea")
|
|
||||||
# Un periodo, como "2025-S1": año y semestre.
|
|
||||||
PERIODO = re.compile(r"\d{4}-S[12]")
|
|
||||||
|
|
||||||
|
|
||||||
def _error(mensaje: str, codigo: int):
|
|
||||||
return jsonify({"error": mensaje}), codigo
|
|
||||||
|
|
||||||
|
|
||||||
def _resumen(id_: str, medida) -> dict:
|
|
||||||
contrato = medida.extension.contrato
|
|
||||||
return {
|
|
||||||
"id": id_,
|
|
||||||
"titulo": medida.title,
|
|
||||||
"contrato": contrato,
|
|
||||||
"figuras": sorted(FIGURAS_TEA[contrato]),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _periodos_de(texto: str | None) -> list[str]:
|
|
||||||
"""Los periodos de `?periodos=`. Sin parámetro (o vacío), lista vacía: todos los que tienen reporte."""
|
|
||||||
if not texto:
|
|
||||||
return []
|
|
||||||
periodos = texto.split(",")
|
|
||||||
if not all(PERIODO.fullmatch(periodo) for periodo in periodos):
|
|
||||||
raise ValueError(f"Periodos mal formados: {texto!r}; use AAAA-S1 o AAAA-S2.")
|
|
||||||
return list(dict.fromkeys(periodos))
|
|
||||||
|
|
||||||
|
|
||||||
def _periodos_con_reporte(sesion: Session, medida) -> list[str]:
|
|
||||||
reporte = TABLAS.MeasureReport
|
|
||||||
consulta = (
|
|
||||||
select(reporte.periodo_id)
|
|
||||||
.where(reporte.measure_url == medida.url, reporte.measure_version == medida.version)
|
|
||||||
.distinct()
|
|
||||||
.order_by(reporte.periodo_id)
|
|
||||||
)
|
|
||||||
return list(sesion.exec(consulta))
|
|
||||||
|
|
||||||
|
|
||||||
@tea_bp.get("/indicadores")
|
|
||||||
def listar_indicadores():
|
|
||||||
return jsonify([_resumen(id_, medida) for id_, medida in DEFINICIONES.items()])
|
|
||||||
|
|
||||||
|
|
||||||
@tea_bp.get("/indicadores/<indicador>/figuras/<figura>")
|
|
||||||
def get_figura(indicador: str, figura: str):
|
|
||||||
medida = DEFINICIONES.get(indicador)
|
|
||||||
if medida is None:
|
|
||||||
return _error("indicador desconocido", 404)
|
|
||||||
contrato = medida.extension.contrato
|
|
||||||
if figura not in FIGURAS_TEA[contrato]:
|
|
||||||
return _error(f"figura {figura!r} no es del contrato {contrato}", 404)
|
|
||||||
|
|
||||||
tema = request.args.get("tema", "claro")
|
|
||||||
if tema not in TEMAS:
|
|
||||||
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
|
||||||
try:
|
|
||||||
periodos = _periodos_de(request.args.get("periodos"))
|
|
||||||
except ValueError as error:
|
|
||||||
return _error(str(error), 400)
|
|
||||||
|
|
||||||
sesion = get_tea_session()
|
|
||||||
try:
|
|
||||||
if not periodos:
|
|
||||||
periodos = _periodos_con_reporte(sesion, medida)
|
|
||||||
if not periodos:
|
|
||||||
return _error("el indicador no tiene reportes calculados", 404)
|
|
||||||
texto = figura_json_tea(sesion, medida, periodos, figura, tablas=TABLAS, tema=tema)
|
|
||||||
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 Response(texto, mimetype="application/json")
|
|
||||||
|
|
||||||
|
|
||||||
@tea_bp.get("/pacientes/<int:pac_id>")
|
@tea_bp.get("/pacientes/<int:pac_id>")
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
"""Las rutas de indicadores, iguales para cada proyecto (CaCu, CaMa, TEA).
|
||||||
|
|
||||||
|
`registrar_indicadores` agrega a un blueprint:
|
||||||
|
|
||||||
|
GET /indicadores lista de indicadores
|
||||||
|
GET /indicadores/<id>/figuras/<figura>?periodos=&tema=
|
||||||
|
|
||||||
|
Las definiciones salen del kit (`measures_de`) 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.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import re
|
||||||
|
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.figuras import TEMAS, figura_json, figuras_de, periodos_con_reporte
|
||||||
|
from indicadores_kit.tablas import tablas_de
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
# Cómo se escribe un periodo de cada tipo (`registry/periodos.py`) y un ejemplo para el mensaje.
|
||||||
|
FORMATOS = {
|
||||||
|
"dia": (re.compile(r"\d{4}-\d{2}-\d{2}"), "AAAA-MM-DD"),
|
||||||
|
"semana_epidemiologica": (re.compile(r"\d{4}-SE\d{2}"), "AAAA-SEnn"),
|
||||||
|
"semana_habil": (re.compile(r"\d{4}-SH\d{2}"), "AAAA-SHnn"),
|
||||||
|
"semana_iso": (re.compile(r"\d{4}-W\d{2}"), "AAAA-Wnn"),
|
||||||
|
"mes": (re.compile(r"\d{4}-\d{2}"), "AAAA-MM"),
|
||||||
|
"bimestre": (re.compile(r"\d{4}-B[1-6]"), "AAAA-B1 a AAAA-B6"),
|
||||||
|
"trimestre": (re.compile(r"\d{4}-T[1-4]"), "AAAA-T1 a AAAA-T4"),
|
||||||
|
"semestre": (re.compile(r"\d{4}-S[12]"), "AAAA-S1 o AAAA-S2"),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _error(mensaje: str, codigo: int):
|
||||||
|
return jsonify({"error": mensaje}), codigo
|
||||||
|
|
||||||
|
|
||||||
|
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`)."""
|
||||||
|
return next((tipo for tipo in tipos if FORMATOS[tipo][0].fullmatch(periodo)), None)
|
||||||
|
|
||||||
|
|
||||||
|
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)`.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: un periodo mal formado, de un tipo que el indicador no
|
||||||
|
publica (`extension.publicacion.tipos_periodo`), o de tipos mezclados.
|
||||||
|
"""
|
||||||
|
if not texto:
|
||||||
|
return [], None
|
||||||
|
tipos = medida.extension.publicacion.tipos_periodo
|
||||||
|
periodos = list(dict.fromkeys(texto.split(",")))
|
||||||
|
encontrados = {_tipo_de(periodo, tipos) for periodo in periodos}
|
||||||
|
if None in encontrados:
|
||||||
|
formatos = "; ".join(FORMATOS[tipo][1] for tipo in tipos)
|
||||||
|
raise ValueError(f"Periodos mal formados: {texto!r}; este indicador publica {formatos}.")
|
||||||
|
if len(encontrados) > 1:
|
||||||
|
raise ValueError(f"Periodos de tipos distintos: {texto!r}; pida un solo tipo a la vez.")
|
||||||
|
return periodos, encontrados.pop()
|
||||||
|
|
||||||
|
|
||||||
|
def registrar_indicadores(
|
||||||
|
blueprint: Blueprint, proyecto: str, get_session: Callable[[], Session]
|
||||||
|
) -> None:
|
||||||
|
"""Agrega las dos rutas de indicadores de `proyecto` al blueprint.
|
||||||
|
|
||||||
|
`get_session` es la fábrica de `Persistance` (`get_<proyecto>_session`):
|
||||||
|
se llama en cada petición, no al registrar.
|
||||||
|
"""
|
||||||
|
definiciones = measures_de(proyecto) # fijas: se leen una vez
|
||||||
|
tablas = tablas_de(proyecto)
|
||||||
|
|
||||||
|
def listar_indicadores():
|
||||||
|
return jsonify(
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": id_,
|
||||||
|
"titulo": medida.title,
|
||||||
|
"contrato": medida.extension.contrato,
|
||||||
|
"figuras": figuras_de(medida),
|
||||||
|
"tipos_periodo": medida.extension.publicacion.tipos_periodo,
|
||||||
|
}
|
||||||
|
for id_, medida in definiciones.items()
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_figura(indicador: str, figura: str):
|
||||||
|
medida = definiciones.get(indicador)
|
||||||
|
if medida is None:
|
||||||
|
return _error("indicador desconocido", 404)
|
||||||
|
if figura not in figuras_de(medida):
|
||||||
|
return _error(
|
||||||
|
f"figura {figura!r} no es del contrato {medida.extension.contrato}", 404
|
||||||
|
)
|
||||||
|
|
||||||
|
tema = request.args.get("tema", "claro")
|
||||||
|
if tema not in TEMAS:
|
||||||
|
return _error(f"tema desconocido {tema!r}; use claro u oscuro", 400)
|
||||||
|
try:
|
||||||
|
periodos, tipo = periodos_pedidos(request.args.get("periodos"), medida)
|
||||||
|
except ValueError as error:
|
||||||
|
return _error(str(error), 400)
|
||||||
|
|
||||||
|
sesion = get_session()
|
||||||
|
try:
|
||||||
|
if not periodos:
|
||||||
|
# El primer tipo que publica el indicador.
|
||||||
|
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)
|
||||||
|
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 Response(texto, mimetype="application/json")
|
||||||
|
|
||||||
|
blueprint.add_url_rule("/indicadores", "listar_indicadores", listar_indicadores)
|
||||||
|
blueprint.add_url_rule(
|
||||||
|
"/indicadores/<indicador>/figuras/<figura>", "get_figura", get_figura
|
||||||
|
)
|
||||||
Reference in New Issue
Block a user