b1bbbc25b4
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
109 lines
5.4 KiB
Python
109 lines
5.4 KiB
Python
"""The routes of CaMa's descriptive analysis, under `/cama/analisis`.
|
|
|
|
GET /cama/analisis what the analysis offers: dimensions, measures, horizons and what isn't available
|
|
GET /cama/analisis/resumen the indicator cards of the selection
|
|
GET /cama/analisis/distribucion patients by BI-RADS, age group or biopsy result
|
|
GET /cama/analisis/comparacion the share of cases among biopsied patients, by BI-RADS or age group, and its test
|
|
GET /cama/analisis/mapa BI-RADS by age group
|
|
GET /cama/analisis/tendencia reports of mammogram and biopsy per month or semester (activity; takes only the cut-off)
|
|
GET /cama/analisis/indicadores patients of the cohort by BI-RADS category (the aggregate the tab has always read)
|
|
|
|
The selection (cut-off, window, filters) is the follow-up list's, with its suppression, its revision and its errors.
|
|
"""
|
|
|
|
import json
|
|
import re
|
|
from collections.abc import Callable
|
|
|
|
from flask import Blueprint, Response, current_app, jsonify, request
|
|
from sqlmodel import Session
|
|
from werkzeug.datastructures import MultiDict
|
|
|
|
from webapi.cama_analysis import service
|
|
from webapi.cama_follow_up.access import configured_access
|
|
from webapi.cama_follow_up.cohort import CohorteNoDisponible
|
|
from webapi.cama_follow_up.listing import GrupoPequeno, PedidoInvalido, RevisionDistinta
|
|
from webapi.cama_follow_up.routes import CONTEXTO, FILTROS, _requested
|
|
|
|
COMUNES = ("corte", "meses", *CONTEXTO, *FILTROS)
|
|
ENTEROS = {"horizonte": "horizonte", "periodos": "periodos"}
|
|
TEXTOS = {"por": "por", "medida": "medida", "tipo": "tipo", "filas": "filas_por", "columnas": "columnas_por"}
|
|
|
|
|
|
def analysis_blueprint(get_session: Callable[[], Session]) -> Blueprint:
|
|
"""The blueprint of the analysis, to register with `url_prefix="/cama/analisis"`."""
|
|
blueprint = Blueprint("cama_analisis", __name__)
|
|
blueprint.before_request(configured_access)
|
|
|
|
@blueprint.after_request
|
|
def no_store(response):
|
|
response.headers["Cache-Control"] = "no-store"
|
|
return response
|
|
|
|
def answer(build, propios: tuple[str, ...], comunes: tuple[str, ...]):
|
|
reader = current_app.config.get('CAMA_COHORT_READER')
|
|
if build is service.indicadores and 'CAMA_COHORT_READER' in current_app.config and not getattr(reader, '_cama_default_reader', False):
|
|
from webapi.cama_analysis_legacy import indicators
|
|
return indicators()
|
|
try:
|
|
pedido = _pedido(request.args, propios, comunes)
|
|
except ValueError as error:
|
|
return jsonify({"error": str(error)}), 400
|
|
sesion = get_session()
|
|
try:
|
|
cuerpo = build(sesion, **pedido)
|
|
except PedidoInvalido as error:
|
|
return jsonify({"error": str(error)}), 400
|
|
except GrupoPequeno as error:
|
|
return jsonify({"error": str(error), "motivo": "supresion"}), 403
|
|
except RevisionDistinta as error:
|
|
return jsonify({"error": str(error), "motivo": "revision"}), 409
|
|
except CohorteNoDisponible as error:
|
|
return jsonify({"error": str(error), "motivo": "cohorte"}), 503
|
|
finally:
|
|
sesion.close()
|
|
return Response(json.dumps(cuerpo, ensure_ascii=False), mimetype="application/json")
|
|
|
|
routes = {
|
|
"": (service.catalogo, ()), "/resumen": (service.resumen, ("horizonte",)),
|
|
"/distribucion": (service.distribucion, ("por",)), "/comparacion": (service.comparacion, ("por", "medida")),
|
|
"/mapa": (service.mapa, ("filas", "columnas", "medida")), "/tendencia": (service.tendencia, ("tipo", "periodos"), ("corte",)),
|
|
"/indicadores": (service.indicadores, ()),
|
|
}
|
|
for ruta, (construye, propios, *resto) in routes.items():
|
|
comunes = resto[0] if resto else COMUNES
|
|
blueprint.add_url_rule(ruta, endpoint=ruta.strip("/") or "catalogo",
|
|
view_func=(lambda c=construye, p=propios, k=comunes: answer(c, p, k)), methods=["GET"])
|
|
return blueprint
|
|
|
|
|
|
def _pedido(args, propios: tuple[str, ...], admitidos: tuple[str, ...] = COMUNES) -> dict:
|
|
"""The request's parameters: the selection's (typed by the follow-up's own parser) and this route's.
|
|
|
|
A route that isn't about the cohort (the trend) admits only the cut-off: window, filters and context are refused.
|
|
"""
|
|
for nombre in args:
|
|
if nombre not in (*admitidos, *propios):
|
|
raise ValueError(f"parámetro desconocido {nombre!r}; se admite {list(admitidos + propios)}.")
|
|
comunes = MultiDict((k, v) for k, v in args.items(multi=True) if k in admitidos)
|
|
base = _requested(comunes, admitidos)
|
|
if admitidos == COMUNES:
|
|
pedido = {"corte": base.get("corte"), "meses": base.get("meses"), "filtros": base.get("filtros", {}),
|
|
"contexto": tuple(base.get(k) for k in CONTEXTO), "hoy": None}
|
|
else:
|
|
pedido = {"corte": base.get("corte"), "hoy": None}
|
|
for nombre in propios:
|
|
if len(args.getlist(nombre)) > 1:
|
|
raise ValueError(f"parámetro repetido {nombre!r}.")
|
|
if nombre in args:
|
|
valor = args[nombre]
|
|
if nombre in ENTEROS:
|
|
if not re.fullmatch(r"\d{1,6}", valor):
|
|
raise ValueError(f"{nombre} debe ser un entero; llegó {valor!r}")
|
|
pedido[ENTEROS[nombre]] = int(valor)
|
|
else:
|
|
if not valor:
|
|
raise ValueError(f"{nombre} no puede ir vacío.")
|
|
pedido[TEXTOS[nombre]] = valor
|
|
return pedido
|