FHIR out from the catalog, the FHIR door, ConceptMap routes; round-trip, new-label and Synthea gates
This commit is contained in:
+12
-10
@@ -118,11 +118,11 @@ def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
|||||||
for x in report.get("result", []))} # fmt: skip
|
for x in report.get("result", []))} # fmt: skip
|
||||||
|
|
||||||
cytologies = sorted(
|
cytologies = sorted(
|
||||||
(r for r in reports if _code(r["code"]) == "cervical-cytology"
|
(r for r in reports if _code(r["code"]) == "cervical_cytology"
|
||||||
and start <= r["effectiveDateTime"] <= cutoff),
|
and start <= r["effectiveDateTime"] <= cutoff),
|
||||||
key=lambda r: r["effectiveDateTime"]) # fmt: skip
|
key=lambda r: r["effectiveDateTime"]) # fmt: skip
|
||||||
hpv = [r for r in cytologies if "hpv" in results(r)]
|
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"
|
biopsies = sorted((r for r in reports if _code(r["code"]) == "cervical_biopsy"
|
||||||
and _ext(r, "report-date")),
|
and _ext(r, "report-date")),
|
||||||
key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip
|
key=lambda r: _ext(r, "report-date")["valueDate"]) # fmt: skip
|
||||||
status = _ext(patient, "follow-up-status")["valueCoding"]["code"]
|
status = _ext(patient, "follow-up-status")["valueCoding"]["code"]
|
||||||
@@ -132,20 +132,22 @@ def follow_up(bundles: list[dict], start: str, cutoff: str) -> list[dict]:
|
|||||||
last, found = cytologies[-1], results(cytologies[-1])
|
last, found = cytologies[-1], results(cytologies[-1])
|
||||||
row["cytology"] = {"date": last["effectiveDateTime"], **{
|
row["cytology"] = {"date": last["effectiveDateTime"], **{
|
||||||
k: _code(found[c]["valueCodeableConcept"]) if c in found else None
|
k: _code(found[c]["valueCodeableConcept"]) if c in found else None
|
||||||
for k, c in (("result", "cytology-result"),
|
for k, c in (("result", "cervical_cytology.result"),
|
||||||
("adequacy", "cytology-adequacy"))}} # fmt: skip
|
("adequacy", "cervical_cytology.adequacy"))}} # fmt: skip
|
||||||
days = _ext(last, "days-to-diagnosis")
|
days = _ext(last, "days-to-diagnosis")
|
||||||
row["days_to_diagnosis"] = days and days["valueInteger"]
|
row["days_to_diagnosis"] = days and days["valueInteger"]
|
||||||
if hpv:
|
if hpv:
|
||||||
found = results(hpv[-1])
|
found = results(hpv[-1])
|
||||||
types = [found[k]["valueBoolean"] for k in ("hpv-16", "hpv-18") if k in found]
|
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"],
|
row["hpv"] = {"date": hpv[-1]["effectiveDateTime"],
|
||||||
"positive": found["hpv"]["valueBoolean"],
|
"positive": found["cervical_cytology.hpv"]["valueBoolean"],
|
||||||
"types_16_18": any(types) if types else None} # fmt: skip
|
"types_16_18": any(types) if types else None} # fmt: skip
|
||||||
if biopsies:
|
if biopsies:
|
||||||
last = biopsies[-1]
|
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"],
|
row["biopsy"] = {"date": _ext(last, "report-date")["valueDate"],
|
||||||
"histology": _code(last["conclusionCode"][0])
|
"histology": histology} # fmt: skip
|
||||||
if last.get("conclusionCode") else None} # fmt: skip
|
|
||||||
rows.append(row)
|
rows.append(row)
|
||||||
return rows
|
return rows
|
||||||
|
|||||||
@@ -28,6 +28,8 @@ import pytest
|
|||||||
from fhir_checks import follow_up, pages, served, unscored, validate
|
from fhir_checks import follow_up, pages, served, unscored, validate
|
||||||
from test_conectar import ok, wait_for
|
from test_conectar import ok, wait_for
|
||||||
|
|
||||||
|
from conftest import put_concept_map
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
ROOT = Path(__file__).parents[2]
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||||
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu"
|
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu"
|
||||||
@@ -79,6 +81,7 @@ def _report(entry: dict, measure: str) -> tuple:
|
|||||||
|
|
||||||
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path):
|
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path):
|
||||||
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||||
|
put_concept_map(api, "hospital_cacu")
|
||||||
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
|
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
|
||||||
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
|
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
|
||||||
q = platform.query
|
q = platform.query
|
||||||
|
|||||||
+41
-6
@@ -54,8 +54,18 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
|||||||
}
|
}
|
||||||
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
assert len(ok(api.post("/ingest/sources/preview?limit=5", json=notes))) == 5
|
||||||
|
|
||||||
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
# The site's codes in platform terms: a ConceptMap, saved before the drawing that names
|
||||||
|
# it. One that maps onto a code no field allows is refused, saying which.
|
||||||
drawn = json.loads(messy_site.drawn)
|
drawn = json.loads(messy_site.drawn)
|
||||||
|
missing = api.put("/ingest/pipelines/site", json=drawn)
|
||||||
|
assert missing.status_code == 422 and "messy_site" in missing.text
|
||||||
|
codes = json.loads(messy_site.concept_map.read_text())
|
||||||
|
wrong = json.loads(json.dumps(codes).replace('"code": "HSIL"', '"code": "BIRADS-7"'))
|
||||||
|
refused = api.put("/ingest/concept-maps/messy_site", json=wrong)
|
||||||
|
assert refused.status_code == 422 and "BIRADS-7 is not an allowed code" in refused.text
|
||||||
|
assert ok(api.put("/ingest/concept-maps/messy_site", json=codes)) == {"version": 1}
|
||||||
|
|
||||||
|
# Saving a drawing: broken ones are refused with the reason; good ones get versions.
|
||||||
broken = {
|
broken = {
|
||||||
"nodes": [
|
"nodes": [
|
||||||
*drawn["nodes"],
|
*drawn["nodes"],
|
||||||
@@ -88,7 +98,8 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
|||||||
r["_record"]: f"pacientes_his:{r['num']}"
|
r["_record"]: f"pacientes_his:{r['num']}"
|
||||||
for r in ok(api.get("/ingest/pipelines/site/nodes/his_patients/rows?limit=500"))
|
for r in ok(api.get("/ingest/pipelines/site/nodes/his_patients/rows?limit=500"))
|
||||||
}
|
}
|
||||||
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == 53
|
reports = sum(1 for r in truth if r["where"].startswith("ArchivosUni:"))
|
||||||
|
assert len(ok(api.get("/ingest/pipelines/site/nodes/cytology/rows?limit=500"))) == reports
|
||||||
|
|
||||||
# Review: reports that contradict each other, rows held because their person is torn
|
# Review: reports that contradict each other, rows held because their person is torn
|
||||||
# (a record number shared by two patients), and persons that may be one patient.
|
# (a record number shared by two patients), and persons that may be one patient.
|
||||||
@@ -100,16 +111,21 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
|||||||
|
|
||||||
# The reviewer settles all of it, checking each case against the source documents.
|
# The reviewer settles all of it, checking each case against the source documents.
|
||||||
patient = messy_site.patients(platform.query)
|
patient = messy_site.patients(platform.query)
|
||||||
whose = {}
|
whose, before = {}, {}
|
||||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||||
whose.setdefault(person, set()).add(patient[record])
|
whose.setdefault(person, set()).add(patient[record])
|
||||||
|
before[record] = person
|
||||||
|
# A queued person or candidate is one of its records (decisions are kept by record).
|
||||||
|
whose |= {record: whose[person] for record, person in before.items()}
|
||||||
for r in truth:
|
for r in truth:
|
||||||
if r.get("flipped"):
|
if r.get("flipped"):
|
||||||
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
decision = CYTOLOGY | {"record": record_of[r["where"]], "reason": "flipped HPV"}
|
||||||
ok(api.post("/review/rejections", json=decision), status=201)
|
ok(api.post("/review/rejections", json=decision), status=201)
|
||||||
|
merges = 0
|
||||||
for entry in persons["to_settle"]:
|
for entry in persons["to_settle"]:
|
||||||
for c in entry["candidates"]:
|
for c in entry["candidates"]:
|
||||||
same = whose[entry["person"]] == whose[c["candidate"]]
|
same = whose[entry["person"]] == whose[c["candidate"]]
|
||||||
|
merges += same
|
||||||
decision = {"person": entry["person"], "candidate": c["candidate"], "same": same}
|
decision = {"person": entry["person"], "candidate": c["candidate"], "same": same}
|
||||||
ok(api.post("/review/persons", json=decision), status=201)
|
ok(api.post("/review/persons", json=decision), status=201)
|
||||||
collision = {r["where"]: r for r in truth if r.get("collision")}
|
collision = {r["where"]: r for r in truth if r.get("collision")}
|
||||||
@@ -121,6 +137,15 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
|||||||
"value": collision[where]["true_record_number"],
|
"value": collision[where]["true_record_number"],
|
||||||
}
|
}
|
||||||
ok(api.post("/review/corrections", json=fix), status=201)
|
ok(api.post("/review/corrections", json=fix), status=201)
|
||||||
|
# A row a rule held because its value is wrong (a scan misread) is rejected after a look
|
||||||
|
# at the document; rows of the torn person wait for the correction above.
|
||||||
|
misread = [
|
||||||
|
h for h in ok(api.get("/review/held", params=CYTOLOGY))
|
||||||
|
if not any("disagree on birth date" in why for why in h["_held"])
|
||||||
|
] # fmt: skip
|
||||||
|
for h in misread:
|
||||||
|
decision = CYTOLOGY | {"record": h["_record"], "reason": "misread in the scan"}
|
||||||
|
ok(api.post("/review/rejections", json=decision), status=201)
|
||||||
bad = {"record": "x", "field": "birth_date", "value": "not a date"}
|
bad = {"record": "x", "field": "birth_date", "value": "not a date"}
|
||||||
assert api.post("/review/corrections", json=bad).status_code == 422
|
assert api.post("/review/corrections", json=bad).status_code == 422
|
||||||
|
|
||||||
@@ -136,7 +161,17 @@ def test_an_operator_connects_a_site_and_settles_its_review(api, platform, messy
|
|||||||
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
for record, person in platform.query("select _record, person_id from bronze.n__site__persons"):
|
||||||
groups.setdefault(person, set()).add(patient[record])
|
groups.setdefault(person, set()).add(patient[record])
|
||||||
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
assert sorted(map(sorted, groups.values())) == sorted([p] for p in people)
|
||||||
|
|
||||||
|
# Person ids are stable: a person keeps an id her records had, and an id that went
|
||||||
|
# away (merged by the review) resolves to the person that replaced it.
|
||||||
|
after = dict(platform.query("select _record, person_id from bronze.n__site__persons"))
|
||||||
|
gone = set(before.values()) - set(after.values())
|
||||||
|
replaced = dict(platform.query("select person_id, replaced_by from silver.person_link"))
|
||||||
|
assert merges and len(gone) == merges and set(replaced) == gone
|
||||||
|
for old, new in replaced.items():
|
||||||
|
assert new in set(after.values())
|
||||||
|
assert any(before[r] == old and after[r] == new for r in before)
|
||||||
|
assert set(after.values()) <= set(before.values()) # no person got a new id
|
||||||
placed = platform.count("silver.cervical_cytology")
|
placed = platform.count("silver.cervical_cytology")
|
||||||
assert placed == sum(
|
reports = sum(1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped"))
|
||||||
1 for r in truth if r["entity"] == "cervical_cytology" and not r.get("flipped")
|
assert placed == reports - len(misread)
|
||||||
)
|
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""Phase 3.5 gate: one silver, two doors. What one platform serves as FHIR, another takes
|
||||||
|
through its FHIR door, as a standard hospital would send it, and places the same silver: the
|
||||||
|
same values of the same studies of the same patients, and so the same indicators. The
|
||||||
|
receiving side is configuration only: a pipeline whose fhir nodes read the sender's inbox."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fhir_checks import pages
|
||||||
|
from test_conectar import ok, run, wait_for
|
||||||
|
|
||||||
|
from conftest import put_concept_map
|
||||||
|
|
||||||
|
ROOT = Path(__file__).parents[2]
|
||||||
|
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||||
|
PIPELINES = ROOT / "tests" / "fixtures" / "pipelines"
|
||||||
|
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
|
||||||
|
SILVER = """
|
||||||
|
select i.value, o.study, o.instance, o.field,
|
||||||
|
o.value_text, o.value_num, o.value_bool, o.value_date
|
||||||
|
from silver.observation as o
|
||||||
|
join silver.person_identifier as i on i.person_id = o.person_id
|
||||||
|
where i.system not like '%curp' and i.system not like '%nss'
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _served(api) -> list[dict]:
|
||||||
|
"""Everything the CaCu FHIR base serves about every patient."""
|
||||||
|
patients = [e["resource"] for b in pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||||
|
for e in b.get("entry", [])] # fmt: skip
|
||||||
|
found = list(patients)
|
||||||
|
ids = [p["id"] for p in patients]
|
||||||
|
for kind in ("DiagnosticReport", "Observation", "Encounter"):
|
||||||
|
for i in range(0, len(ids), 50):
|
||||||
|
subject = ",".join(f"Patient/{p}" for p in ids[i : i + 50])
|
||||||
|
for b in pages(api, f"/cacu/fhir/{kind}", {"subject": subject, "_count": 200}):
|
||||||
|
found += [e["resource"] for e in b.get("entry", [])]
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
|
def _silver(platform) -> set[tuple]:
|
||||||
|
"""Every value silver holds, by patient record number, as Python values (each engine
|
||||||
|
returns booleans and dates its own way)."""
|
||||||
|
|
||||||
|
def plain(row) -> tuple:
|
||||||
|
number, study, instance, field, text, num, flag, day = row
|
||||||
|
num = None if num is None else float(num)
|
||||||
|
flag = None if flag is None else bool(flag)
|
||||||
|
return number, study, instance, field, text, num, flag, day and str(day)[:10]
|
||||||
|
|
||||||
|
return {plain(r) for r in platform.query(SILVER)}
|
||||||
|
|
||||||
|
|
||||||
|
def test_what_one_platform_serves_another_places_through_the_fhir_door(
|
||||||
|
api, platform, fresh_api, fresh_platform
|
||||||
|
):
|
||||||
|
# The sending side: the CaCu hospital, loaded through its drawn pipeline.
|
||||||
|
put_concept_map(api, "hospital_cacu")
|
||||||
|
drawn = (PIPELINES / "hospital_cacu.json").read_text().replace("{hospital}", str(HOSPITAL))
|
||||||
|
ok(api.put("/ingest/pipelines/cacu", json=json.loads(drawn)))
|
||||||
|
run(api, "cacu")
|
||||||
|
sent = _served(api)
|
||||||
|
bundle = {"resourceType": "Bundle", "type": "batch", "entry": [
|
||||||
|
{"resource": r, "request": {"method": "PUT", "url": f"{r['resourceType']}/{r['id']}"}}
|
||||||
|
for r in sent
|
||||||
|
]} # fmt: skip
|
||||||
|
|
||||||
|
# The receiving side: what it sends goes nowhere without a pipeline to place it.
|
||||||
|
door = "/cacu/fhir?sender=hospital"
|
||||||
|
assert fresh_api.post(door, json=bundle).status_code == 404
|
||||||
|
receiving = (PIPELINES / "fhir_door.json").read_text().replace("{sender}", "hospital")
|
||||||
|
ok(fresh_api.put("/ingest/pipelines/hospital", json=json.loads(receiving)))
|
||||||
|
assert (
|
||||||
|
fresh_api.post(door, json={"resourceType": "Bundle", "type": "searchset"}).status_code
|
||||||
|
== 422
|
||||||
|
)
|
||||||
|
answer = fresh_api.post(door, json=bundle)
|
||||||
|
assert answer.status_code == 202, answer.text
|
||||||
|
assert answer.headers["content-type"].startswith("application/fhir+json")
|
||||||
|
assert len(answer.json()["entry"]) == len(sent)
|
||||||
|
wait_for(fresh_api, answer.headers["location"].rsplit("/", 1)[1])
|
||||||
|
|
||||||
|
# One silver: every value of every study instance, by patient record number.
|
||||||
|
placed = _silver(platform)
|
||||||
|
assert len(placed) > 1000 and {r[1] for r in placed} >= {"cervical_cytology", "clinical_note"}
|
||||||
|
assert _silver(fresh_platform) == placed
|
||||||
|
assert fresh_platform.count("silver.person") == platform.count("silver.person")
|
||||||
|
|
||||||
|
# And so the same indicators, every measure, every semester.
|
||||||
|
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||||
|
for measure in [e["resource"]["id"] for e in measures["entry"]]:
|
||||||
|
params = {"measure": measure, "reporting-period": ",".join(PERIODS),
|
||||||
|
"event-cutoff": "2026-11-25"} # fmt: skip
|
||||||
|
ours, theirs = (
|
||||||
|
[e["resource"]["group"] for b in pages(a, "/cacu/fhir/MeasureReport", params)
|
||||||
|
for e in b["entry"]]
|
||||||
|
for a in (api, fresh_api)
|
||||||
|
) # fmt: skip
|
||||||
|
assert ours == theirs, measure
|
||||||
|
|
||||||
|
|
||||||
|
# The same laboratory, a year later: it renamed its result column and writes its results in
|
||||||
|
# words. Nothing in code changes: the drawing names the new column, the ConceptMap gets the
|
||||||
|
# new spellings.
|
||||||
|
RENAMED = {"NORMAL": "Negativo para lesión", "LIEBG": "Lesión de bajo grado",
|
||||||
|
"LIEAG": "Lesión de alto grado"} # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_new_label_is_a_concept_map_row_not_code(api, platform, fresh_api, fresh_platform,
|
||||||
|
tmp_path): # fmt: skip
|
||||||
|
put_concept_map(api, "hospital_cacu")
|
||||||
|
drawn = (PIPELINES / "hospital_cacu.json").read_text()
|
||||||
|
ok(
|
||||||
|
api.put(
|
||||||
|
"/ingest/pipelines/cacu", json=json.loads(drawn.replace("{hospital}", str(HOSPITAL)))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
run(api, "cacu")
|
||||||
|
|
||||||
|
(tmp_path / "lab").mkdir()
|
||||||
|
for name in ("hospital_cacu.db",):
|
||||||
|
(tmp_path / "lab" / name).write_bytes((HOSPITAL / name).read_bytes())
|
||||||
|
with sqlite3.connect(tmp_path / "lab" / "hospital_cacu.db") as con:
|
||||||
|
con.execute(
|
||||||
|
"alter table citologiacervical rename column cit_celulas_escamosas to PAP_RESULT"
|
||||||
|
)
|
||||||
|
for old, new in RENAMED.items():
|
||||||
|
con.execute(
|
||||||
|
"update citologiacervical set PAP_RESULT = ? where PAP_RESULT = ?", (new, old)
|
||||||
|
)
|
||||||
|
codes = json.loads(
|
||||||
|
(ROOT / "tests" / "fixtures" / "concept_maps" / "hospital_cacu.json").read_text()
|
||||||
|
)
|
||||||
|
bethesda = next(g for g in codes["group"] if g["target"].endswith("/bethesda"))
|
||||||
|
bethesda["element"] += [{"code": new, "target": [{"code": {"NORMAL": "NILM", "LIEBG": "LSIL",
|
||||||
|
"LIEAG": "HSIL"}[old], "equivalence": "equivalent"}]}
|
||||||
|
for old, new in RENAMED.items()] # fmt: skip
|
||||||
|
ok(fresh_api.put("/ingest/concept-maps/hospital_cacu", json=codes))
|
||||||
|
# The source names the database's column; the map names it as bronze holds it (the
|
||||||
|
# canvas preview shows dlt's normalised names: PAP_RESULT is pap_result).
|
||||||
|
renamed = drawn.replace(
|
||||||
|
'"cit_celulas_escamosas", "cit_vph_resultado"', '"PAP_RESULT", "cit_vph_resultado"'
|
||||||
|
)
|
||||||
|
renamed = renamed.replace('"result": "cit_celulas_escamosas"', '"result": "pap_result"')
|
||||||
|
renamed = renamed.replace("{hospital}", str(tmp_path / "lab"))
|
||||||
|
ok(fresh_api.put("/ingest/pipelines/cacu", json=json.loads(renamed)))
|
||||||
|
run(fresh_api, "cacu")
|
||||||
|
|
||||||
|
placed = _silver(platform)
|
||||||
|
assert any(r[3] == "result" and r[4] == "NILM" for r in placed)
|
||||||
|
assert _silver(fresh_platform) == placed
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
"""Phase 3.5 gate: Synthea through the FHIR door. A seeded synthetic population (Synthea,
|
||||||
|
with the platform's cervical-screening module) arrives as a standard hospital would send it,
|
||||||
|
and every report it holds reaches silver: nothing held, one person per patient."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fhir_checks import pages
|
||||||
|
from test_conectar import ok, wait_for
|
||||||
|
|
||||||
|
ROOT = Path(__file__).parents[2]
|
||||||
|
SYNTHEA = os.environ.get("SYNTHEA_JAR", "/opt/synthea/synthea.jar")
|
||||||
|
MODULES = ROOT / "tests" / "fixtures" / "synthea" / "modules"
|
||||||
|
DOOR = ROOT / "tests" / "fixtures" / "pipelines" / "fhir_door.json"
|
||||||
|
STUDY = "https://isssteleon.org/fhir/CodeSystem/study"
|
||||||
|
|
||||||
|
|
||||||
|
def _population(out: Path, people: int = 20) -> list[dict]:
|
||||||
|
"""Synthea's FHIR R4 transaction Bundles, one per patient (fixed seeds)."""
|
||||||
|
subprocess.run(
|
||||||
|
["java", "-jar", SYNTHEA, "-p", str(people), "-s", "7", "-cs", "7", "-g", "F",
|
||||||
|
"-a", "25-64", "-d", str(MODULES), "-m", "cervical_screening",
|
||||||
|
"--exporter.baseDirectory", str(out), "--exporter.fhir.export", "true",
|
||||||
|
"--exporter.hospital.fhir.export", "false",
|
||||||
|
"--exporter.practitioner.fhir.export", "false"],
|
||||||
|
check=True, capture_output=True, cwd=out.parent,
|
||||||
|
) # fmt: skip
|
||||||
|
return [json.loads(p.read_text()) for p in sorted((out / "fhir").glob("*.json"))]
|
||||||
|
|
||||||
|
|
||||||
|
def _reports(bundles: list[dict], study: str) -> int:
|
||||||
|
return sum(
|
||||||
|
1 for b in bundles for e in b["entry"]
|
||||||
|
if e["resource"]["resourceType"] == "DiagnosticReport"
|
||||||
|
and any(c.get("system") == STUDY and c.get("code") == study
|
||||||
|
for c in e["resource"].get("code", {}).get("coding", []))
|
||||||
|
) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_synthea_population_comes_in_through_the_fhir_door(api, platform, tmp_path):
|
||||||
|
bundles = _population(tmp_path / "synthea")
|
||||||
|
patients = sum(1 for b in bundles for e in b["entry"]
|
||||||
|
if e["resource"]["resourceType"] == "Patient") # fmt: skip
|
||||||
|
assert patients == 20 and _reports(bundles, "cervical_cytology") > 40
|
||||||
|
|
||||||
|
receiving = DOOR.read_text().replace("{sender}", "synthea")
|
||||||
|
ok(api.put("/ingest/pipelines/synthea", json=json.loads(receiving)))
|
||||||
|
batch = {"resourceType": "Bundle", "type": "batch",
|
||||||
|
"entry": [e for b in bundles for e in b["entry"]]} # fmt: skip
|
||||||
|
answer = api.post("/cacu/fhir?sender=synthea", json=batch)
|
||||||
|
assert answer.status_code == 202, answer.text[:500]
|
||||||
|
wait_for(api, answer.headers["location"].rsplit("/", 1)[1])
|
||||||
|
|
||||||
|
# Nothing held, every report placed, one person per patient.
|
||||||
|
for study in ("cervical_cytology", "cervical_biopsy"):
|
||||||
|
assert ok(api.get("/review/held", params={"entity": study})) == [], study
|
||||||
|
assert platform.count(f"silver.{study}") == _reports(bundles, study), study
|
||||||
|
assert platform.count("silver.person") == patients
|
||||||
|
(served,) = pages(api, "/cacu/fhir/Patient", {"_count": 200})
|
||||||
|
assert served["total"] == patients
|
||||||
@@ -10,6 +10,8 @@ from pathlib import Path
|
|||||||
import pytest
|
import pytest
|
||||||
from test_conectar import ok, run
|
from test_conectar import ok, run
|
||||||
|
|
||||||
|
from conftest import put_concept_map
|
||||||
|
|
||||||
ROOT = Path(__file__).parents[2]
|
ROOT = Path(__file__).parents[2]
|
||||||
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
|
||||||
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
||||||
@@ -19,8 +21,10 @@ PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
|
|||||||
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way
|
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True) # pages read one API either way
|
||||||
def test_every_page_loads_from_the_api(api, platform, messy_site):
|
def test_every_page_loads_from_the_api(api, platform, messy_site):
|
||||||
hospital = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
hospital = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
|
||||||
|
put_concept_map(api, "hospital_cacu")
|
||||||
ok(api.put("/ingest/pipelines/cacu", json=hospital))
|
ok(api.put("/ingest/pipelines/cacu", json=hospital))
|
||||||
run(api, "cacu")
|
run(api, "cacu")
|
||||||
|
put_concept_map(api, "messy_site")
|
||||||
ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn)))
|
ok(api.put("/ingest/pipelines/site", json=json.loads(messy_site.drawn)))
|
||||||
run(api, "site")
|
run(api, "site")
|
||||||
subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
subprocess.run(["npx", "playwright", "test"], cwd=ROOT / "WebApp", check=True,
|
||||||
|
|||||||
+126
-27
@@ -4,21 +4,27 @@ built by Core's mappers from the rows Persistance reads; nothing is computed her
|
|||||||
counting a few thousand rows (measures) and ordering the follow-up list."""
|
counting a few thousand rows (measures) and ordering the follow-up list."""
|
||||||
|
|
||||||
from datetime import date, datetime
|
from datetime import date, datetime
|
||||||
|
from typing import Annotated, Any
|
||||||
|
|
||||||
from fastapi import APIRouter, HTTPException, Query, Request
|
from dagster_graphql import DagsterGraphQLClient
|
||||||
|
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request
|
||||||
from fastapi.responses import Response
|
from fastapi.responses import Response
|
||||||
from fhir.resources.R4B.bundle import Bundle
|
from fhir.resources.R4B.bundle import Bundle
|
||||||
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
from fhir.resources.R4B.capabilitystatement import CapabilityStatement
|
||||||
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
from fhir.resources.R4B.operationoutcome import OperationOutcome
|
||||||
from fhir.resources.R4B.resource import Resource
|
from fhir.resources.R4B.resource import Resource
|
||||||
|
|
||||||
from core import cacu
|
from core import cacu, catalog
|
||||||
from core import fhir as f
|
from core import fhir as f
|
||||||
from core import follow_up as fu
|
from core import follow_up as fu
|
||||||
from core import measures as m
|
from core import measures as m
|
||||||
from core.domains import Domain
|
from core.domains import Domain
|
||||||
|
from core.pipeline import ID_PATTERN
|
||||||
|
from persistance import config_log, readers
|
||||||
from persistance import fhir as reads
|
from persistance import fhir as reads
|
||||||
from persistance import measures as measure_reads
|
from persistance import measures as measure_reads
|
||||||
|
from webapi.ingest import submit
|
||||||
|
from webapi.runs import dagster
|
||||||
|
|
||||||
FHIR_JSON = "application/fhir+json"
|
FHIR_JSON = "application/fhir+json"
|
||||||
MEASURES = {Domain.CACU: m.MEASURES}
|
MEASURES = {Domain.CACU: m.MEASURES}
|
||||||
@@ -94,8 +100,29 @@ def read_patient(domain: Domain, id: str) -> Response:
|
|||||||
_clinical(domain)
|
_clinical(domain)
|
||||||
(row,) = reads.rows("person", id=id) or [None]
|
(row,) = reads.rows("person", id=id) or [None]
|
||||||
if row is None:
|
if row is None:
|
||||||
raise HTTPException(404, f"no Patient/{id}")
|
(link,) = reads.rows("replaced", id=id) or [None]
|
||||||
return fhir(f.patient({**row, "status": fu.status(row, _cutoff(None))}))
|
if link is None:
|
||||||
|
raise HTTPException(404, f"no Patient/{id}")
|
||||||
|
return fhir(f.replaced_patient(id, link["replaced_by"]))
|
||||||
|
(found,) = _with_identity([{**row, "status": fu.status(row, _cutoff(None))}])
|
||||||
|
return fhir(f.patient(found))
|
||||||
|
|
||||||
|
|
||||||
|
def _with_identity(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("names", persons=persons):
|
||||||
|
names.setdefault(r["person_id"], []).append(r["text"])
|
||||||
|
for r in reads.rows("identifiers", persons=persons):
|
||||||
|
ids.setdefault(r["person_id"], []).append((r["system"], r["value"]))
|
||||||
|
for r in reads.rows("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
|
||||||
|
|
||||||
|
|
||||||
@router.get("/Patient", responses=_OK, response_class=Response)
|
@router.get("/Patient", responses=_OK, response_class=Response)
|
||||||
@@ -148,15 +175,16 @@ def search_patient(
|
|||||||
rows = fu.ordered(rows, sort, risks, horizon)
|
rows = fu.ordered(rows, sort, risks, horizon)
|
||||||
page = _sliced(rows, count, offset)
|
page = _sliced(rows, count, offset)
|
||||||
mine = {r["person_id"] for r in page}
|
mine = {r["person_id"] for r in page}
|
||||||
included = _included(revinclude, include, sorted(mine), at,
|
included = _included(domain, revinclude, include, sorted(mine), at,
|
||||||
{p: v for p, v in risks.items() if p in mine}) # fmt: skip
|
{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 window is not None else None
|
||||||
return bundle(request, [f.patient(r) for r in page], len(rows), count, offset, included,
|
patients = [f.patient(r) for r in _with_identity(page)]
|
||||||
|
return bundle(request, patients, len(rows), count, offset, included,
|
||||||
applied) # fmt: skip
|
applied) # fmt: skip
|
||||||
|
|
||||||
|
|
||||||
def _included(revinclude: list[str], include: list[str], persons: list[str], at: date,
|
def _included(domain: Domain, revinclude: list[str], include: list[str], persons: list[str],
|
||||||
risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
at: date, risks: dict[str, list[dict]]) -> list[Resource]: # fmt: skip
|
||||||
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
unknown = set(revinclude) - set(REVINCLUDES) | set(include) - {"DiagnosticReport:result"}
|
||||||
if unknown:
|
if unknown:
|
||||||
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
raise HTTPException(422, f"cannot include {sorted(unknown)}")
|
||||||
@@ -166,12 +194,10 @@ def _included(revinclude: list[str], include: list[str], persons: list[str], at:
|
|||||||
reports and "DiagnosticReport:result" in include
|
reports and "DiagnosticReport:result" in include
|
||||||
)
|
)
|
||||||
if reports or observations:
|
if reports or observations:
|
||||||
for row in reads.rows("cytology", persons=persons, cutoff=at.isoformat()):
|
for r in _studies(domain, persons, at.isoformat()):
|
||||||
report, *results = f.cytology(row)
|
kind = r.get_resource_type()
|
||||||
found += ([report] if reports else []) + (results if observations else [])
|
if (kind == "DiagnosticReport" and reports) or (kind == "Observation" and observations):
|
||||||
if reports:
|
found.append(r)
|
||||||
found += [f.biopsy(r) for r in reads.rows("biopsy", persons=persons,
|
|
||||||
cutoff=at.isoformat())] # fmt: skip
|
|
||||||
if "RiskAssessment:subject" in revinclude:
|
if "RiskAssessment:subject" in revinclude:
|
||||||
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
found += _risk_assessments([r for p in persons for r in risks.get(p, [])])
|
||||||
return found
|
return found
|
||||||
@@ -186,6 +212,28 @@ def _subjects(subject: str | None) -> list[str]:
|
|||||||
return [s.removeprefix("Patient/") for s in subject.split(",")]
|
return [s.removeprefix("Patient/") for s in subject.split(",")]
|
||||||
|
|
||||||
|
|
||||||
|
# Facts gold adds to a study's report (CaCu: days from the sample to its diagnosis).
|
||||||
|
REPORT_FACTS = {"cervical_cytology": "diagnosis_days"}
|
||||||
|
|
||||||
|
|
||||||
|
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] = []
|
||||||
|
for study in catalog.of_domain(domain.value):
|
||||||
|
spec = catalog.studies()[study]
|
||||||
|
facts = {}
|
||||||
|
if kind := REPORT_FACTS.get(study):
|
||||||
|
facts = {(r["person_id"], str(r["sample_date"])[:10]): r["days"]
|
||||||
|
for r in reads.rows(kind, persons=persons, cutoff=at)} # 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))]
|
||||||
|
found += f.instance(study, f.known(study, row, at), extra)
|
||||||
|
return found
|
||||||
|
|
||||||
|
|
||||||
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
def _risk_assessments(rows: list[dict]) -> list[Resource]:
|
||||||
groups: dict[tuple, list[dict]] = {}
|
groups: dict[tuple, list[dict]] = {}
|
||||||
for r in rows:
|
for r in rows:
|
||||||
@@ -212,27 +260,35 @@ def search_diagnostic_report(request: Request, domain: Domain,
|
|||||||
subject: str | None = Query(None, description=SUBJECT),
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
_count: int | None = Query(None),
|
_count: int | None = Query(None),
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
"""Cervical cytologies and biopsies, as known by the last day with data."""
|
"""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)
|
_clinical(domain)
|
||||||
count, offset = _page(_count, _offset)
|
count, offset = _page(count, offset)
|
||||||
persons, at = _subjects(subject), _cutoff(None).isoformat()
|
persons, at = _subjects(subject), _cutoff(None).isoformat()
|
||||||
found = [f.cytology(r)[0] for r in reads.rows("cytology", persons=persons, cutoff=at)]
|
found = [r for r in _studies(domain, persons, at) if r.get_resource_type() == kind]
|
||||||
found += [f.biopsy(r) for r in reads.rows("biopsy", persons=persons, cutoff=at)]
|
|
||||||
found.sort(key=lambda r: (str(r.effectiveDateTime), r.code.coding[0].code))
|
|
||||||
return bundle(request, _sliced(found, count, offset), len(found), count, offset)
|
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)
|
@router.get("/Observation", responses=_OK, response_class=Response)
|
||||||
def search_observation(request: Request, domain: Domain,
|
def search_observation(request: Request, domain: Domain,
|
||||||
subject: str | None = Query(None, description=SUBJECT),
|
subject: str | None = Query(None, description=SUBJECT),
|
||||||
_count: int | None = Query(None),
|
_count: int | None = Query(None),
|
||||||
_offset: int = Query(0)) -> Response: # fmt: skip
|
_offset: int = Query(0)) -> Response: # fmt: skip
|
||||||
"""The results of cervical cytologies (Bethesda, adequacy, HPV)."""
|
"""Every result of the domain's reports, one per field of the catalog."""
|
||||||
|
return _study_search("Observation", request, domain, subject, _count, _offset)
|
||||||
def build(rows):
|
|
||||||
return [o for r in rows for o in f.cytology(r)[1:]]
|
|
||||||
|
|
||||||
return _clinical_search("cytology", build, request, domain, subject, _count, _offset)
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/Condition", responses=_OK, response_class=Response)
|
@router.get("/Condition", responses=_OK, response_class=Response)
|
||||||
@@ -331,6 +387,42 @@ def search_measure_report(
|
|||||||
return bundle(request, reports, len(asked), count, offset)
|
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 ----------------------------------------------------------------------
|
# --- CapabilityStatement ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
@@ -338,8 +430,14 @@ def search_measure_report(
|
|||||||
def metadata(request: Request, domain: Domain) -> Response:
|
def metadata(request: Request, domain: Domain) -> Response:
|
||||||
"""What this base serves: built from the routes above, so it cannot drift from them."""
|
"""What this base serves: built from the routes above, so it cannot drift from them."""
|
||||||
resources: dict[str, dict] = {}
|
resources: dict[str, dict] = {}
|
||||||
|
system: list[dict] = []
|
||||||
for route in router.routes:
|
for route in router.routes:
|
||||||
_, kind, *rest = route.path.removeprefix(router.prefix).split("/")
|
path = route.path.removeprefix(router.prefix)
|
||||||
|
if not path: # the base itself: the FHIR door
|
||||||
|
if domain in CLINICAL:
|
||||||
|
system = [{"code": "batch"}, {"code": "transaction"}]
|
||||||
|
continue
|
||||||
|
_, kind, *rest = path.split("/")
|
||||||
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
if kind == "metadata" or (kind != "Measure" and kind != "MeasureReport"
|
||||||
and domain not in CLINICAL): # fmt: skip
|
and domain not in CLINICAL): # fmt: skip
|
||||||
continue
|
continue
|
||||||
@@ -368,7 +466,8 @@ def metadata(request: Request, domain: Domain) -> Response:
|
|||||||
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
"implementation": {"description": f"ISSSTELEON {domain.value}",
|
||||||
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
"url": str(request.base_url).rstrip("/") + f"/{domain.value}/fhir"},
|
||||||
"rest": [{"mode": "server",
|
"rest": [{"mode": "server",
|
||||||
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()]}],
|
"resource": [{k: v for k, v in r.items() if v} for r in resources.values()],
|
||||||
|
**({"interaction": system} if system else {})}],
|
||||||
}) # fmt: skip
|
}) # fmt: skip
|
||||||
return fhir(statement)
|
return fhir(statement)
|
||||||
|
|
||||||
|
|||||||
+41
-4
@@ -5,8 +5,10 @@ from typing import Annotated, Any
|
|||||||
|
|
||||||
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
|
||||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query, UploadFile
|
from fastapi import APIRouter, Depends, HTTPException, Path, Query, UploadFile
|
||||||
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from core import concept_map
|
||||||
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
from core.pipeline import ID_PATTERN, ImportPath, Pipeline, Source, redacted, restored
|
||||||
from core.schema import ENTITIES
|
from core.schema import ENTITIES
|
||||||
from persistance import config_log, nodes
|
from persistance import config_log, nodes
|
||||||
@@ -90,7 +92,11 @@ def pipeline(pipeline_id: PipelineId, version: int | None = None) -> SavedPipeli
|
|||||||
|
|
||||||
@router.put("/pipelines/{pipeline_id}")
|
@router.put("/pipelines/{pipeline_id}")
|
||||||
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
||||||
"""Saves a new version. Masked secrets sent back are kept as they were saved."""
|
"""Saves a new version. Masked secrets sent back are kept as they were saved; every
|
||||||
|
ConceptMap a node names must exist."""
|
||||||
|
named = {n.concept_map for n in drawn.nodes if getattr(n, "concept_map", None)}
|
||||||
|
if missing := sorted(m for m in named if not config_log.latest_version(m, "concept_maps")):
|
||||||
|
raise HTTPException(422, detail=f"no concept maps {missing}")
|
||||||
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
previous = config_log.get(pipeline_id)[1] if config_log.latest_version(pipeline_id) else None
|
||||||
try:
|
try:
|
||||||
complete = restored(drawn, previous)
|
complete = restored(drawn, previous)
|
||||||
@@ -99,6 +105,33 @@ def save_pipeline(pipeline_id: PipelineId, drawn: Pipeline) -> dict[str, int]:
|
|||||||
return {"version": config_log.save(pipeline_id, complete)}
|
return {"version": config_log.save(pipeline_id, complete)}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/concept-maps")
|
||||||
|
def concept_maps() -> Rows:
|
||||||
|
"""Every ConceptMap a site saved: its id, latest version and when."""
|
||||||
|
return config_log.listing("concept_maps")
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/concept-maps/{map_id}")
|
||||||
|
def get_concept_map(map_id: PipelineId) -> dict[str, Any]:
|
||||||
|
"""A site's codes in platform terms (FHIR R4B ConceptMap), latest version."""
|
||||||
|
if not config_log.latest_version(map_id, "concept_maps"):
|
||||||
|
raise HTTPException(404, detail=f"no concept map {map_id}")
|
||||||
|
return config_log.concept_map(map_id).model_dump(mode="json", exclude_none=True)
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/concept-maps/{map_id}")
|
||||||
|
def save_concept_map(map_id: PipelineId, doc: dict[str, Any]) -> dict[str, int]:
|
||||||
|
"""Saves a new version of a ConceptMap. Its groups target the systems platform fields
|
||||||
|
take codes from, and only codes those fields allow (core.concept_map)."""
|
||||||
|
try:
|
||||||
|
found = ConceptMap.model_validate({**doc, "resourceType": "ConceptMap"})
|
||||||
|
except ValueError as e:
|
||||||
|
raise HTTPException(422, detail=str(e)) from e
|
||||||
|
if problems := concept_map.problems(found):
|
||||||
|
raise HTTPException(422, detail=problems)
|
||||||
|
return {"version": config_log.save(map_id, found, "concept_maps")}
|
||||||
|
|
||||||
|
|
||||||
class RunRequest(BaseModel):
|
class RunRequest(BaseModel):
|
||||||
version: int | None = None # default: the latest saved
|
version: int | None = None # default: the latest saved
|
||||||
|
|
||||||
@@ -112,14 +145,18 @@ def start_run(
|
|||||||
"""Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}."""
|
"""Starts the `ingest` job for this pipeline; follow it at /runs/{run_id}."""
|
||||||
if not config_log.latest_version(pipeline_id):
|
if not config_log.latest_version(pipeline_id):
|
||||||
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
raise HTTPException(404, detail=f"no pipeline {pipeline_id}")
|
||||||
config = {"pipeline": pipeline_id, "version": request.version}
|
return {"run_id": submit(client, pipeline_id, request.version)}
|
||||||
|
|
||||||
|
|
||||||
|
def submit(client: DagsterGraphQLClient, pipeline_id: str, version: int | None = None) -> str:
|
||||||
|
"""Starts the `ingest` job for a saved pipeline (the latest version by default)."""
|
||||||
|
config = {"pipeline": pipeline_id, "version": version}
|
||||||
try:
|
try:
|
||||||
run_id = client.submit_job_execution(
|
return client.submit_job_execution(
|
||||||
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
"ingest", run_config={"ops": {"run_pipeline": {"config": config}}}
|
||||||
)
|
)
|
||||||
except DagsterGraphQLClientError as e:
|
except DagsterGraphQLClientError as e:
|
||||||
raise HTTPException(502, detail=str(e)) from e
|
raise HTTPException(502, detail=str(e)) from e
|
||||||
return {"run_id": run_id}
|
|
||||||
|
|
||||||
|
|
||||||
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
|
@router.get("/pipelines/{pipeline_id}/nodes/{node_id}/rows")
|
||||||
|
|||||||
Reference in New Issue
Block a user