355 lines
18 KiB
Python
355 lines
18 KiB
Python
"""A domain's FHIR R4 endpoint, `/<domain>/fhir/`: its measures and, for TEA, its patients' screening.
|
|
|
|
GET metadata CapabilityStatement
|
|
GET Measure, Measure/<id> the measures (dbt's definitions)
|
|
GET Measure/<id>/$evaluate-measure one period: periodStart and periodEnd, or `periodo`
|
|
GET MeasureReport?measure=&periodo=|period= several periods (one report each), with `tipo-periodo`
|
|
POST Measure/$recalcular queues the domain's recomputation
|
|
GET CodeSystem, CodeSystem/<id>, ValueSet/<id> the project's code systems
|
|
GET EpisodeOfCare, EpisodeOfCare/$resumen-eeg TEA's follow-up list and its EEG summary (DEV only)
|
|
GET Patient/<pseudonym>/$resumen-tea TEA's patient summary (DEV only)
|
|
|
|
Every question of a measure takes `corte_evento` and `corte_conocimiento` as in `webapi.kpis`. Errors are
|
|
`OperationOutcome`s. Patient data are served only in DEV, on simulated data, each resource tagged `simulado`.
|
|
"""
|
|
|
|
from collections.abc import Callable
|
|
from datetime import date, datetime, timedelta, timezone
|
|
from pathlib import Path
|
|
|
|
from flask import Blueprint, request
|
|
from werkzeug.exceptions import HTTPException
|
|
|
|
from webapi.fhir.common import FHIR_VERSION, canonical, entry, fhir, outcome, page, searchset, simulated_data
|
|
from webapi.fhir.measures import fhir_id, labels, measure_report, measure_resource, measure_url
|
|
from webapi.fhir.terminology import code_systems, metric_value_set
|
|
from webapi.kpis import ANSWERS, _date, _datetime, _last_load, definitions_of, scoring_of
|
|
from webapi.metrics import Question, UndecidedRule
|
|
|
|
TEA_SEARCH = ("status", "date", "etapa", "fecha-etapa", "grupo-edad", "mchat", "css", "resultado-eeg", "alteracion")
|
|
|
|
|
|
def fhir_blueprint(project: str, repositories, manifest: Path, *, with_patients: bool = False,
|
|
now: Callable[[], datetime] = lambda: datetime.now(timezone.utc)) -> Blueprint:
|
|
"""The blueprint of a domain, to register with `url_prefix="/<domain>/fhir"`. `repositories` is the domain's
|
|
`persistance.<domain>` module; `with_patients` adds TEA's patient routes (only in DEV)."""
|
|
blueprint = Blueprint(f"{project}_fhir", __name__)
|
|
titles = labels(manifest)
|
|
patients = with_patients and project == "tea"
|
|
|
|
def definitions() -> dict:
|
|
"""The domain's measures by their FHIR id; `definition()` also takes the dbt id."""
|
|
return {fhir_id(d): d for d in definitions_of(project, manifest).values()}
|
|
|
|
def definition_of(measure_id: str):
|
|
return definitions().get(measure_id.replace("_", "-"))
|
|
|
|
def measure(definition) -> dict:
|
|
title, description = titles.get(definition.metric, (definition.measure_id, ""))
|
|
return measure_resource(definition, title, description)
|
|
|
|
@blueprint.app_errorhandler(HTTPException)
|
|
def http_error(error: HTTPException):
|
|
"""Under `/<domain>/fhir/`, an error is an `OperationOutcome`, also for a route that doesn't exist there;
|
|
elsewhere, Flask's own answer."""
|
|
if "/fhir/" not in request.path and not request.path.endswith("/fhir"):
|
|
return error
|
|
code = {404: "not-found", 405: "not-supported"}.get(error.code, "exception")
|
|
return outcome(error.code, code, error.description or error.name)
|
|
|
|
@blueprint.get("/metadata")
|
|
def capability_statement():
|
|
resources = [
|
|
{"type": "Measure", "interaction": [{"code": "read"}, {"code": "search-type"}],
|
|
"operation": [{"name": "evaluate-measure", "definition": "http://hl7.org/fhir/OperationDefinition/Measure-evaluate-measure"},
|
|
{"name": "recalcular", "definition": canonical("OperationDefinition/recalcular")}]},
|
|
{"type": "MeasureReport", "interaction": [{"code": "search-type"}],
|
|
"searchParam": [{"name": n, "type": t} for n, t in (("measure", "reference"), ("period", "date"),
|
|
("periodo", "token"), ("tipo-periodo", "token"))]},
|
|
{"type": "CodeSystem", "interaction": [{"code": "read"}, {"code": "search-type"}]},
|
|
]
|
|
if patients:
|
|
resources += [
|
|
{"type": "EpisodeOfCare", "interaction": [{"code": "search-type"}],
|
|
"searchParam": [{"name": n, "definition": canonical(f"SearchParameter/episode-{n}"),
|
|
"type": "date" if n in ("date", "fecha-etapa") else
|
|
"number" if n in ("mchat", "css") else "token"} for n in TEA_SEARCH],
|
|
"searchInclude": ["*"],
|
|
"operation": [{"name": "resumen-eeg", "definition": canonical("OperationDefinition/resumen-eeg")}]},
|
|
{"type": "Patient", "operation": [{"name": "resumen-tea",
|
|
"definition": canonical("OperationDefinition/resumen-tea")}]},
|
|
{"type": "ValueSet", "interaction": [{"code": "read"}]},
|
|
]
|
|
return fhir({"resourceType": "CapabilityStatement", "status": "active", "date": now().date().isoformat(),
|
|
"kind": "instance", "fhirVersion": FHIR_VERSION, "format": ["application/fhir+json"],
|
|
"implementation": {"description": f"ISSSTELEON, {project.upper()}", "url": request.url_root},
|
|
"rest": [{"mode": "server", "resource": resources}]})
|
|
|
|
@blueprint.get("/Measure")
|
|
def measures():
|
|
found = [measure(d) for _, d in sorted(definitions().items())]
|
|
if url := request.args.get("url"):
|
|
found = [m for m in found if m["url"] == url]
|
|
count, offset = page()
|
|
return fhir(searchset([entry(m) for m in found[offset:offset + count]], len(found), count, offset))
|
|
|
|
@blueprint.get("/Measure/<measure_id>")
|
|
def read_measure(measure_id: str):
|
|
definition = definition_of(measure_id)
|
|
if definition is None:
|
|
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
|
return fhir(measure(definition))
|
|
|
|
def ask(definition, period, event_cutoff, knowledge_cutoff):
|
|
question = Question(definition.url, period.periodo_id, event_cutoff, knowledge_cutoff)
|
|
answer_of, _ = ANSWERS[scoring_of(definition)]
|
|
result = answer_of(project, definition, question, parameters=repositories.def_parametro_repository,
|
|
periods=repositories.dim_periodo_repository, history=repositories.history_repository,
|
|
queries=repositories.dbt_query_repository)
|
|
return measure_report(definition, question, result, period, now())
|
|
|
|
def cutoffs():
|
|
return (_date(request.args.get("corte_evento")),
|
|
_datetime(request.args.get("corte_conocimiento")) or _last_load(repositories))
|
|
|
|
@blueprint.get("/Measure/<measure_id>/$evaluate-measure")
|
|
def evaluate_measure(measure_id: str):
|
|
definition = definition_of(measure_id)
|
|
if definition is None:
|
|
return outcome(404, "not-found", f"no hay un indicador {measure_id!r}")
|
|
try:
|
|
event_cutoff, knowledge_cutoff = cutoffs()
|
|
period = _period_asked(repositories)
|
|
except ValueError as error:
|
|
return outcome(400, "invalid", str(error))
|
|
except LookupError as error:
|
|
return outcome(404, "not-found", str(error))
|
|
try:
|
|
return fhir(ask(definition, period, event_cutoff, knowledge_cutoff))
|
|
except UndecidedRule as error:
|
|
return outcome(409, "business-rule", str(error))
|
|
|
|
@blueprint.get("/MeasureReport")
|
|
def measure_reports():
|
|
asked = request.args.get("measure", "")
|
|
by_url = {measure_url(d): d for d in definitions().values()}
|
|
definition = by_url.get(asked.split("|")[0]) or definition_of(asked)
|
|
if definition is None:
|
|
return outcome(400, "required", "falta `measure` (el canónico o el id de un indicador)")
|
|
try:
|
|
event_cutoff, knowledge_cutoff = cutoffs()
|
|
periods = _periods_searched(repositories)
|
|
count, offset = page()
|
|
except ValueError as error:
|
|
return outcome(400, "invalid", str(error))
|
|
except LookupError as error:
|
|
return outcome(404, "not-found", str(error))
|
|
try:
|
|
reports = [ask(definition, p, event_cutoff, knowledge_cutoff) for p in periods[offset:offset + count]]
|
|
except UndecidedRule as error:
|
|
return outcome(409, "business-rule", str(error))
|
|
return fhir(searchset([entry(r) for r in reports], len(periods), count, offset))
|
|
|
|
@blueprint.post("/Measure/$recalcular")
|
|
def recompute():
|
|
from webapi.recomputation import RecomputationQueue
|
|
|
|
RecomputationQueue().request_run(project)
|
|
return outcome(202, "informational", f"se pidió recalcular los indicadores de {project}", severity="information")
|
|
|
|
@blueprint.get("/CodeSystem")
|
|
def code_system_search():
|
|
systems = list(code_systems(project).values())
|
|
return fhir(searchset([entry(s) for s in systems], len(systems), len(systems) or 1, 0))
|
|
|
|
@blueprint.get("/CodeSystem/<system_id>")
|
|
def read_code_system(system_id: str):
|
|
system = code_systems(project).get(system_id)
|
|
return fhir(system) if system else outcome(404, "not-found", f"no hay un sistema de códigos {system_id!r}")
|
|
|
|
if patients:
|
|
_patient_routes(blueprint, repositories, now)
|
|
return blueprint
|
|
|
|
|
|
def _period_asked(repositories):
|
|
"""The `dim_periodo` row the question names: `periodo`, or `periodStart` and `periodEnd` (inclusive)."""
|
|
if periodo := request.args.get("periodo"):
|
|
period = repositories.dim_periodo_repository.get(periodo)
|
|
if period is None:
|
|
raise LookupError(f"no hay un periodo {periodo!r}")
|
|
return period
|
|
start, end = request.args.get("periodStart"), request.args.get("periodEnd")
|
|
if not (start and end):
|
|
raise ValueError("falta el periodo: `periodStart` y `periodEnd`, o `periodo`")
|
|
start, end = date.fromisoformat(start), date.fromisoformat(end)
|
|
for period in repositories.dim_periodo_repository.list(limit=10000, inicio=start):
|
|
if period.fin - timedelta(days=1) == end:
|
|
return period
|
|
raise LookupError(f"no hay un periodo de {start} a {end}")
|
|
|
|
|
|
def _periods_searched(repositories) -> list:
|
|
"""The periods of a `MeasureReport` search: `periodo` (comma-separated ids), or the periods of `tipo-periodo`
|
|
within `period=ge…` and `period=le…`."""
|
|
if ids := [p for p in request.args.get("periodo", "").split(",") if p]:
|
|
periods = [repositories.dim_periodo_repository.get(i) for i in ids]
|
|
if missing := [i for i, p in zip(ids, periods) if p is None]:
|
|
raise LookupError(f"no hay un periodo {missing[0]!r}")
|
|
return periods
|
|
kind = request.args.get("tipo-periodo")
|
|
if not kind:
|
|
raise ValueError("falta `periodo` o `tipo-periodo` con `period`")
|
|
low, high = date.min, date.max
|
|
for value in request.args.getlist("period"):
|
|
if value.startswith("ge"):
|
|
low = date.fromisoformat(value[2:])
|
|
elif value.startswith("le"):
|
|
high = date.fromisoformat(value[2:])
|
|
else:
|
|
raise ValueError(f"`period` admite ge y le: {value!r}")
|
|
found = repositories.dim_periodo_repository.list(limit=10000, tipo=kind)
|
|
return sorted((p for p in found if p.inicio >= low and p.fin - timedelta(days=1) <= high), key=lambda p: p.inicio)
|
|
|
|
|
|
def _bound(name: str) -> tuple[float | None, float | None]:
|
|
"""A number search parameter's bounds: `mchat=ge8&mchat=le20`, or one exact value."""
|
|
low = high = None
|
|
for value in request.args.getlist(name):
|
|
if value.startswith("ge"):
|
|
low = float(value[2:])
|
|
elif value.startswith("le"):
|
|
high = float(value[2:])
|
|
else:
|
|
low = high = float(value)
|
|
return low, high
|
|
|
|
|
|
def _dates(name: str) -> tuple[date | None, date | None]:
|
|
low = high = None
|
|
for value in request.args.getlist(name):
|
|
if value.startswith("ge"):
|
|
low = date.fromisoformat(value[2:])
|
|
elif value.startswith("le"):
|
|
high = date.fromisoformat(value[2:])
|
|
else:
|
|
low = high = date.fromisoformat(value)
|
|
return low, high
|
|
|
|
|
|
def _patient_routes(blueprint: Blueprint, repositories, now) -> None:
|
|
from webapi.fhir import tea
|
|
|
|
queries = repositories.dbt_query_repository
|
|
|
|
def matching():
|
|
"""The episodes the search's parameters select, at its cut-off (`date=le…`, by default today)."""
|
|
unknown = [k for k in request.args if not k.startswith("_") and k not in TEA_SEARCH]
|
|
if unknown:
|
|
raise ValueError(f"parámetro de búsqueda no admitido: {unknown[0]!r}")
|
|
if request.args.get("alteracion") and not tea.alterations_validated():
|
|
raise PermissionError("las alteraciones del EEG no se muestran hasta validar sus referencias")
|
|
since, cutoff = _dates("date")
|
|
cutoff = cutoff or now().date()
|
|
stage_from, stage_to = _dates("fecha-etapa")
|
|
mchat, css = _bound("mchat"), _bound("css")
|
|
|
|
def within(value, bounds):
|
|
low, high = bounds
|
|
return value is not None and (low is None or value >= low) and (high is None or value <= high)
|
|
|
|
found = []
|
|
for e in tea.episodes(queries, cutoff):
|
|
stage = e.stage
|
|
if since is not None and e.finished and stage[1] < since:
|
|
continue
|
|
if (status := request.args.get("status")) and status != ("finished" if e.finished else "active"):
|
|
continue
|
|
if (etapa := request.args.get("etapa")) and (stage is None or stage[0] not in etapa.split(",")):
|
|
continue
|
|
if (stage_from or stage_to) and (stage is None or not within(stage[1].toordinal(), (
|
|
stage_from and stage_from.toordinal(), stage_to and stage_to.toordinal()))):
|
|
continue
|
|
if (group := request.args.get("grupo-edad")) and e.child["grupo_edad"] not in group.split(","):
|
|
continue
|
|
if request.args.getlist("mchat") and not within(e.child["mchat"], mchat):
|
|
continue
|
|
if request.args.getlist("css") and not within(e.child["css_ados2"], css):
|
|
continue
|
|
if result := request.args.get("resultado-eeg"):
|
|
shown = e.eeg_result if tea.alterations_validated() else (
|
|
"sin-eeg-valido" if e.eeg_result == "sin-eeg-valido" else "valido")
|
|
if shown not in result.split(","):
|
|
continue
|
|
if (alteration := request.args.get("alteracion")) and alteration not in e.alterations():
|
|
continue
|
|
found.append(e)
|
|
return sorted(found, key=lambda e: e.pseudonym)
|
|
|
|
@blueprint.get("/EpisodeOfCare")
|
|
def episodes_of_care():
|
|
try:
|
|
found = matching()
|
|
count, offset = page()
|
|
except ValueError as error:
|
|
return tea_outcome(400, "invalid", error)
|
|
except PermissionError as error:
|
|
return tea_outcome(403, "forbidden", error)
|
|
simulated = simulated_data()
|
|
shown = found[offset:offset + count]
|
|
entries = [entry(tea.episode_of_care(e, simulated)) for e in shown]
|
|
if request.args.get("_include"):
|
|
entries += [entry(r, "include") for e in shown for r in _included(tea, queries, e, simulated)]
|
|
return fhir(searchset(entries, len(found), count, offset))
|
|
|
|
@blueprint.get("/EpisodeOfCare/$resumen-eeg")
|
|
def eeg_summary():
|
|
try:
|
|
found = matching()
|
|
except ValueError as error:
|
|
return tea_outcome(400, "invalid", error)
|
|
except PermissionError as error:
|
|
return tea_outcome(403, "forbidden", error)
|
|
valid = [e for e in found if e.eeg_result != "sin-eeg-valido"]
|
|
parameters = [{"name": "con_eeg_valido", "valueInteger": len(valid)},
|
|
{"name": "sin_eeg_valido", "valueInteger": len(found) - len(valid)}]
|
|
if tea.alterations_validated():
|
|
by_alteration: dict[str, int] = {}
|
|
for e in valid:
|
|
for code in e.alterations():
|
|
by_alteration[code] = by_alteration.get(code, 0) + 1
|
|
parameters += [{"name": "normales", "valueInteger": sum(e.eeg_result == "normal" for e in valid)},
|
|
{"name": "anormales", "valueInteger": sum(e.eeg_result == "anormal" for e in valid)},
|
|
*({"name": "por_alteracion", "part": [{"name": "alteracion", "valueCode": code},
|
|
{"name": "pacientes", "valueInteger": n}]}
|
|
for code, n in sorted(by_alteration.items()))]
|
|
return fhir({"resourceType": "Parameters", "parameter": parameters})
|
|
|
|
@blueprint.get("/Patient/<pseudonym>/$resumen-tea")
|
|
def patient_summary(pseudonym: str):
|
|
pac_id = tea.patient_of(queries, pseudonym)
|
|
if pac_id is None:
|
|
return outcome(404, "not-found", f"no hay un paciente {pseudonym!r}")
|
|
return fhir(tea.patient_summary(queries, pac_id, now().date(), simulated_data()))
|
|
|
|
@blueprint.get("/ValueSet/tea-alteracion")
|
|
def alteration_types():
|
|
return fhir(metric_value_set())
|
|
|
|
|
|
def tea_outcome(status: int, code: str, error: Exception):
|
|
return outcome(status, code, str(error))
|
|
|
|
|
|
def _included(tea, queries, e, simulated: bool) -> list[dict]:
|
|
"""What an episode's search includes: its patient, its steps, its M-CHAT, its diagnosis and its study EEG."""
|
|
from sqlalchemy import select
|
|
|
|
persons = tea._rows(queries, select(tea.PERSONS).where(tea.PERSONS.c.pac_id == e.child["pac_id"]))
|
|
resources = [tea.patient(e.child["pac_id"], persons[0]["fecha_nacimiento"] if persons else None, simulated),
|
|
tea.care_plan(e, simulated)]
|
|
resources += [r for r in (tea.mchat_observation(e, simulated), tea.condition(e, simulated)) if r]
|
|
if (eeg := e.study_eeg()) is not None:
|
|
resources += tea.eeg_resources(eeg, e.pseudonym, e.metrics, [], simulated)
|
|
return resources
|