"""The FHIR R4B API, one base per domain (`/{domain}/fhir`): read, the searches the WebApp uses, paging, and a CapabilityStatement built from these routes themselves. Resources are built by Core's mappers from the rows Persistance reads; nothing is computed here beyond counting a few thousand rows (measures) and ordering the follow-up list.""" import unicodedata from collections import defaultdict from datetime import date, datetime from typing import Annotated, Any from urllib.parse import urlencode from dagster_graphql import DagsterGraphQLClient from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request from fastapi.responses import Response from fhir.resources.R4B.bundle import Bundle from fhir.resources.R4B.capabilitystatement import CapabilityStatement from fhir.resources.R4B.operationoutcome import OperationOutcome from fhir.resources.R4B.parameters import Parameters from fhir.resources.R4B.resource import Resource from core import catalog from core import fhir as f from core import measures as m from core.domains import Domain, measures, part from core.follow_up import window_start from core.pipeline import ID_PATTERN from core.tea import fhir as tea_fhir from core.tea.follow_up import FILTERS as TEA_FILTERS from persistance import config_log, readers from persistance import fhir as reads from persistance import measures as measure_reads from webapi.ingest import submit from webapi.runs import dagster FHIR_JSON = "application/fhir+json" PAGE, MAX_PAGE = 50, 200 REVINCLUDES = ("DiagnosticReport:subject", "RiskAssessment:subject", "Observation:subject") router = APIRouter(prefix="/{domain}/fhir", tags=["fhir"]) _OK = {200: {"content": {FHIR_JSON: {"schema": {"type": "object"}}}, "description": "FHIR"}} def fhir(resource: Resource) -> Response: return Response(resource.model_dump_json(exclude_none=True), media_type=FHIR_JSON) def outcome(status: int, text: str) -> Response: issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid", "diagnostics": text} # fmt: skip return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True), status_code=status, media_type=FHIR_JSON) # fmt: skip def _clinical(domain: Domain): """The domain's follow-up module: a domain serves clinical resources once it has one.""" if (found := part(domain, "follow_up")) is None: raise HTTPException(404, f"no clinical resources for {domain.value} yet") return found def _cutoff(domain: Domain, asked: date | None) -> date: """The day asked for, or by default the last day with data in the domain (up to today).""" if asked is not None: return asked return reads.last_data_day(domain.value) or date.today() def _page(count: int | None, offset: int) -> tuple[int, int]: count = PAGE if count is None else count if not 0 <= count <= MAX_PAGE or offset < 0: raise HTTPException(422, f"_count goes from 0 to {MAX_PAGE}; _offset from 0") return count, offset def bundle(request: Request, matches: list[Resource], total: int, count: int, offset: int, included: list[Resource] = (), applied: dict | None = None) -> Response: # fmt: skip """A searchset page of `matches`, with links to its neighbours. The links carry the parameters as applied (`applied`: defaults the server chose).""" base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0] def link(relation: str, at: int) -> dict: params = {**(applied or {}), "_offset": at, "_count": count} query = [(k, v) for k, v in request.query_params.multi_items() if k not in params] url = request.url.replace(query=urlencode([*query, *params.items()], doseq=True)) return {"relation": relation, "url": str(url)} links = [link("self", offset)] if offset + count < total: links.append(link("next", offset + count)) if offset > 0: links.append(link("previous", max(offset - count, 0))) groups = (("match", matches), ("include", included)) entries = [{"fullUrl": f"{base}/{r.get_resource_type()}/{r.id}", "resource": r, "search": {"mode": mode}} for mode, group in groups for r in group] # fmt: skip found = Bundle(type="searchset", total=total, link=links, entry=entries or None) return fhir(found) def _sliced(found: list, count: int, offset: int) -> list: return found[offset:offset + count] # fmt: skip # --- Patient --------------------------------------------------------------------------------- _WINDOW = Query( None, alias="follow-up-window", description="months: the domain's follow-up list over that window up to the cut-off", ) _START = Query( None, alias="follow-up-start", description="explicit window start that overrides follow-up-window", ) _CUTOFF = Query(None, alias="follow-up-cutoff", description="default: the last day with data") _STATUS = Query(None, alias="follow-up-status") @router.get( "/Patient/$eeg-summary", responses=_OK, response_class=Response, description="EEG counts for the follow-up list. Without a window or start, " "use the whole history.", ) def eeg_summary( request: Request, domain: Domain, window: int | None = _WINDOW, start: date | None = _START, cutoff: date | None = _CUTOFF, status: str | None = _STATUS, ) -> Response: fu = _clinical(domain) if not hasattr(fu, "summary"): return outcome(404, f"no EEG summary for {domain.value}") at = _cutoff(domain, cutoff) try: rows, _, _ = _patient_rows(request, domain, fu, at, window, start, cutoff, status, whole_history=True) # fmt: skip except ValueError as exc: return outcome(422, str(exc)) counts = fu.summary(rows) parameters = [ {"name": name, "valueInteger": counts[name]} for name in ("valid", "not_valid", "normal", "abnormal") ] for entry in counts["by_alteration"]: parameters.append({"name": "by_alteration", "part": [ {"name": "alteration", "valueCode": entry["alteration"]}, {"name": "patients", "valueInteger": entry["patients"]}, ]}) # fmt: skip return fhir(Parameters(parameter=parameters)) @router.get("/Patient/{id}", responses=_OK, response_class=Response) def read_patient(domain: Domain, id: str) -> Response: fu = _clinical(domain) (row,) = reads.rows(domain.value, "person", id=id) or [None] if row is None: (link,) = reads.rows(domain.value, "replaced", id=id) or [None] if link is None: raise HTTPException(404, f"no Patient/{id}") return fhir(f.replaced_patient(id, link["replaced_by"])) status = fu.status(row, _cutoff(domain, None)) (found,) = _with_identity(domain, [{**row, "status": status}]) return fhir(f.patient(found, fu.STATUS_SYSTEM)) def _with_identity(domain: Domain, rows: list[dict]) -> list[dict]: """Persons with their names, identifiers and the ids they replaced.""" persons = [r["person_id"] for r in rows] names, ids, replaces = {}, {}, {} for r in reads.rows(domain.value, "names", persons=persons): names.setdefault(r["person_id"], []).append(r["text"]) for r in reads.rows(domain.value, "identifiers", persons=persons): ids.setdefault(r["person_id"], []).append((r["system"], r["value"])) for r in reads.rows(domain.value, "replaces", persons=persons): replaces.setdefault(r["replaced_by"], []).append(r["person_id"]) return [ {**r, "names": names.get(p, []), "identifiers": ids.get(p, []), "replaces": replaces.get(p, [])} for r in rows if (p := r["person_id"]) ] # fmt: skip def _folded(text: str) -> str: return "".join(c for c in unicodedata.normalize("NFKD", text.casefold()) if not unicodedata.combining(c)) # fmt: skip def _matches(row: dict, name: str | None, identifier: str | None) -> bool: if name: words = _folded(name).split() if not any(all(any(w.startswith(q) for w in _folded(n).split()) for q in words) for n in row["names"]): # fmt: skip return False if identifier: system, _, value = identifier.rpartition("|") if not any((not system or s == system) and v.casefold() == value.strip().casefold() for s, v in row["identifiers"]): # fmt: skip return False return True @router.get( "/Patient", responses=_OK, response_class=Response, description=( "Patients, or the domain's follow-up list selected by window or start.\n\n" "For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without\n" "follow-up episodes appear only in the plain search." ), ) def search_patient( request: Request, domain: Domain, _id: str | None = Query(None, alias="_id"), window: int | None = _WINDOW, start: date | None = _START, cutoff: date | None = _CUTOFF, status: str | None = _STATUS, name: str | None = Query( None, description="each word starts a word of her name (case and accents ignored)" ), identifier: str | None = Query( None, description="[system|]value: a CURP or record number (case ignored)" ), sort: str = Query("-recent", alias="_sort", description="-recent or -risk-"), horizon: float | None = Query(None, alias="risk-horizon", description="years"), revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"), include: list[str] = Query([], alias="_include:iterate", description="DiagnosticReport:result"), _count: int | None = Query(None), _offset: int = Query(0), ) -> Response: fu = _clinical(domain) count, offset = _page(_count, _offset) at = _cutoff(domain, cutoff) horizon = fu.DEFAULT_HORIZON if horizon is None else horizon try: rows, listed, applied = _patient_rows( request, domain, fu, at, window, start, cutoff, status, sort, _id ) except ValueError as exc: return outcome(422, str(exc)) if name or identifier: found = {r["person_id"] for r in _with_identity(domain, rows) if _matches(r, name, identifier)} # fmt: skip rows = [r for r in rows if r["person_id"] in found] persons = [r["person_id"] for r in rows] risks: dict[str, list[dict]] = {} if domain != Domain.TEA and (listed and sort != "-recent" or "RiskAssessment:subject" in revinclude): # fmt: skip for r in reads.rows(domain.value, "risk", persons=persons): risks.setdefault(r["person_id"], []).append(r) if listed: rows = fu.ordered(rows, sort, risks, horizon) page = _sliced(rows, count, offset) mine = {r["person_id"] for r in page} included = _included(domain, revinclude, include, sorted(mine), at, {p: v for p, v in risks.items() if p in mine}) # fmt: skip patients = [f.patient(r, fu.STATUS_SYSTEM) for r in _with_identity(domain, page)] return bundle(request, patients, len(rows), count, offset, included, applied) # fmt: skip def _patient_rows( request: Request, domain: Domain, fu, at: date, window: int | None, start: date | None, cutoff: date | None, status: str | None, sort: str = "-recent", _id: str | None = None, *, whole_history: bool = False, ) -> tuple[list[dict], bool, dict]: filters = { name: request.query_params.getlist(name) for name in (TEA_FILTERS if domain == Domain.TEA else ()) if name in request.query_params } if filters: fu.matches({}, filters) listed = ( whole_history or start is not None or window is not None or bool(filters) or (hasattr(fu, "FILTERS") and cutoff is not None) ) persons = reads.rows(domain.value, "persons") applied = {} if listed: if sort not in fu.SORTS: raise HTTPException(422, f"_sort is one of {fu.SORTS}") if start is None and window is not None: if window not in fu.WINDOWS: raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}") start = window_start(at, window) start = start or date.min params = {"start": start.isoformat(), "cutoff": at.isoformat()} person = {r["person_id"]: r for r in persons} rows = [ {**person[r["person_id"]], **r} for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at) ] applied = {"follow-up-cutoff": at.isoformat(), **filters} else: rows = [{**r, "status": fu.status(r, at)} for r in persons] if _id: rows = [r for r in rows if r["person_id"] in _id.split(",")] if status: rows = [r for r in rows if r["status"] in status.split(",")] if filters: rows = [r for r in rows if fu.matches(r, filters)] return rows, listed, applied def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str], at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip allowed = _revincludes(domain) unknown = set(revinclude) - set(allowed) | set(include) - {"DiagnosticReport:result"} if unknown: raise HTTPException(422, f"cannot include {sorted(unknown)}") found: list[Resource] = [] reports = "DiagnosticReport:subject" in revinclude observations = "Observation:subject" in revinclude or ( reports and "DiagnosticReport:result" in include ) if reports or observations: for r in _studies(domain, persons, at.isoformat()): kind = r.get_resource_type() if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations): found.append(r) if "Condition:subject" in revinclude: found += [f.condition(r) for r in reads.rows(domain.value, "condition", persons=persons, cutoff=at.isoformat())] # fmt: skip if "RiskAssessment:subject" in revinclude: if domain == Domain.TEA: found += _tea_risks(persons, at.isoformat()) else: found += _risk_assessments([r for p in persons for r in risks.get(p, [])]) return found def _revincludes(domain: Domain) -> tuple[str, ...]: return (*REVINCLUDES, "Condition:subject") if domain == Domain.TEA else REVINCLUDES # --- clinical searches: by subject ---------------------------------------------------------- def _subjects(subject: str | None) -> list[str]: if not subject: raise HTTPException(422, "subject is required (Patient/, comma-separated)") return [s.removeprefix("Patient/") for s in subject.split(",")] def _studies(domain: Domain, persons: list[str], at: str) -> list[Resource]: """Every instance of the domain's studies (the catalog's) for these persons, as known by `at`: its DiagnosticReport (or Encounter) and Observations, in date order.""" found: list[Resource] = [] report_facts = _clinical(domain).REPORT_FACTS if domain == Domain.TEA: births = { r["person_id"]: date.fromisoformat(f._day(r["birth_date"])) if r["birth_date"] else None for r in reads.rows(domain.value, "births", persons=persons) } for study in catalog.of_domain(domain.value): spec = catalog.studies()[study] facts = {} if kind := report_facts.get(study): found_facts = reads.rows(domain.value, kind, persons=persons, cutoff=at) facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"] for r in found_facts} # fmt: skip first = next(e.date for e in spec.events.values() if e.parent is None) for row in reads.instances(study, persons, at): days = facts.get((row["person_id"], str(row[first])[:10])) extra = [] if days is None else [f.ext("days-to-diagnosis", "integer", int(days))] known = f.known(study, row, at) found += f.instance(study, known, extra) if domain == Domain.TEA and study == "ados2": known["evaluation_date"] = date.fromisoformat(f._day(known["evaluation_date"])) found.append(tea_fhir.ados2_observation(known, births.get(row["person_id"]))) if domain == Domain.TEA: found += _tea_eeg_studies(persons, at) return found def _tea_eeg_studies(persons: list[str], at: str) -> list[Resource]: def rows(kind): return reads.rows("tea", kind, persons=persons, cutoff=at) def key(row): return row["person_id"], row["study_date"], row["edf"] regions, results = defaultdict(list), defaultdict(list) for row in rows("regions"): regions[(*key(row), row["code"])].append(row) for row in rows("checks"): results[key(row)].append(tea_fhir.eeg_check(row)) for row in rows("metrics"): results[key(row)].append(tea_fhir.eeg_metric(row, regions[(*key(row), row["code"])])) found = [] for row in rows("eegs"): observations = results[key(row)] found.extend((tea_fhir.eeg_report(row, observations), *observations)) return found def _tea_risks(persons: list[str], at: str) -> list[Resource]: groups = defaultdict(list) for row in reads.rows("tea", "association_scores", persons=persons, cutoff=at): group = groups[row["person_id"]] if ( not group or row["edf"] == group[0]["edf"] and row["study_date"] == group[0]["study_date"] ): group.append(row) return [tea_fhir.association_risk(group) for group in groups.values()] def _risk_assessments(rows: list[dict]) -> list[Resource]: groups: dict[tuple, list[dict]] = {} for r in rows: groups.setdefault((r["model"], r["version"], r["person_id"], str(r["index_date"])), []).append(r) # fmt: skip return [f.risk_assessment(g[0], g) for g in groups.values()] def _clinical_search(kind: str, build, request, domain, subject, count, offset): fu = _clinical(domain) count, offset = _page(count, offset) params: dict = {"persons": _subjects(subject)} if kind != "risk": params["cutoff"] = _cutoff(domain, None).isoformat() if kind == "procedure": params["types"] = list(fu.PROCEDURES) if kind == "risk" and domain == Domain.TEA: found = _tea_risks(params["persons"], _cutoff(domain, None).isoformat()) else: found = build(reads.rows(domain.value, kind, **params)) return bundle(request, _sliced(found, count, offset), len(found), count, offset) SUBJECT = "Patient/, comma-separated" @router.get("/DiagnosticReport", responses=_OK, response_class=Response) def search_diagnostic_report(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """The domain's reports (each study of the catalog with a report), as known by the last day with data.""" return _study_search("DiagnosticReport", request, domain, subject, _count, _offset) def _study_search(kind: str, request, domain, subject, count, offset) -> Response: _clinical(domain) count, offset = _page(count, offset) persons, at = _subjects(subject), _cutoff(domain, None).isoformat() found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind] return bundle(request, _sliced(found, count, offset), len(found), count, offset) @router.get("/Encounter", responses=_OK, response_class=Response) def search_encounter(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """Consultations: each study of the catalog without a report, as an encounter.""" return _study_search("Encounter", request, domain, subject, _count, _offset) @router.get("/Observation", responses=_OK, response_class=Response) def search_observation(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """Every result of the domain's reports, one per field of the catalog.""" return _study_search("Observation", request, domain, subject, _count, _offset) @router.get("/Condition", responses=_OK, response_class=Response) def search_condition(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """What clinical notes diagnosed (CaMa: and each recurrence).""" def build(rows): return [f.condition(r) for r in rows] return _clinical_search("condition", build, request, domain, subject, _count, _offset) @router.get("/Procedure", responses=_OK, response_class=Response) def search_procedure(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """The procedures the domain's timeline infers (CaCu: colposcopies and treatments; CaMa: each treatment, by its kind).""" def build(rows): return [f.procedure(r, domain.value) for r in rows] return _clinical_search("procedure", build, request, domain, subject, _count, _offset) @router.get("/RiskAssessment", responses=_OK, response_class=Response) def search_risk_assessment(request: Request, domain: Domain, subject: str | None = Query(None, description=SUBJECT), _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """The champion models' risks, one per model and index date.""" return _clinical_search("risk", _risk_assessments, request, domain, subject, _count, _offset) # --- Measure and MeasureReport ---------------------------------------------------------------- def _measure(domain: Domain, key: str) -> m.Measure: found = measures(domain) for code, measure in found.items(): if key in (code, f.measure_id(code), f.measure_url(code)): return measure raise HTTPException(404, f"no {domain.value} Measure {key}") @router.get("/Measure/{id}", responses=_OK, response_class=Response) def read_measure(domain: Domain, id: str) -> Response: return fhir(f.measure(_measure(domain, id), domain.value)) @router.get("/Measure", responses=_OK, response_class=Response) def search_measure(request: Request, domain: Domain, _count: int | None = Query(None), _offset: int = Query(0)) -> Response: # fmt: skip """Every measure of the domain (none for a domain without them yet).""" count, offset = _page(_count, _offset) found = [f.measure(x, domain.value) for x in measures(domain).values()] return bundle(request, _sliced(found, count, offset), len(found), count, offset) @router.get("/MeasureReport", responses=_OK, response_class=Response) def search_measure_report( request: Request, domain: Domain, measure: str = Query(alias="measure", description="the Measure's id or canonical URL"), periods: str = Query( alias="reporting-period", description="semesters (2025-S1) or months (2025-03), comma-separated", ), as_of: datetime | None = Query( None, alias="as-of", description="count only what was known by then" ), event_cutoff: date | None = Query( None, alias="event-cutoff", description="durations count to this day" ), _count: int | None = Query(None), _offset: int = Query(0), ) -> Response: """The measure's summary report for each period asked for, evaluated over gold.""" found = _measure(domain, measure.split("|")[0]) count, offset = _page(_count, _offset) try: asked = [(p.strip(), m.Period.parse(p.strip())) for p in periods.split(",") if p.strip()] except ValueError as e: raise HTTPException(422, f"reporting-period: {e}") from e rows = measure_reads.rows(domain.value, found.rows, **found.params) reports = [] page = _sliced(asked, count, offset) results = m.evaluate_periods(found, rows, [p for _, p in page], as_of, event_cutoff) for (text, period), result in zip(page, results, strict=True): report = m.report(found, period, result, as_of) report.id = f"{f.measure_id(found.id)}-{text.lower()}" reports.append(report) return bundle(request, reports, len(asked), count, offset) # --- the FHIR door: what a standard hospital sends ----------------------------------------- @router.post("", responses=_OK, response_class=Response, status_code=202) def post_bundle( domain: Domain, bundle: Annotated[dict[str, Any], Body(description="a FHIR R4 batch or transaction Bundle")], sender: str = Query( pattern=ID_PATTERN, max_length=40, description="the sender's pipeline (its fhir nodes read this inbox)", ), client: DagsterGraphQLClient = Depends(dagster), ) -> Response: """A standard hospital's Bundle: checked as FHIR, kept as sent in the sender's inbox, and placed by the sender's pipeline (a run starts; follow it at the Location).""" try: parsed = Bundle.model_validate(bundle) except ValueError as e: raise HTTPException(422, f"not a valid R4 Bundle: {e}") from e if parsed.type not in ("batch", "transaction", "collection"): raise HTTPException(422, "send a batch, transaction or collection Bundle") if not config_log.latest_version(sender): raise HTTPException(404, f"no pipeline {sender} to place what it sends") readers.receive(sender, bundle) run_id = submit(client, sender) entries = [{"response": {"status": "202 Accepted", "location": f"{e.resource.get_resource_type()}/{e.resource.id}"}} for e in parsed.entry or [] if e.resource is not None] # fmt: skip answer = Bundle(type="batch-response", entry=entries or None) found = fhir(answer) found.status_code = 202 found.headers["Location"] = f"/runs/{run_id}" return found # --- CapabilityStatement ---------------------------------------------------------------------- @router.get("/metadata", responses=_OK, response_class=Response) def metadata(request: Request, domain: Domain) -> Response: """What this base serves: built from the routes above, so it cannot drift from them.""" resources: dict[str, dict] = {} system: list[dict] = [] fu = part(domain, "follow_up") clinical = fu is not None for route in router.routes: path = route.path.removeprefix(router.prefix) if not path: # the base itself: the FHIR door if clinical: system = [{"code": "batch"}, {"code": "transaction"}] continue _, kind, *rest = path.split("/") if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" and not clinical): # fmt: skip continue if rest and rest[0].startswith("$"): continue entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []}) if kind == "Patient" and not rest: entry |= {"searchInclude": ["DiagnosticReport:result"], "searchRevInclude": list(_revincludes(domain))} # fmt: skip if domain == Domain.TEA: entry["searchParam"] += [ {"name": name, "type": spec[0]} for name, spec in TEA_FILTERS.items() ] entry["interaction"].append({"code": "read" if rest else "search-type"}) for param in route.dependant.query_params: name = param.alias if name.startswith("_") and name != "_id": continue declared = f.SEARCH_PARAMETERS.get(name) entry["searchParam"].append({ "name": name, "type": declared[1] if declared else _STANDARD[name], **({"definition": f"{f.BASE}/SearchParameter/{name}"} if declared else {}), }) # fmt: skip statement = CapabilityStatement.model_validate({ "resourceType": "CapabilityStatement", "status": "active", "date": date.today().isoformat(), "kind": "instance", "fhirVersion": f.FHIR_VERSION, "format": ["json"], "implementation": {"description": f"ISSSTELEON {domain.value}", "url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"}, "rest": [{"mode": "server", "resource": [{k: v for k, v in r.items() if v} for r in resources.values()], **({"interaction": system} if system else {})}], }) # fmt: skip return fhir(statement) _STANDARD = { "_id": "token", "subject": "reference", "measure": "reference", "follow-up-start": "date", "name": "string", "identifier": "token", }