127 lines
6.1 KiB
Python
127 lines
6.1 KiB
Python
"""`GET /<domain>/indicadores/<measure_id>`: a measure's periods answered on request, as a FHIR `Bundle` of `MeasureReport`s.
|
|
|
|
Query: `periodos` (comma-separated `dim_periodo` ids, required), `corte_evento` (`YYYY-MM-DD`, optional: facts dated
|
|
after it don't count) and `corte_conocimiento` (ISO date-time, optional: facts known after it don't count; by default
|
|
the start of the last load, so the same question asked before the next load reads the stored answer). The definitions
|
|
come from dbt's manifest (`DBT_MANIFEST`): proportions (`webapi.metrics`), compositions (`webapi.compositions`) and
|
|
durations (`webapi.durations`; without `corte_evento`, the day of the last load).
|
|
"""
|
|
|
|
import json
|
|
from collections.abc import Callable
|
|
from datetime import date, datetime, timezone
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
from core.indicadores.tipos import FechaHoraUTC
|
|
from flask import Blueprint, Response, jsonify, request
|
|
from sqlalchemy import column, func, select, table
|
|
|
|
from webapi.compositions import CompositionDefinition, answer_composition, composition_definitions, composition_report
|
|
from webapi.durations import DurationDefinition, answer_duration, duration_definitions, duration_report
|
|
from webapi.metrics import Question, UndecidedRule, answer, measure_definitions, measure_report
|
|
|
|
LOADS = table("carga", column("inicio", FechaHoraUTC))
|
|
|
|
|
|
def definitions_of(project: str, manifest: Path) -> dict:
|
|
"""Every measure the manifest defines for the domain, by its id (the end of its url). A measure that waits for
|
|
a validation (`meta.requiere_validacion`) is left out until it's given."""
|
|
return {i: d for i, d in _defined(project, manifest).items() if not _awaits_validation(d)}
|
|
|
|
|
|
@lru_cache
|
|
def _defined(project: str, manifest: Path) -> dict:
|
|
every = {**measure_definitions(manifest), **composition_definitions(manifest), **duration_definitions(manifest)}
|
|
return {d.measure_id: d for d in every.values() if d.url.startswith(f"{project}/")}
|
|
|
|
|
|
def _awaits_validation(definition) -> bool:
|
|
"""TEA's EEG alterations, the one validation so far, stay hidden until the domain expert validates them."""
|
|
if not definition.meta.get("requiere_validacion"):
|
|
return False
|
|
from webapi.fhir.tea import alterations_validated
|
|
|
|
return not alterations_validated()
|
|
|
|
|
|
def kpis_blueprint(project: str, repositories, manifest: Path, *,
|
|
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
|
"""The blueprint of a domain, to register with `url_prefix="/<domain>"`. `repositories` is the domain's
|
|
`persistance.<domain>` module."""
|
|
blueprint = Blueprint(f"{project}_kpis", __name__)
|
|
|
|
@blueprint.get("/indicadores")
|
|
def list_kpis():
|
|
"""The measures answered on request: id, url, version and scoring."""
|
|
return jsonify([{"id": i, "url": d.url, "version": d.version, "scoring": scoring_of(d)}
|
|
for i, d in sorted(definitions_of(project, manifest).items())])
|
|
|
|
@blueprint.get("/indicadores/<measure_id>")
|
|
def get_kpi(measure_id: str):
|
|
"""A measure's periods as a FHIR Bundle of MeasureReports, computed on request and kept in the history."""
|
|
definition = definitions_of(project, manifest).get(measure_id)
|
|
if definition is None:
|
|
return jsonify({"error": f"no hay un indicador {measure_id!r} calculado bajo pedido"}), 404
|
|
try:
|
|
periods = [p for p in request.args.get("periodos", "").split(",") if p]
|
|
if not periods:
|
|
raise ValueError("falta `periodos`")
|
|
event_cutoff = _date(request.args.get("corte_evento"))
|
|
knowledge_cutoff = _datetime(request.args.get("corte_conocimiento")) or _last_load(repositories)
|
|
except ValueError as error:
|
|
return jsonify({"error": str(error)}), 400
|
|
ask, serialize = ANSWERS[scoring_of(definition)]
|
|
entries = []
|
|
for period_id in periods:
|
|
period = repositories.dim_periodo_repository.get(period_id)
|
|
if period is None:
|
|
return jsonify({"error": f"no hay un periodo {period_id!r}"}), 404
|
|
question = Question(definition.url, period_id, event_cutoff, knowledge_cutoff)
|
|
try:
|
|
result = ask(project, definition, question, parameters=repositories.def_parametro_repository,
|
|
periods=repositories.dim_periodo_repository, history=repositories.history_repository,
|
|
queries=repositories.dbt_query_repository)
|
|
except UndecidedRule as error:
|
|
return jsonify({"error": str(error)}), 409
|
|
entries.append({"resource": serialize(definition, question, result, period, now())})
|
|
bundle = {"resourceType": "Bundle", "type": "searchset", "total": len(entries), "entry": entries}
|
|
return Response(json.dumps(bundle, ensure_ascii=False), mimetype="application/fhir+json")
|
|
|
|
return blueprint
|
|
|
|
|
|
ANSWERS = {"proportion": (answer, measure_report), "composition": (answer_composition, composition_report),
|
|
"continuous-variable": (answer_duration, duration_report)}
|
|
|
|
|
|
def scoring_of(definition) -> str:
|
|
if isinstance(definition, CompositionDefinition):
|
|
return "composition"
|
|
return "continuous-variable" if isinstance(definition, DurationDefinition) else "proportion"
|
|
|
|
|
|
def _date(value: str | None) -> date | None:
|
|
if not value:
|
|
return None
|
|
try:
|
|
return date.fromisoformat(value)
|
|
except ValueError:
|
|
raise ValueError(f"`corte_evento` no es una fecha AAAA-MM-DD: {value!r}") from None
|
|
|
|
|
|
def _datetime(value: str | None) -> datetime | None:
|
|
if not value:
|
|
return None
|
|
try:
|
|
moment = datetime.fromisoformat(value)
|
|
except ValueError:
|
|
raise ValueError(f"`corte_conocimiento` no es una fecha y hora ISO: {value!r}") from None
|
|
return moment if moment.tzinfo else moment.replace(tzinfo=timezone.utc)
|
|
|
|
|
|
def _last_load(repositories) -> datetime | None:
|
|
"""The start of the domain's last load: what's known now, and stable until the next load."""
|
|
_, ((last,),) = repositories.dbt_query_repository.rows(select(func.max(LOADS.c.inicio)))
|
|
return last
|