"""What this module covers: each CaMa patient's clinical scenario, inferred by dbt (`cama_procedimientos_inferidos`, rules in `cama.escenarios`): post-treatment from a discharge note after a malignant breast tumour's diagnosis, carried by her timeline as an `escenario_postratamiento` fact with the evidence that started it; every other patient is under observation ("en observación"), which has no fact. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database (`staging/cama.py`) loaded, with dbt's views. Its records: first mammograms taken H-001 2025-03-10, H-003 06-30, H-101 01-15, H-102 02-20, H-103 07-01, H-104 11-11; notes H-003 C50.4 (08-04), H-103 C50.9 (07-20), H-102 C50.9 (09-30), H-001 D05.1 (03-01), H-101 Z12.3 (01-15), H-104 C50 without a date; H-003 an invasive biopsy (07-28). No note has a type: the tests that need a discharge write `nota_medica.tipo_nota` themselves. """ import os from datetime import date from pathlib import Path import pytest from conftest import base_de from sqlalchemy import text @pytest.fixture def manifest(): path = os.environ.get("DBT_MANIFEST") if not path: pytest.skip("DBT_MANIFEST isn't set: `dbt compile` in Transformation writes it") return Path(path) @pytest.fixture def base(tmp_path, manifest): base = base_de("cama", tmp_path) base.run("catalogs", "load", "views", "event_models") yield base base.motor.dispose() def scenarios(base) -> dict[str, set[tuple[str, date, str]]]: """Patient (hospital id) -> the scenario facts of her timeline, (tipo, fecha, evidence).""" with base.motor.connect() as con: rows = con.execute(text( "select p.pac_id_hospital, l.tipo, l.fecha, l.valor_codigo from cama_linea_de_tiempo l " "join paciente p on p.pac_id = l.pac_id where l.tipo like 'escenario%'")).all() found: dict[str, set[tuple[str, date, str]]] = {} for r in rows: found.setdefault(r.pac_id_hospital, set()).add((r.tipo, date.fromisoformat(str(r.fecha)[:10]), r.valor_codigo)) return found def discharge(base, hospital_id: str) -> None: """Marks the patient's notes as discharge notes, as a load that brings `nm_tipo_nota` would.""" with base.motor.begin() as con: con.execute(text( "insert into observacion_clinica (procedimiento_id, carga_id, pac_id, resultado_id, valor_id, valor_fuente) " "select p.procedimiento_id, p.carga_id, p.pac_id, 'nota_medica.tipo_nota', 'EGRESO', 'EGRESO' " "from procedimiento p join paciente x on x.pac_id = p.pac_id " "where p.estudio_id = 'nota_medica' and p.clase = 'encuentro' and x.pac_id_hospital = :h"), {"h": hospital_id}) def test_without_a_discharge_every_patient_is_under_observation(base): """Pins down: a mammogram, a malignant ICD-10 note (H-003, H-102, H-103) or an invasive biopsy (H-003) alone start no scenario: with no discharge note nobody is in post-treatment and the timeline has no scenario fact, which reads as under observation. Fails if screening or a diagnosis go back to being scenarios of their own.""" assert scenarios(base) == {} def test_a_discharge_note_with_the_diagnosis_starts_post_treatment(base): """Pins down: a discharge note that carries a malignant tumour's ICD-10 puts H-003 in post-treatment from its date, and only her. Fails if `tipos_nota_egreso` loses EGRESO or the discharge rule stops reading the note's type.""" discharge(base, "H-003") assert scenarios(base) == {"H-003": {("escenario_postratamiento", date(2025, 8, 4), "egreso")}} def test_a_discharge_without_a_diagnosis_is_not_post_treatment(base): """Pins down: a discharge of a patient with no malignant diagnosis (H-101's screening note, Z12.3) leaves her under observation: post-treatment needs the diagnosis. Fails if the discharge rule stops asking for it.""" discharge(base, "H-101") assert scenarios(base) == {}