ceca8a03b5
KeyError es subclase de LookupError. El except LookupError de la ruta convertía cualquier error interno del kit en un 404 con su mensaje. Ahora solo un periodo sin reporte da 404; lo demás es un error del servidor.
110 lines
3.6 KiB
Python
110 lines
3.6 KiB
Python
import re
|
|
|
|
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 persistance.db import get_tea_session
|
|
from persistance.tea import pacientes_repository
|
|
|
|
tea_bp = Blueprint("tea", __name__)
|
|
|
|
# Las 18 definiciones de TEA, por id (nombre del archivo). Son fijas: se leen una vez.
|
|
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>")
|
|
def get_paciente(pac_id: int):
|
|
paciente = pacientes_repository.get(pac_id)
|
|
if paciente is None:
|
|
return jsonify({"error": "not found"}), 404
|
|
return jsonify(paciente.model_dump())
|
|
|
|
|
|
@tea_bp.post("/predict")
|
|
def predict():
|
|
model = TeaModel()
|
|
try:
|
|
return jsonify({"prediction": model.predict(data=None)})
|
|
except NotImplementedError as exc:
|
|
return jsonify({"error": str(exc)}), 501
|