TEA's follow-up list by step, case and EEG result, with its filters and $eeg-summary; a list from a start day

This commit is contained in:
Roberto Treviño
2026-12-06 03:33:25 -06:00
parent 2a28e8fc50
commit 4ce3a165ad
3 changed files with 70 additions and 25 deletions
+41 -23
View File
@@ -182,6 +182,9 @@ def search_patient(
cutoff: date | None = Query(
None, alias="follow-up-cutoff", description="default: the last day with data"
),
start: date | None = Query(
None, alias="follow-up-start", description="the list from this day (in place of a window)"
),
status: str | None = Query(None, alias="follow-up-status"),
name: str | None = Query(
None, description="each word starts a word of her name (case and accents ignored)"
@@ -197,28 +200,14 @@ 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; with `follow-up-window` or `follow-up-start` (or, where the domain has them,
its filters or a cut-off: its whole history), the domain's follow-up list at the cut-off,
filtered and in reading order, with what the list shows of each patient included."""
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]
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)
]
rows, listed = _listed(request, domain, at, window, start, cutoff, sort)
if _id: # alone or on the list: those patients (on the list, as it shows them)
rows = [r for r in rows if r["person_id"] in _id.split(",")]
if status:
@@ -231,22 +220,50 @@ def search_patient(
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 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 _risks(domain, persons, at)[0]:
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
applied = {"follow-up-cutoff": at.isoformat()} if listed else None
patients = [f.patient(r, fu.STATUS_SYSTEM)
for r in _with_identity(domain, _noted(domain, page, at))] # fmt: skip
return bundle(request, patients, len(rows), count, offset, included,
applied) # fmt: skip
def _listed(request: Request, domain: Domain, at: date, window: int | None, start: date | None,
cutoff: date | None, sort: str = "-recent") -> tuple[list[dict], bool]: # fmt: skip
"""The domain's patients at the cut-off, or its follow-up list (whether it is) from the
window's or the asked start, else its whole history, met by the domain's filters asked."""
fu = _clinical(domain)
filters = {name: request.query_params.getlist(name) for name in getattr(fu, "FILTERS", {})
if name in request.query_params} # fmt: skip
try:
filters and fu.matches({}, filters) # only whether each filter can be met
except ValueError as exc:
raise HTTPException(422, str(exc)) from None
persons = reads.rows(domain.value, "persons")
if window is None and not (start or filters or (hasattr(fu, "FILTERS") and cutoff)):
return [{**r, "status": fu.status(r, at)} for r in persons], False
if window is not None and 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 = start or (date.min if window is None else window_start(at, window))
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)
]
return [r for r in rows if fu.matches(r, filters)] if filters else rows, True
_COMPARE = {"gt": operator.gt, "ge": operator.ge, "lt": operator.lt, "le": operator.le}
@@ -522,12 +539,13 @@ def metadata(request: Request, domain: Domain) -> Response:
and not clinical): # fmt: skip
continue
entry = resources.setdefault(kind, {"type": kind, "interaction": [], "searchParam": []})
names = [p.alias for p in route.dependant.query_params]
if kind == "Patient" and not rest:
entry |= {"searchInclude": ["DiagnosticReport:result"],
"searchRevInclude": list(REVINCLUDES)} # fmt: skip
names += list(getattr(part(domain, "follow_up"), "FILTERS", ()))
entry["interaction"].append({"code": "read" if rest else "search-type"})
for param in route.dependant.query_params:
name = param.alias
for name in names:
if name.startswith("_") and name != "_id":
continue
declared = f.SEARCH_PARAMETERS.get(name)
+26
View File
@@ -0,0 +1,26 @@
"""TEA's FHIR operations over its follow-up list: `$eeg-summary`, the EEGs of the children
the list holds (with its filters; its whole history when no window or start is asked)."""
from datetime import date
from fastapi import APIRouter, Query, Request
from fastapi.responses import Response
from core.domains import Domain
from core.tea import fhir as tea_fhir
from core.tea import follow_up
from webapi.fhir import _OK, _cutoff, _listed, fhir
router = APIRouter(prefix="/tea/fhir/Patient", tags=["fhir"])
@router.get("/$eeg-summary", responses=_OK, response_class=Response)
def eeg_summary(
request: Request,
window: int | None = Query(None, alias="follow-up-window", description="months"),
start: date | None = Query(None, alias="follow-up-start"),
cutoff: date | None = Query(None, alias="follow-up-cutoff"),
) -> Response:
at = _cutoff(Domain.TEA, cutoff)
rows, _ = _listed(request, Domain.TEA, at, window, start, at)
return fhir(tea_fhir.eeg_summary(follow_up.summary(rows)))
+3 -2
View File
@@ -3,7 +3,7 @@ from fastapi.exception_handlers import http_exception_handler
from starlette.exceptions import HTTPException
from core.domains import Domain
from webapi import eeg, fhir, fhir_cacu, ingest, models, review, runs, sources, users
from webapi import eeg, fhir, fhir_cacu, fhir_tea, ingest, models, review, runs, sources, users
from webapi.auth import caller
app = FastAPI(
@@ -19,7 +19,8 @@ app.include_router(review.router)
app.include_router(runs.router)
app.include_router(models.router)
app.include_router(eeg.router)
app.include_router(fhir_cacu.router) # before the generic Patient/{id}
app.include_router(fhir_cacu.router) # these two before the generic Patient/{id}
app.include_router(fhir_tea.router)
app.include_router(fhir.router)
app.include_router(users.router) # sign-in for the web app; no route requires it