"""What the FHIR gate checks with: every resource the API serves, the HL7 validator over them, and the follow-up list read the way the WebApp reads it.""" import json import os import subprocess from pathlib import Path from core import fhir VALIDATOR = os.environ.get("FHIR_VALIDATOR_JAR", "/opt/fhir/validator_cli.jar") PAGES = 100 # a search with more pages than this is a paging bug E = fhir.EXTENSION def pages(api, path: str, params=None) -> list[dict]: """Every page of a search, following `next` to the end.""" found, url = [], path for _ in range(PAGES): response = api.get(url, params=params) assert response.status_code == 200, response.text assert response.headers["content-type"].startswith("application/fhir+json") found.append(bundle := response.json()) url = next((x["url"] for x in bundle["link"] if x["relation"] == "next"), None) params = None # the next link carries the query if url is None: return found raise AssertionError(f"{path}: more than {PAGES} pages") def served(api, base: str, periods: list[str], patients: list[str]) -> list[dict]: """Every kind of resource the base serves, each search paged to the end: metadata, the measures and their reports, the follow-up list with what it includes, a read of each patient, and each clinical search for them.""" found = [api.get(f"{base}/metadata").json()] found += pages(api, f"{base}/Measure") for measure in [e["resource"]["id"] for b in found[1:] for e in b["entry"]]: found += pages(api, f"{base}/MeasureReport", {"measure": measure, "reporting-period": ",".join(periods)}) # fmt: skip found += pages(api, f"{base}/Patient", [ ("follow-up-window", 12), ("_count", 25), ("_revinclude", "DiagnosticReport:subject"), ("_revinclude", "RiskAssessment:subject"), ("_include:iterate", "DiagnosticReport:result"), ]) # fmt: skip found += [api.get(f"{base}/Patient/{p}").json() for p in patients] for kind in ("DiagnosticReport", "Observation", "Condition", "Procedure", "RiskAssessment"): found += pages(api, f"{base}/{kind}", {"subject": ",".join(patients), "_count": 40}) return found def validate(resources: list[dict], folder: Path) -> tuple[list[dict], list[dict]]: """The HL7 validator (offline: no terminology server) over the resources, with our conformance resources loaded: its errors and its warnings.""" data, ig = folder / "served", folder / "ig" data.mkdir() ig.mkdir() for i, resource in enumerate(resources): (data / f"{i:05d}.json").write_text(json.dumps(resource)) for resource in fhir.conformance(): (ig / f"{resource.get_resource_type()}-{resource.id}.json").write_text( resource.model_dump_json(exclude_none=True)) # fmt: skip out = folder / "outcome.json" subprocess.run(["java", "-jar", VALIDATOR, str(data), str(ig), "-version", fhir.FHIR_VERSION, "-tx", "n/a", "-ig", str(ig), "-output", str(out)], check=False, capture_output=True) # fmt: skip outcome = json.loads(out.read_text()) outcomes = [e["resource"] for e in outcome.get("entry", [])] or [outcome] issues = [i for o in outcomes for i in o.get("issue", [])] errors = [i for i in issues if i["severity"] in ("error", "fatal")] return errors, [i for i in issues if i["severity"] == "warning"] SCORE_REQUIRED = "A measureScore is required when the Measure.scoring=" def unscored(issue: dict, resources: list[dict]) -> bool: """The validator's one allowed error: a summary report of a period with nothing to score (no denominator, nothing measured) has no score, since the rate or median is undefined. FHIR's validator asks for one anyway.""" text = issue.get("details", {}).get("text", "") where = " ".join(issue.get("expression", [])) if not text.startswith(SCORE_REQUIRED) or "/*MeasureReport/" not in where: return False report_id = where.split("/*MeasureReport/")[1].split("*/")[0] everything = [r for b in resources for r in [b, *(e["resource"] for e in b.get("entry", []))]] reports = [r for r in everything if r.get("id") == report_id and r.get("resourceType") == "MeasureReport"] # fmt: skip counts = {p["code"]["coding"][0]["code"]: p["count"] for r in reports for p in r["group"][0]["population"]} # fmt: skip nothing = counts.get("denominator", counts.get("measure-observation")) == 0 scored = any("measureScore" in r["group"][0] for r in reports) return bool(reports) and nothing and not scored def _ext(resource: dict, name: str) -> dict | None: return next((x for x in resource.get("extension", []) if x["url"] == E + name), None) def _code(concept: dict) -> str: return concept["coding"][0]["code"] def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]: """The follow-up list as the WebApp shows it, in order: per patient, her status, her latest cytology and HPV sampled in the window, her days to diagnosis, and her latest reported biopsy.""" included = {(e["resource"]["resourceType"], e["resource"]["id"]): e["resource"] for b in bundles for e in b.get("entry", [])} # fmt: skip rows = [] for b in bundles: for patient in (e["resource"] for e in b.get("entry", []) if e["search"]["mode"] == "match"): # fmt: skip reports = [r for (kind, _), r in included.items() if kind == "DiagnosticReport" and r["subject"]["reference"] == f"Patient/{patient['id']}"] # fmt: skip def results(report: dict) -> dict: return {_code(o["code"]): o for o in ( included[("Observation", x["reference"].split("/")[1])] for x in report.get("result", []))} # fmt: skip cytologies = sorted( (r for r in reports if _code(r["code"]) == "cervical_cytology" and start <= r["effectiveDateTime"] <= cutoff), key=lambda r: r["effectiveDateTime"]) # fmt: skip hpv = [r for r in cytologies if "cervical_cytology.hpv" in results(r)] biopsies = sorted((r for r in reports if _code(r["code"]) == "cervical_biopsy" and _ext(r, "report-date")), key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip status = _ext(patient, "follow-up-status")["valueCoding"]["code"] row = {"person": patient["id"], "status": status, "cytology": None, "hpv": None, "days_to_diagnosis": None, "biopsy": None} # fmt: skip if cytologies: last, found = cytologies[-1], results(cytologies[-1]) row["cytology"] = {"date": last["effectiveDateTime"], **{ k: _code(found[c]["valueCodeableConcept"]) if c in found else None for k, c in (("result", "cervical_cytology.result"), ("adequacy", "cervical_cytology.adequacy"))}} # fmt: skip days = _ext(last, "days-to-diagnosis") row["days_to_diagnosis"] = days and days["valueInteger"] if hpv: found = results(hpv[-1]) typed = ("cervical_cytology.hpv_16", "cervical_cytology.hpv_18") types = [found[k]["valueBoolean"] for k in typed if k in found] row["hpv"] = {"date": hpv[-1]["effectiveDateTime"], "positive": found["cervical_cytology.hpv"]["valueBoolean"], "types_16_18": any(types) if types else None} # fmt: skip if biopsies: last, found = biopsies[-1], results(biopsies[-1]) grade = found.get("cervical_biopsy.histology") histology = grade and _code(grade["valueCodeableConcept"]) row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"], "histology": histology} # fmt: skip rows.append(row) return rows