diff --git a/tests/test_cama_follow_up.py b/tests/test_cama_follow_up.py index 31655a0..a2a6c0a 100644 --- a/tests/test_cama_follow_up.py +++ b/tests/test_cama_follow_up.py @@ -8,6 +8,7 @@ invented patients with the cases below; their names (`P01`...) are the source id Cohort at 2025-12-31 (reported by then, latest mammogram per patient, BI-RADS 4 to 6): BI-RADS 5: P01-P06; 4A: P07-P11; 6: P12, P13; 4 without subcategory: P14; P17 has two mammograms the same day. P15's latest mammogram is BI-RADS 2 and P16's BI-RADS 5 is reported after the cut-off: neither is in it. +No patient has a post-treatment fact in her timeline, so everyone is under observation; `con_postratamiento` adds some. """ import json @@ -151,14 +152,16 @@ def test_the_biopsy_shown_is_the_latest_report_known_at_the_cutoff(base, app): def test_the_rows_carry_only_what_silver_holds_and_the_platform_identifier(base, app): """Pins down: each item has exactly pac_id (decimal text), age group, BI-RADS and its date, biopsy result and its - date: no status, priority, days or pseudonym, and no source id anywhere in the body. Fails if a column the data - doesn't support is added, or the hospital's identifier leaks.""" + date, and the clinical scenario: no status, priority, days or pseudonym, and no source id anywhere in the body. + Fails if a column the data doesn't support is added, or the hospital's identifier leaks.""" respuesta = get(app, page_size=200) cuerpo = respuesta.get_json() assert cuerpo["simulado"] is True - assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha"} for i in cuerpo["items"]) + assert all(set(i) == {"pac_id", "grupo_edad", "birads", "mastografia_fecha", "biopsia", "biopsia_fecha", + "escenario_clinico"} for i in cuerpo["items"]) + assert {i["escenario_clinico"] for i in cuerpo["items"]} == {"EN_OBSERVACION"} assert all(i["pac_id"].isdigit() and not i["pac_id"].startswith("0") for i in cuerpo["items"]) - assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia"] + assert [c["clave"] for c in cuerpo["columnas"]] == ["pac_id", "grupo_edad", "birads", "biopsia", "escenario_clinico"] assert not any(h in respuesta.get_data(as_text=True) for h in PACIENTES) assert respuesta.headers["Cache-Control"] == "no-store" @@ -368,3 +371,51 @@ def test_two_reports_of_one_mammogram_resolve_to_the_later_one_and_two_patients_ with Session(base.motor) as sesion: cohorte_ = cohort.cohorte_al(sesion, D(2025, 12, 31)) assert sorted((f.pac_id, f.birads) for f in cohorte_) == [(1, "BIRADS_5"), (2, "BIRADS_6")] + + +@pytest.fixture +def con_postratamiento(tmp_path): + """The same 17 patients, with the timeline replaced by a table holding post-treatment facts: P01 to P05 on + 2025-11-01 and P06 on 2026-01-15, after the cut-off.""" + if not os.environ.get("DBT_MANIFEST"): + pytest.skip("DBT_MANIFEST isn't set: dbt compile in Transformation writes it") + from sqlalchemy import text + + base = base_de("cama", tmp_path, datos=insertar) + base.run(*UNTIL_MODELS, allow_undecided=True) + hechos = {**{f"P0{n}": "2025-11-01" for n in range(1, 6)}, "P06": "2026-01-15"} + with base.motor.begin() as c: + for drop in ("drop view cama_linea_de_tiempo", "drop table cama_linea_de_tiempo"): + try: + with c.begin_nested(): + c.execute(text(drop)) + except Exception: + pass + c.execute(text("create table cama_linea_de_tiempo (pac_id integer, tipo text, fecha date)")) + for hospital, fecha in hechos.items(): + c.execute(text("insert into cama_linea_de_tiempo select pac_id, 'escenario_postratamiento', :f from paciente " + "where pac_id_hospital = :h"), {"f": fecha, "h": hospital}) + flask = Flask(__name__) + flask.register_blueprint(follow_up_blueprint(lambda: Session(base.motor)), url_prefix="/cama") + yield base, flask.test_client() + base.motor.dispose() + + +def test_the_clinical_scenario_is_post_treatment_from_its_fact_and_under_observation_otherwise(con_postratamiento): + """Pins down: a patient is `POST_TRATAMIENTO` once her timeline's `escenario_postratamiento` fact is on or before the + cut-off (P01-P05 at 2025-12-31, P06 only from 2026-01-15) and `EN_OBSERVACION` otherwise; the filter selects by it + and offers both values with their labels. Fails if a fact after the cut-off counts, if the scenario is read from + something other than the timeline, or if the filter stops being offered.""" + base, app = con_postratamiento + nombres = hospital_de(base) + escenario = lambda corte: {nombres[i["pac_id"]]: i["escenario_clinico"] + for i in get(app, corte=corte, page_size=200).get_json()["items"]} + al_corte = escenario(CORTE) + assert {h for h, e in al_corte.items() if e == "POST_TRATAMIENTO"} == {"P01", "P02", "P03", "P04", "P05"} + assert {e for h, e in al_corte.items() if h not in {"P01", "P02", "P03", "P04", "P05"}} == {"EN_OBSERVACION"} + assert escenario("2026-01-31")["P06"] == "POST_TRATAMIENTO" + filtrada = get(app, escenario_clinico="POST_TRATAMIENTO", page_size=200) + assert {nombres[p] for p in pacs(filtrada)} == {"P01", "P02", "P03", "P04", "P05"} + filtro = next(f for f in filtrada.get_json()["filtros_disponibles"] if f["clave"] == "escenario_clinico") + assert filtro["opciones"] == [{"codigo": "POST_TRATAMIENTO", "etiqueta": "Post-tratamiento"}, + {"codigo": "EN_OBSERVACION", "etiqueta": "En observación"}] diff --git a/tests/test_cama_scenarios.py b/tests/test_cama_scenarios.py new file mode 100644 index 0000000..d893976 --- /dev/null +++ b/tests/test_cama_scenarios.py @@ -0,0 +1,78 @@ +"""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) == {} diff --git a/tests/test_cama_stratifiers.py b/tests/test_cama_stratifiers.py index 219a318..8d5361b 100644 --- a/tests/test_cama_stratifiers.py +++ b/tests/test_cama_stratifiers.py @@ -1,13 +1,13 @@ -"""What this module covers: CaMa's tumour stratifiers, from the results read from reports to a measure's strata. -dbt's `cama_estratificadores` (stage group, early or advanced stage, surrogate molecular subtype, T by size) as -timeline facts; `CAMA_BIRADS_CANCER_INVASOR` broken down by them with the `linea_de_tiempo_al_corte` stratum; and the -labels a timeline stratum's values carry into FHIR. +"""What this module covers: CaMa's tumour characteristics read from reports. dbt's `cama_estratificadores` (stage +group, early or advanced stage, T by size) as timeline facts; that no measure is served by clinical stage or tumour +size; `CAMA_BIRADS_CANCER_INVASOR` without tumour strata; and the labels a timeline stratum's values carry into FHIR. Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base`, the CaMa fixture database (`staging/cama.py`) through the cycle up to `event_models`. Only H-003 has an invasive cancer: biopsy reported on -2025-07-28 from her BI-RADS 4A mammogram (14 mm), HER2 3+, and a note of 2025-08-04 with stage IIA. +2025-07-28 from her BI-RADS 4A mammogram (14 mm), and a note of 2025-08-04 with stage IIA. """ +import json import os from dataclasses import replace from datetime import date @@ -20,7 +20,7 @@ from webapi.compositions import answer_composition, composition_definitions from webapi.fhir.measures import _label from webapi.metrics import Question -URL = "cama/CAMA_BIRADS_CANCER_INVASOR" +BIRADS = "cama/CAMA_BIRADS_CANCER_INVASOR" UNTIL_MODELS = ("catalogs", "load", "views", "registry", "definitions", "event_models") @@ -40,72 +40,43 @@ def base(tmp_path, sin_supresion, manifest): base.motor.dispose() -def answered(base, manifest, period: str, event_cutoff: date | None = None): +def answered(base, manifest, url: str, period: str, event_cutoff: date | None = None): d = base.dominio - definition = composition_definitions(manifest)[URL] - return answer_composition("cama", definition, Question(URL, period, event_cutoff=event_cutoff), + definition = composition_definitions(manifest)[url] + return answer_composition("cama", definition, Question(url, period, event_cutoff=event_cutoff), parameters=d.def_parametro_repository, periods=d.dim_periodo_repository, history=d.history_repository, queries=d.dbt_query_repository, allow_undecided=True) -def stratifiers(base) -> set[str]: +def stratifiers(base, manifest) -> set[str]: + """The stratifiers' `tipo`s, from the view built here: no served measure reads it, so the cycle doesn't.""" + node = next(n for n in json.loads(manifest.read_text(encoding="utf-8"))["nodes"].values() + if n["resource_type"] == "model" and n["name"] == "cama_estratificadores") with base.motor.connect() as con: - return set(con.execute(text("select tipo from cama_estratificadores")).scalars()) + return set(con.execute(text(f"select tipo from ({node['compiled_code']}) e")).scalars()) -def test_the_stratifiers_come_from_h003_s_reports(base): - """Pins down: the view derives the stage's group and early stage from the note, the subtype from the pathology - report and T1 from the 14 mm lesion, and nothing for patients without those results. Fails if a rule in - `vars.cama.estratos` or a timeline `tipo` it reads changes.""" - assert stratifiers(base) == {"estadio_ii", "etapa_temprana", "subtipo_her2", "tamano_t1"} +def test_the_stratifiers_come_from_h003_s_reports(base, manifest): + """Pins down: the view derives the stage's group and early stage from the note and T1 from the 14 mm lesion, and + nothing else: there's no molecular subtype. Fails if a rule in `vars.cama.estratos` or a timeline `tipo` it reads + changes, or a subtype comes back.""" + assert stratifiers(base, manifest) == {"estadio_ii", "etapa_temprana", "tamano_t1"} -def test_the_measure_breaks_down_the_invasive_cancers_by_tumour(base, manifest): - """Pins down: H-003 counts in S2, the period of her biopsy report, under the BI-RADS of the mammogram that led to - it, and in each stratum by what her reports said. S1 has no invasive cancer. Fails if the event model, the - category or a stratum's values drift.""" - assert answered(base, manifest, "2025-S1").categories == {} - result = answered(base, manifest, "2025-S2") - assert result.categories == {"B4A": 1} - assert result.strata == {"grupo_edad": {"50-59": {"B4A": 1}}, "estadio": {"II": {"B4A": 1}}, - "etapa": {"TEMPRANA": {"B4A": 1}}, "clasificacion": {"HER2": {"B4A": 1}}, - "tamano": {"T1": {"B4A": 1}}} +def test_no_measure_is_served_by_stage_or_tumour_size(manifest): + """Pins down: clinical stage and tumour size aren't served as measures; they come from reports read by text, not + yet validated. Fails if a measure on them is published again.""" + metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values() + urls = {m["config"].get("meta", {}).get("measure_url") for m in metrics} - {None} + assert BIRADS in urls and BIRADS in composition_definitions(manifest) + assert not {u for u in urls if "ESTADIO" in u or "TAMANO" in u} -def test_a_stratum_by_the_cut_off_sees_only_what_was_dated_by_then(base, manifest): - """Pins down: `linea_de_tiempo_al_corte` reads the timeline up to the event cut-off: on 2025-08-01 the subtype - (report of 07-28) is known and the stage (note of 08-04) isn't yet. Fails if the stratum reads before the period's - start (H-003 would have nothing) or ignores the cut-off (she'd have her stage).""" - strata = answered(base, manifest, "2025-S2", event_cutoff=date(2025, 8, 1)).strata - assert strata["clasificacion"] == {"HER2": {"B4A": 1}} - assert strata["estadio"] == {"SIN_DATO": {"B4A": 1}} - - -SUBTIPOS = [ - ({"her2": "H3"}, "subtipo_her2"), - ({"her2": "H1", "receptor_estrogeno": "NEGATIVO", "receptor_progesterona": "NEGATIVO"}, "subtipo_triple_negativo"), - ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 10.0}, "subtipo_luminal_a"), - ({"her2": "H0", "receptor_progesterona_pct": 50.0, "ki67_pct": 30.0}, "subtipo_luminal_b"), - ({"her2": "H0", "receptor_progesterona_pct": 10.0, "ki67_pct": 10.0}, "subtipo_luminal_b"), - ({"her2": "H0", "ki67_pct": None}, None), - ({"her2": "H2"}, None), -] - - -@pytest.mark.parametrize("cambios, subtipo", SUBTIPOS) -def test_the_surrogate_subtype_follows_its_rules(base, cambios, subtipo): - """Pins down the surrogate subtype from one pathology report: HER2 3+ is HER2-positive; HER2 0 or 1+ with both - receptors negative, triple negative; with a positive receptor, luminal A only with Ki-67 under 20 % and - progesterone of at least 20 %, else luminal B; without Ki-67, or with an equivocal HER2, none. The fixture's - report starts as ER+ 90 %, PR- 0 %, HER2 3+, Ki-67 25 %, with PR made positive here unless a case says otherwise. - Fails if a branch of the rule or a threshold in `vars.cama.estratos` changes.""" - valores = {"receptor_progesterona": "POSITIVO", **cambios} - with base.motor.begin() as con: - for nombre, valor in valores.items(): - columna = "valor_numerico" if nombre.endswith("_pct") else "valor_id" - con.execute(text(f"update observacion_clinica set {columna} = :v where resultado_id = :r"), - {"v": valor, "r": f"biopsia.{nombre}"}) - assert {t for t in stratifiers(base) if t.startswith("subtipo_")} == ({subtipo} if subtipo else set()) +def test_the_birads_of_the_invasive_cancers_has_no_tumour_strata(base, manifest): + """Pins down: the BI-RADS of the mammogram before an invasive cancer isn't broken down by the tumour's + characteristics, which describe the cancer and not that mammogram. Fails if tumour strata come back.""" + result = answered(base, manifest, BIRADS, "2025-S2") + assert (result.categories, result.strata) == ({"B4A": 1}, {}) def test_a_timeline_stratum_s_values_carry_their_labels(): diff --git a/tests/test_date_of_death.py b/tests/test_date_of_death.py new file mode 100644 index 0000000..48e8f6a --- /dev/null +++ b/tests/test_date_of_death.py @@ -0,0 +1,62 @@ +"""What this module covers: a patient's date of death, from staging (`paciente.pac_fecha_defuncion`) to silver's +`persona.fecha_defuncion` in CaCu and CaMa, and in CaMa onto her timeline as a `defuncion` fact next to her birth. + +Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `base_con_defuncion`, the domain's +fixture database (`staging/.py`) with one patient given a date of death before it's loaded. +""" + +import os +from datetime import date +from pathlib import Path + +import pytest +from conftest import base_de +from sqlalchemy import text + +DEATH = date(2026, 2, 1) + + +@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) + + +def with_death(domain: str, tmp_path): + """The domain's fixture database with its first patient (lowest `pac_id`) dead on `DEATH`, loaded to silver.""" + base = base_de(domain, tmp_path) + with base.motor.begin() as con: + con.execute(text("update paciente set pac_fecha_defuncion = :d where pac_id = (select min(pac_id) from paciente)"), + {"d": DEATH}) + return base + + +@pytest.mark.parametrize("domain", ["cacu", "cama"]) +def test_silver_persona_carries_the_date_of_death(domain, tmp_path, manifest): + """Pins down: the dead patient's `persona` has her date of death and everyone else's is null. Fails if the + staging-to-silver copy (`persons.de_derechohabiente`) stops carrying `pac_fecha_defuncion`.""" + base = with_death(domain, tmp_path) + base.run("catalogs", "load") + with base.motor.connect() as con: + rows = con.execute(text("select pac_id, fecha_defuncion from persona order by pac_id")).all() + base.motor.dispose() + assert [date.fromisoformat(str(rows[0].fecha_defuncion)[:10])] + [r.fecha_defuncion for r in rows[1:]] \ + == [DEATH] + [None] * (len(rows) - 1) + + +def test_cama_timeline_has_birth_for_everyone_and_death_for_the_dead(tmp_path, manifest): + """Pins down: every CaMa patient has a `nacimiento` fact and only the dead one a `defuncion` fact, on her date of + death, with class `persona`. Fails if the timeline stops reading `persona` or reads a null date as a death.""" + base = with_death("cama", tmp_path) + base.run("catalogs", "load", "views", "event_models") + with base.motor.connect() as con: + people = con.execute(text("select count(*) from persona")).scalar_one() + facts = con.execute(text( + "select tipo, pac_id, fecha, clase from cama_linea_de_tiempo where tipo in ('nacimiento', 'defuncion')")).all() + first = con.execute(text("select min(pac_id) from persona")).scalar_one() + base.motor.dispose() + assert sum(f.tipo == "nacimiento" for f in facts) == people + assert [(f.pac_id, date.fromisoformat(str(f.fecha)[:10]), f.clase) for f in facts if f.tipo == "defuncion"] \ + == [(first, DEATH, "persona")] diff --git a/tests/test_extracted_results.py b/tests/test_extracted_results.py index 8dd938e..440f42e 100644 --- a/tests/test_extracted_results.py +++ b/tests/test_extracted_results.py @@ -125,7 +125,7 @@ def test_a_pathology_pdf_s_text_layer_gives_its_results(): going through the PDF reader, or a receptor's percentage stops sharing its captions with the receptor.""" leido = cama.DEL_REPORTE_DE_PATOLOGIA.leer(SimpleNamespace(bx_pdf_blob=pdf_de(INFORME_DE_PATOLOGIA[1]))) assert {r: v for r, (v, _) in leido.items()} == { - "biopsia.tipo_histologico": "DUCTAL_INFILTRANTE", "biopsia.grado_nottingham": "G2", + "biopsia.tipo_histologico": "8500/3", "biopsia.grado_nottingham": "G2", "biopsia.receptor_estrogeno": "POSITIVO", "biopsia.receptor_estrogeno_pct": 90.0, "biopsia.receptor_progesterona": "NEGATIVO", "biopsia.receptor_progesterona_pct": 0.0, "biopsia.her2": "H3", "biopsia.ki67_pct": 25.0, diff --git a/tests/test_orquestacion_oro.py b/tests/test_orquestacion_oro.py index 8a1bd5c..eb2f598 100644 --- a/tests/test_orquestacion_oro.py +++ b/tests/test_orquestacion_oro.py @@ -84,9 +84,9 @@ def test_las_definiciones_son_las_del_manifiesto_de_dbt(base): measure the manifest declares stops reaching `cat_estrato` and `cat_measure`, or a second run deletes rows.""" resumen = base.run("definitions")["definitions"] - # CaCu: three strata and its seven measures; CaMa: the five strata of its invasive cancers, the BI-RADS stratum of the histopathological result and its eleven measures; - # TEA: the age group and its ten measures. - assert resumen["definitions"] == {"cacu": 10, "cama": 17, "tea": 11}[base.proyecto] + # CaCu: three strata and its seven measures; CaMa: the BI-RADS stratum of the histopathological result and its + # eleven measures; TEA: the age group and its ten measures. + assert resumen["definitions"] == {"cacu": 10, "cama": 12, "tea": 11}[base.proyecto] # Y el catálogo de publicación de §6f (T-19b): un `cat_measure` por measure, sincronizado. assert base.dominio.cat_measure_repository.count() == {"cacu": 7, "cama": 11, "tea": 10}[base.proyecto] assert base.run("definitions")["definitions"]["borradas"] == 0 diff --git a/webapi/cama_follow_up/cohort.py b/webapi/cama_follow_up/cohort.py index eb6932d..df7e8db 100644 --- a/webapi/cama_follow_up/cohort.py +++ b/webapi/cama_follow_up/cohort.py @@ -6,12 +6,14 @@ date taken, then the greatest source id, then the latest report date, then the g always gives the same cohort. A report that carries two different BI-RADS counts through the more severe one (`cama.birads_gravedad`), and a biopsy report with two different grades through the more severe grade. The biopsy shown is the latest report, on or before the cut-off and not before the mammogram, of a biopsy that mammogram led to. +Her clinical scenario at the cut-off is post-treatment when her timeline has an `escenario_postratamiento` fact dated on +or before it (`cama_procedimientos_inferidos`, rules in `cama.escenarios`), and under observation otherwise. Facts are read as silver holds them now: the list is not a reconstruction of what was known on the cut-off. """ from dataclasses import dataclass -from datetime import date +from datetime import date, timedelta from sqlalchemy import Date, Integer, String, column, func, inspect, select, table from sqlmodel import Session @@ -25,6 +27,8 @@ ESCENARIO = "diagnostico" VERSION = "0.1.0" SIN_DATO = "SIN_DATO" SIN_BIOPSIA = "SIN_BIOPSIA" +POST_TRATAMIENTO = "POST_TRATAMIENTO" +EN_OBSERVACION = "EN_OBSERVACION" # Grades from least to most severe, for two contradictory results of the same report; any other grade ranks lowest. GRADOS_POR_GRAVEDAD = ("BENIGNO", "CARCINOMA_IN_SITU", "CARCINOMA_INVASOR") @@ -35,14 +39,17 @@ CANDIDATOS = table( column("fecha_nacimiento", Date), column("biopsia_id", Integer), column("biopsia_fuente_id", String), column("biopsia_fecha_reporte", Date), column("biopsia_grado", String), ) +LINEA_DE_TIEMPO = table("cama_linea_de_tiempo", column("pac_id", Integer), column("tipo", String), column("fecha", Date)) class CohorteNoDisponible(RuntimeError): - """The cohort's view isn't in the database: the indicator cycle that creates the event views hasn't run (503).""" + """The cohort's view or the timeline isn't in the database: the indicator cycle that creates the event views hasn't + run (503).""" def disponible(sesion: Session) -> bool: - return inspect(sesion.get_bind()).has_table(CANDIDATOS.name) + inspector = inspect(sesion.get_bind()) + return all(inspector.has_table(t.name) for t in (CANDIDATOS, LINEA_DE_TIEMPO)) @dataclass(frozen=True) @@ -58,6 +65,7 @@ class Fila: # The earliest eligible biopsy report, and the earliest one whose grade counts as cancer (`cama.biopsia_cancer`). primera_biopsia_fecha: date | None = None primer_maligno_fecha: date | None = None + escenario_clinico: str = EN_OBSERVACION @property def resultado(self) -> str: @@ -93,8 +101,17 @@ def grupo_de_edad(nacimiento: date | None, corte: date, grupos: list) -> str: return SIN_DATO +def en_postratamiento(sesion: Session, corte: date) -> set[int]: + """The patients whose timeline puts them in post-treatment on or before `corte`.""" + linea = LINEA_DE_TIEMPO.c + # Before the next day, so a date stored with a time still counts on its own day. + return set(sesion.execute(select(linea.pac_id).distinct().where( + linea.tipo == "escenario_postratamiento", linea.fecha < corte + timedelta(days=1))).scalars()) + + def cohorte_al(sesion: Session, corte: date) -> list[Fila]: """The cohort at `corte`, latest mammogram first, then by `pac_id`.""" + postratamiento = en_postratamiento(sesion, corte) admitidos = set(valor_de(sesion, "cama.birads_4_a_6", tablas=TABLAS)) malignos = set(valor_de(sesion, "cama.biopsia_cancer", tablas=TABLAS)) grupos = grupos_de_cortes(valor_de(sesion, "cama.grupos_edad", tablas=TABLAS), tablas=TABLAS) @@ -133,6 +150,7 @@ def cohorte_al(sesion: Session, corte: date) -> list[Fila]: biopsia_fecha=biopsia["biopsia_fecha_reporte"] if biopsia else None, primera_biopsia_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"]), default=None), primer_maligno_fecha=min((b["biopsia_fecha_reporte"] for b in elegida["biopsias"] if b["biopsia_grado"] in malignos), default=None), + escenario_clinico=POST_TRATAMIENTO if pac_id in postratamiento else EN_OBSERVACION, )) return sorted(cohorte, key=lambda f: (-f.mastografia_fecha.toordinal(), f.pac_id)) diff --git a/webapi/cama_follow_up/listing.py b/webapi/cama_follow_up/listing.py index e45911e..3c8a9e0 100644 --- a/webapi/cama_follow_up/listing.py +++ b/webapi/cama_follow_up/listing.py @@ -14,7 +14,7 @@ from datetime import date, timedelta from sqlmodel import Session from webapi.cama_follow_up.cohort import ( - COHORTE, ESCENARIO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion, + COHORTE, EN_OBSERVACION, ESCENARIO, POST_TRATAMIENTO, SIN_BIOPSIA, SIN_DATO, VERSION, CohorteNoDisponible, Fila, codigo_birads, cohorte_al, construccion, disponible, grupos_de_edad, ) from webapi.orchestration.reference.rules import valor_de @@ -25,11 +25,13 @@ VENTANA_POR_OMISION = 3 PAGINA_MAXIMA = 200 EXPORTACION_MAXIMA = 5000 GRADOS = {"BENIGNO": "Benigno", "CARCINOMA_IN_SITU": "Carcinoma in situ", "CARCINOMA_INVASOR": "Carcinoma invasor"} +ESCENARIOS_CLINICOS = {POST_TRATAMIENTO: "Post-tratamiento", EN_OBSERVACION: "En observación"} COLUMNAS = [ {"clave": "pac_id", "etiqueta": "Identificador de paciente"}, {"clave": "grupo_edad", "etiqueta": "Grupo de edad"}, {"clave": "birads", "etiqueta": "Última mastografía", "detalles": [{"clave": "mastografia_fecha", "etiqueta": "Fecha"}]}, {"clave": "biopsia", "etiqueta": "Resultado histopatológico", "detalles": [{"clave": "biopsia_fecha", "etiqueta": "Fecha de reporte"}]}, + {"clave": "escenario_clinico", "etiqueta": "Escenario clínico"}, ] @@ -80,6 +82,8 @@ def filtros_disponibles(sesion: Session) -> list[dict]: *({"codigo": g, "etiqueta": e} for g, e in GRADOS.items()), {"codigo": SIN_DATO, "etiqueta": "Biopsia reportada sin resultado"}, {"codigo": SIN_BIOPSIA, "etiqueta": "Sin biopsia reportada"}]}, + {"clave": "escenario_clinico", "etiqueta": "Escenario clínico", "opciones": [ + {"codigo": c, "etiqueta": e} for c, e in ESCENARIOS_CLINICOS.items()]}, ] @@ -114,7 +118,8 @@ def _selecciona(cohorte: list[Fila], *, corte: date, meses: int, filtros: dict) def _item(f: Fila) -> dict: return {"pac_id": str(f.pac_id), "grupo_edad": f.grupo_edad, "birads": f.birads, "mastografia_fecha": f.mastografia_fecha.isoformat(), "biopsia": f.biopsia, - "biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None} + "biopsia_fecha": f.biopsia_fecha.isoformat() if f.biopsia_fecha else None, + "escenario_clinico": f.escenario_clinico} def _consulta(sesion: Session, *, corte, meses, filtros, contexto, hoy, page, page_size) -> tuple[dict, list[Fila]]: diff --git a/webapi/cama_follow_up/routes.py b/webapi/cama_follow_up/routes.py index 22d412b..112894c 100644 --- a/webapi/cama_follow_up/routes.py +++ b/webapi/cama_follow_up/routes.py @@ -15,7 +15,7 @@ from webapi.cama_follow_up.listing import ( ) FECHA = re.compile(r"\d{4}-\d{2}-\d{2}") -FILTROS = ("birads", "grupo_edad", "biopsia") +FILTROS = ("birads", "grupo_edad", "biopsia", "escenario_clinico") CONTEXTO = ("cohorte", "escenario", "revision") ENTEROS = ("meses", "page", "page_size") diff --git a/webapi/orchestration/reference/catalogs.py b/webapi/orchestration/reference/catalogs.py index 2691940..a4a8bd8 100644 --- a/webapi/orchestration/reference/catalogs.py +++ b/webapi/orchestration/reference/catalogs.py @@ -204,8 +204,8 @@ def _tipo_de_valor(resultado: dict, resultado_id: str) -> str: raise CatalogoInvalido(f"{resultado_id}: un resultado de tipo codigo necesita valores.") if tipo_valor != "codigo" and "valores" in resultado: raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo lleva valores, no uno de tipo {tipo_valor}.") - if tipo_valor != "externo" and "sistema" in resultado: - raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo externo lleva sistema, no uno de tipo {tipo_valor}.") + if tipo_valor not in ("codigo", "externo") and "sistema" in resultado: + raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo codigo o externo lleva sistema, no uno de tipo {tipo_valor}.") if tipo_valor != "numero" and "unidad" in resultado: raise CatalogoInvalido(f"{resultado_id}: solo un resultado de tipo numero lleva unidad, no uno de tipo {tipo_valor}.") return tipo_valor diff --git a/webapi/orchestration/silver/persons.py b/webapi/orchestration/silver/persons.py index ae7f31e..9f6c962 100644 --- a/webapi/orchestration/silver/persons.py +++ b/webapi/orchestration/silver/persons.py @@ -22,6 +22,7 @@ def de_derechohabiente(paciente) -> dict: "dependencia": texto_limpio(paciente.pac_dependencia), "parentesco": texto_limpio(paciente.pac_parentesco), "codigo_postal": texto_limpio(paciente.pac_codigo_postal), + "fecha_defuncion": paciente.pac_fecha_defuncion, }