From 25b52b0f6b7c88c545d85c3921e6f1d73aa0315f Mon Sep 17 00:00:00 2001 From: edgar Date: Wed, 2 Dec 2026 16:32:45 -0600 Subject: [PATCH] Publicar elegibilidad de pacientes en FHIR --- tests/test_cacu_eligibility.py | 92 ++++++++++++++++++++++++++++++++++ webapi/fhir.py | 33 ++++++++++-- 2 files changed, 121 insertions(+), 4 deletions(-) create mode 100644 tests/test_cacu_eligibility.py diff --git a/tests/test_cacu_eligibility.py b/tests/test_cacu_eligibility.py new file mode 100644 index 0000000..c939f9e --- /dev/null +++ b/tests/test_cacu_eligibility.py @@ -0,0 +1,92 @@ +"""The CaCu eligibility operation serves the gold report as FHIR Parameters.""" + +import json +from datetime import date + +import pandas as pd +import pytest +from fastapi import HTTPException + +from core.domains import Domain +from persistance import gold +from webapi import fhir + + +def _patient_reads(monkeypatch, exists=True): + monkeypatch.setattr( + fhir.reads, + "rows", + lambda domain, kind, **params: ([{"person_id": params["id"]}] if exists else []) + if kind == "person" else [], + ) + + +def test_patient_eligibility_operation_returns_reasons_and_applies_filters(monkeypatch): + _patient_reads(monkeypatch) + calls = [] + + def report(scenario, person_id, *, cutoff): + calls.append((scenario, person_id, cutoff)) + return pd.DataFrame([{ + "scenario": "surveillance", + "person_id": person_id, + "index_date": date(2025, 2, 1), + "index_sample_id": "sample-1", + "criterion": "hysterectomy", + "eligible": False, + }]) + + monkeypatch.setattr(fhir.gold_reads, "cacu_eligibility_report", report) + response = fhir.cacu_eligibility( + Domain.CACU, "patient-1", "surveillance", date(2025, 2, 15) + ) + + assert response.status_code == 200 + assert response.media_type == fhir.FHIR_JSON + body = json.loads(response.body) + parts = {p["name"]: p for p in body["parameter"]} + assert body["resourceType"] == "Parameters" + assert parts["patient"]["valueReference"]["reference"] == "Patient/patient-1" + assert parts["cutoff"]["valueDate"] == "2025-02-15" + candidate = parts["candidate"]["part"] + reason = next(p for p in candidate if p["name"] == "criterion") + assert reason["valueCoding"]["code"] == "hysterectomy" + assert reason["valueCoding"]["system"].endswith("/CodeSystem/cacu-exclusion-criterion") + assert calls == [("surveillance", "patient-1", date(2025, 2, 15))] + + +def test_patient_eligibility_reports_stale_gold_as_fhir_conflict(monkeypatch): + _patient_reads(monkeypatch) + + def outdated(*args, **kwargs): + raise gold.GoldSchemaError("rebuild gold.cacu_eligibility") + + monkeypatch.setattr(fhir.gold_reads, "cacu_eligibility_report", outdated) + response = fhir.cacu_eligibility( + Domain.CACU, "patient-1", None, date(2025, 2, 15) + ) + + assert response.status_code == 409 + assert response.media_type == fhir.FHIR_JSON + body = json.loads(response.body) + assert body["resourceType"] == "OperationOutcome" + assert body["issue"][0]["code"] == "conflict" + assert "rebuild gold.cacu_eligibility" in body["issue"][0]["diagnostics"] + + +def test_patient_eligibility_rejects_other_domains_unknown_scenarios_and_unknown_patients( + monkeypatch, +): + _patient_reads(monkeypatch) + with pytest.raises(HTTPException) as other_domain: + fhir.cacu_eligibility(Domain.CAMA, "patient-1", None, date(2025, 2, 15)) + assert other_domain.value.status_code == 404 + + with pytest.raises(HTTPException) as unknown_scenario: + fhir.cacu_eligibility(Domain.CACU, "patient-1", "unknown", date(2025, 2, 15)) + assert unknown_scenario.value.status_code == 422 + + _patient_reads(monkeypatch, exists=False) + with pytest.raises(HTTPException) as unknown_patient: + fhir.cacu_eligibility(Domain.CACU, "missing", None, date(2025, 2, 15)) + assert unknown_patient.value.status_code == 404 diff --git a/webapi/fhir.py b/webapi/fhir.py index 129e70e..0f4cc00 100644 --- a/webapi/fhir.py +++ b/webapi/fhir.py @@ -25,7 +25,7 @@ from core.cacu import reference_risk as reference from core.domains import Domain, measures, part from core.follow_up import window_start from core.pipeline import ID_PATTERN -from persistance import config_log, readers +from persistance import config_log, gold as gold_reads, readers from persistance import fhir as reads from persistance import measures as measure_reads from webapi.ingest import submit @@ -44,7 +44,8 @@ def fhir(resource: Resource) -> Response: def outcome(status: int, text: str) -> Response: - issue = {"severity": "error", "code": "not-found" if status == 404 else "invalid", + code = {404: "not-found", 409: "conflict"}.get(status, "invalid") + issue = {"severity": "error", "code": code, "diagnostics": text} # fmt: skip return Response(OperationOutcome(issue=[issue]).model_dump_json(exclude_none=True), status_code=status, media_type=FHIR_JSON) # fmt: skip @@ -154,6 +155,30 @@ def reference_risk(domain: Domain, id: str, return fhir(f.reference_risk(resolution, comparison, reference.tables())) +@router.get("/Patient/{id}/$eligibility", responses=_OK, response_class=Response) +def cacu_eligibility( + domain: Domain, + id: str, + scenario: str | None = Query(None, description="Limit the report to one CaCu scenario"), + cutoff: date | None = Query(None, description="Only index dates up to this day"), +) -> Response: + """The normalized cohort eligibility and exclusion reasons for one CaCu patient.""" + if domain != Domain.CACU: + raise HTTPException(404, "patient eligibility is available for CaCu only") + scenarios = f.CODE_SYSTEMS["cacu-eligibility-scenario"][1] + if scenario is not None and scenario not in scenarios: + raise HTTPException(422, f"scenario is one of {', '.join(sorted(scenarios))}") + (person,) = reads.rows(domain.value, "person", id=id) or [None] + if person is None: + raise HTTPException(404, f"no Patient/{id}") + day = _cutoff(domain, cutoff) + try: + found = gold_reads.cacu_eligibility_report(scenario, id, cutoff=day) + except gold_reads.GoldSchemaError as exc: + return outcome(409, str(exc)) + return fhir(f.cacu_eligibility(found.to_dict("records"), id, day)) + + 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] @@ -537,8 +562,8 @@ def metadata(request: Request, domain: Domain) -> Response: system = [{"code": "batch"}, {"code": "transaction"}] continue _, kind, *rest = path.split("/") - if rest and rest[-1].startswith("$"): # an operation (the experimental NCI one), not a - continue # read or a search: its parameters are not search parameters + if rest and rest[-1].startswith("$"): # an operation, not a search + continue # its parameters are not search parameters if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport" and not clinical): # fmt: skip continue