"""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