TEA follow-up: Patient search with TEA filters and $eeg-summary

Use _patient_rows and shared Query declarations for follow-up selection. Validate filters with an empty row before reading candidates, and use doseq for repeated values in paging links. Keep operation routes out of the metadata scan for read and search interactions. Use _follow_up_gate to compare the 29 captured queries by normalized record number, scalar counts and metrics.
This commit is contained in:
2026-11-29 19:40:14 -06:00
parent 9e5aa20092
commit b401f98f19
2 changed files with 207 additions and 37 deletions
+137 -37
View File
@@ -5,6 +5,7 @@ counting a few thousand rows (measures) and ordering the follow-up list."""
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
@@ -12,6 +13,7 @@ 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
@@ -73,7 +75,9 @@ def bundle(request: Request, matches: list[Resource], total: int, count: int, of
base = str(request.base_url).rstrip("/") + request.url.path.rsplit("/", 1)[0]
def link(relation: str, at: int) -> dict:
url = request.url.include_query_params(**(applied or {}), _offset=at, _count=count)
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)]
@@ -95,6 +99,52 @@ def _sliced(found: list, count: int, offset: int) -> list:
# --- 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)
def eeg_summary(
request: Request,
domain: Domain,
window: int | None = _WINDOW,
start: date | None = _START,
cutoff: date | None = _CUTOFF,
status: str | None = _STATUS,
) -> Response:
"""EEG counts for the follow-up list. Without a window or start, use the whole history."""
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)
@@ -131,15 +181,10 @@ def search_patient(
request: Request,
domain: Domain,
_id: str | None = Query(None, alias="_id"),
window: int | None = Query(
None,
alias="follow-up-window",
description="months: the domain's follow-up list over that window up to the cut-off",
),
cutoff: date | None = Query(
None, alias="follow-up-cutoff", description="default: the last day with data"
),
status: str | None = Query(None, alias="follow-up-status"),
window: int | None = _WINDOW,
start: date | None = _START,
cutoff: date | None = _CUTOFF,
status: str | None = _STATUS,
sort: str = Query("-recent", alias="_sort", description="-recent or -risk-<outcome>"),
horizon: float | None = Query(None, alias="risk-horizon", description="years"),
revinclude: list[str] = Query([], alias="_revinclude", description=f"any of {REVINCLUDES}"),
@@ -147,49 +192,93 @@ def search_patient(
_count: int | None = Query(None),
_offset: int = Query(0),
) -> Response:
"""Patients; with `follow-up-window`, the domain's follow-up list at the cut-off,
filtered by status and in reading order, with what the list shows of each patient
included."""
"""Patients, or the domain's follow-up list selected by window or start.
For TEA, a cutoff or a TEA filter also selects the follow-up list. Patients without
follow-up episodes appear only in the plain search.
"""
fu = _clinical(domain)
count, offset = _page(_count, _offset)
at = _cutoff(domain, cutoff)
horizon = fu.DEFAULT_HORIZON if horizon is None else horizon
persons_rows = reads.rows(domain.value, "persons")
if window is None:
rows = [{**r, "status": fu.status(r, at)} for r in persons_rows]
if _id:
rows = [r for r in rows if r["person_id"] in _id.split(",")]
else:
if window not in fu.WINDOWS:
raise HTTPException(422, f"follow-up-window is one of {fu.WINDOWS}")
if sort not in fu.SORTS:
raise HTTPException(422, f"_sort is one of {fu.SORTS}")
start = window_start(at, window)
params = {"start": start.isoformat(), "cutoff": at.isoformat()}
person = {r["person_id"]: r for r in persons_rows}
rows = [
{**person[r["person_id"]], **r}
for r in fu.listed(reads.rows(domain.value, "follow_up", **params), start, at)
]
if status:
rows = [r for r in rows if r["status"] in status.split(",")]
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))
persons = [r["person_id"] for r in rows]
risks: dict[str, list[dict]] = {}
if window is not None and sort != "-recent" or "RiskAssessment:subject" in revinclude:
if listed and sort != "-recent" or "RiskAssessment:subject" in revinclude:
for r in reads.rows(domain.value, "risk", persons=persons):
risks.setdefault(r["person_id"], []).append(r)
if window is not None:
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
applied = {"follow-up-cutoff": at.isoformat()} if window is not None else None
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 getattr(fu, "FILTERS", ())
if name in request.query_params
}
if filters:
fu.matches({}, filters) # Validate values even when the selection has no rows.
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
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
@@ -437,7 +526,8 @@ 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] = []
clinical = part(domain, "follow_up") is not None
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
@@ -448,10 +538,15 @@ def metadata(request: Request, domain: Domain) -> Response:
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)} # fmt: skip
entry["searchParam"] += [
{"name": name, "type": spec[0]} for name, spec in getattr(fu, "FILTERS", {}).items()
]
entry["interaction"].append({"code": "read" if rest else "search-type"})
for param in route.dependant.query_params:
name = param.alias
@@ -479,4 +574,9 @@ def metadata(request: Request, domain: Domain) -> Response:
return fhir(statement)
_STANDARD = {"_id": "token", "subject": "reference", "measure": "reference"}
_STANDARD = {
"_id": "token",
"subject": "reference",
"measure": "reference",
"follow-up-start": "date",
}