From c2b18d996978847b1e361bc585ef07e5d9d65e10 Mon Sep 17 00:00:00 2001 From: Angel Capetillo Zavala Date: Sat, 21 Nov 2026 01:29:31 -0600 Subject: [PATCH] feat(fhir): publish optional category groups and stratum captions of compositions --- tests/test_cacu_measure_metadata.py | 213 ++++++++++++++++++++++++++++ webapi/compositions.py | 35 +++++ webapi/fhir/measures.py | 21 ++- 3 files changed, 266 insertions(+), 3 deletions(-) create mode 100644 tests/test_cacu_measure_metadata.py diff --git a/tests/test_cacu_measure_metadata.py b/tests/test_cacu_measure_metadata.py new file mode 100644 index 0000000..19a50d4 --- /dev/null +++ b/tests/test_cacu_measure_metadata.py @@ -0,0 +1,213 @@ +"""What this module covers: the publication metadata of CaCu's FHIR `Measure`s (figures, category captions and the +optional category groups) read from dbt's manifest alone, and the checks that keep a composition's groups consistent. + +Fixtures: `manifest`, dbt's `manifest.json` (`DBT_MANIFEST`; skipped without it); `parametros.toml`, the platform's +reference parameters, whose CaCu catalogs and lists hold the captions, colours and memberships the dbt definitions +repeat; Transformation's `dbt_project.yml` next to the manifest, whose variables repeat the same lists. +""" + +import os +import tomllib +from datetime import date, datetime, timezone +from pathlib import Path +from types import SimpleNamespace + +import pytest +from fhir.resources.R4B import get_fhir_model_class + +from webapi.compositions import CompositionAnswer, InvalidCategoryGroups, category_groups +from webapi.fhir.measures import CATEGORY_GROUP, CATEGORY_LABEL, FIGURES, labels, measure_report, measure_resource +from webapi.kpis import definitions_of + +REFERENCE = Path(__file__).parents[1] / "webapi" / "orchestration" / "reference" / "parametros.toml" +GROUPED = {"CACU-EU7": "citologia_anomala", "CACU-CONFIRMACION-CITOLOGIA": "deteccion_grados"} + + +@pytest.fixture(scope="module") +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 _measures(domain: str, manifest: Path) -> dict[str, dict]: + titles = labels(manifest) + return {d.measure_id.replace("_", "-"): measure_resource(d, *titles.get(d.metric, (d.metric, ""))) + for d in definitions_of(domain, manifest).values()} + + +@pytest.fixture(scope="module") +def measures(manifest): + """Each CaCu measure as the API serves it, by its FHIR id.""" + return _measures("cacu", manifest) + + +def reference(*keys: str): + with REFERENCE.open("rb") as f: + node = tomllib.load(f) + for key in keys: + node = node[key] + return node["valor"] + + +def figures(measure: dict) -> list[str]: + return [e["valueString"] for e in measure["extension"] if e["url"] == FIGURES] + + +def categories(measure: dict) -> dict[str, dict[str, str]]: + """The measure's declared categories, in order: code -> its parts (etiqueta, color and, if any, grupo).""" + return {part["codigo"]: part for part in ( + {p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]} + for e in measure["extension"] if e["url"] == CATEGORY_LABEL)} + + +def groups(measure: dict) -> dict[str, str]: + """The measure's category groups, in order: code -> caption.""" + return {part["codigo"]: part["etiqueta"] for part in ( + {p["url"]: p.get("valueCode") or p["valueString"] for p in e["extension"]} + for e in measure["extension"] if e["url"] == CATEGORY_GROUP)} + + +def test_each_contract_publishes_the_figures_the_page_can_draw(measures): + """Pins down: the two distributions offer the donut and the bars and the two durations their box plot; the C1 + proportions and the risk bands none, because no figure is approved for them yet. Fails if a figure is declared + that the page has no builder for, or one is dropped.""" + assert {i: figures(m) for i, m in measures.items()} == { + "CACU-EU7": ["fig_c2_donas", "fig_c2_barras"], "CACU-CONFIRMACION-CITOLOGIA": ["fig_c2_donas", "fig_c2_barras"], + "CACU-EU-TIEMPO-REPORTE": ["fig_c3r_caja"], "CACU-DIAS-TOMA-DIAGNOSTICO": ["fig_c3r_caja"], + "CACU-EU13": [], "IND1": [], "CACU-RIESGO-BANDA": []} + + +def test_the_category_captions_are_the_reference_catalogs(measures): + """Pins down: the captions, colours and order of the cytology distribution equal `cacu.catalogos.citologia` plus + `cacu.catalogos.sin_dato`, and the confirmation's grades `cacu.catalogos.biopsia`. Fails if either side is edited + without the other.""" + sin_dato = reference("cacu", "catalogos", "sin_dato") + citologia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "citologia")} + eu7 = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-EU7"]).items()} + assert eu7 == {**citologia, "SIN_DATO": (sin_dato["etiqueta"], sin_dato["color"])} + biopsia = {e["clave"]: (e["etiqueta"], e["color"]) for e in reference("cacu", "catalogos", "biopsia")} + confirmacion = {c: (p["etiqueta"], p["color"]) for c, p in categories(measures["CACU-CONFIRMACION-CITOLOGIA"]).items()} + assert list(confirmacion)[:len(biopsia)] == list(biopsia) + assert {c: confirmacion[c] for c in biopsia} == biopsia + + +@pytest.mark.parametrize("fhir_id", sorted(GROUPED)) +def test_the_anomalous_group_is_the_reference_list(measures, manifest, fhir_id): + """Pins down: a grouped composition's ANORMAL members are exactly the parameter list the grouping is defined by + (`cacu.citologia_anomala` for EU7, `cacu.deteccion_grados` for the confirmation) and the dbt variable of the same + name; the other declared categories are NO_ANORMAL, «Sin dato» its own group and «Sin biopsia aún» none. Fails if + a membership drifts from the lists the measures count with.""" + yaml = pytest.importorskip("yaml") + lista = GROUPED[fhir_id] + project = manifest.parent.parent / "dbt_project.yml" + dbt_vars = yaml.safe_load(project.read_text(encoding="utf-8"))["vars"] if project.exists() else None + parts = categories(measures[fhir_id]) + anomalous = sorted(c for c, p in parts.items() if p.get("grupo") == "ANORMAL") + assert anomalous == sorted(reference("cacu", lista)) + if dbt_vars is not None: + assert anomalous == sorted(dbt_vars[lista]) + assert all(p.get("grupo") == "NO_ANORMAL" for c, p in parts.items() + if c not in anomalous and c not in ("SIN_DATO", "SIN_BIOPSIA")) + assert parts["SIN_DATO"]["grupo"] == "SIN_DATO" + assert "grupo" not in parts.get("SIN_BIOPSIA", {}) + + +def test_the_group_captions_are_the_reference_ones(measures): + """Pins down: EU7's groups are `cacu.catalogos.resultado_anormal` plus «Sin dato», and the confirmation's + «Menor que LIEAG» / «LIEAG o más» plus its no-data category's caption, in that order. Fails if a caption drifts.""" + resultado = {e["clave"]: e["etiqueta"] for e in reference("cacu", "catalogos", "resultado_anormal")} + assert groups(measures["CACU-EU7"]) == {**resultado, "SIN_DATO": "Sin dato"} + assert groups(measures["CACU-CONFIRMACION-CITOLOGIA"]) == { + "NO_ANORMAL": "Menor que LIEAG", "ANORMAL": "LIEAG o más", "SIN_DATO": "Biopsia sin grado"} + + +def test_measures_without_groups_publish_none(manifest, measures): + """Pins down: groups are opt-in. CaCu's other measures and every CaMa and TEA measure publish neither a + `categoria-grupo` nor a `grupo` inside a category. Fails if the new extensions leak onto measures that don't + declare them (their clients see exactly what they see without groups).""" + others = {**{i: m for i, m in measures.items() if i not in GROUPED}, + **_measures("cama", manifest), **_measures("tea", manifest)} + for fhir_id, measure in others.items(): + assert not groups(measure), fhir_id + assert all("grupo" not in part for part in categories(measure).values()), fhir_id + + +@pytest.mark.parametrize("fhir_id", sorted(GROUPED)) +def test_a_grouped_measure_is_valid_fhir_r4b(measures, fhir_id): + """Pins down: the nested `grupo` and the `categoria-grupo` extensions keep the Measure valid FHIR R4B. Fails if + the extensions are shaped in a way FHIR's models reject.""" + get_fhir_model_class("Measure").model_validate(measures[fhir_id]) + + +def test_a_composite_stratum_carries_its_caption(manifest): + """Pins down: in a composition's report, a stratum value of a crossed stratifier (status by result) carries the + caption of `meta.etiquetas_estrato` as its display, and a value without one (an age group) keeps the code alone. + Fails if the captions stop reaching the report or start replacing codes.""" + definition = next(d for d in definitions_of("cacu", manifest).values() if d.measure_id == "CACU_EU7") + result = CompositionAnswer(report_id=1, categories={"NORMAL": 2, "ASC-US": 1}, stored_before=True, strata={ + "estatus_seguimiento": {"PRE_COLPOSCOPIA": {"NORMAL": 2}, "POST_COLPOSCOPIA": {"ASC-US": 1}}, + "grupo_edad": {"25-34": {"NORMAL": 2, "ASC-US": 1}}}) + question = SimpleNamespace(event_cutoff=None, knowledge_cutoff=None) + period = SimpleNamespace(inicio=date(2025, 7, 1), fin=date(2026, 1, 1)) + report = measure_report(definition, question, result, period, datetime(2026, 1, 2, tzinfo=timezone.utc)) + shown = {} + for stratifier in report["group"][0]["stratifier"][1:]: + for stratum in stratifier["stratum"]: + value = stratum["component"][0]["value"]["coding"][0] + shown[value["code"]] = value.get("display") + assert shown == {"PRE_COLPOSCOPIA": "Pre colposcopia", "POST_COLPOSCOPIA": "Post colposcopia", "25-34": None} + get_fhir_model_class("MeasureReport").model_validate(report) + + +RULE = {"sin_dato": "SIN_DATO", "etiquetas": { + "A": {"etiqueta": "A", "color": "#000000", "grupo": "G1"}, "B": {"etiqueta": "B", "color": "#000000", "grupo": "G2"}, + "APARTE": {"etiqueta": "Aparte", "color": "#000000"}, + "SIN_DATO": {"etiqueta": "Sin dato", "color": "#000000", "grupo": "SIN_DATO"}}, + "grupos": {"G1": "Uno", "G2": "Dos", "SIN_DATO": "Sin dato"}} + + +def _with(**changes) -> dict: + rule = {**RULE, "etiquetas": {k: dict(v) for k, v in RULE["etiquetas"].items()}, "grupos": dict(RULE["grupos"])} + for path, value in changes.items(): + *parents, last = path.split("__") + node = rule + for p in parents: + node = node[p] + if value is None: + node.pop(last, None) + else: + node[last] = value + return rule + + +def test_valid_groups_are_returned_in_order_and_a_category_may_stay_apart(): + """Pins down: declared and used groups come back in their declared order, and a category without `grupo` (one kept + apart) is allowed. Fails if a valid declaration is rejected or reordered.""" + assert list(category_groups("x", RULE).items()) == [("G1", "Uno"), ("G2", "Dos"), ("SIN_DATO", "Sin dato")] + + +def test_a_composition_without_groups_has_none(): + """Pins down: groups are optional; neither `grupos` nor any `grupo` means none. Fails if declaring groups becomes + mandatory (CaMa's and TEA's compositions declare none).""" + rule = {k: v for k, v in RULE.items() if k != "grupos"} + rule["etiquetas"] = {c: {k: v for k, v in s.items() if k != "grupo"} for c, s in RULE["etiquetas"].items()} + assert category_groups("x", rule) == {} + + +@pytest.mark.parametrize("rule, message", [ + (_with(grupos=None), "`grupos` is missing"), + (_with(etiquetas__A__grupo="G9"), "undeclared groups"), + (_with(grupos__G3="Tres"), "groups without categories"), + (_with(grupos__G1=" "), "non-empty caption"), + (_with(etiquetas__SIN_DATO__grupo="G1", grupos__SIN_DATO=None), "goes alone"), + (_with(etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "goes alone"), + (_with(etiquetas__SIN_DATO__grupo=None, etiquetas__B__grupo="SIN_DATO", grupos__G2=None), "no-data category's own"), +]) +def test_invalid_groups_fail_the_load(rule, message): + """Pins down: each way a declaration can't be read as a partition fails with its reason (a group named but + missing, one declared but unused, an empty caption, the no-data category mixed with others or without its own + group). Fails if one of them is accepted, because the page would draw a wrong or incomplete grouping.""" + with pytest.raises(InvalidCategoryGroups, match=message): + category_groups("x", rule) diff --git a/webapi/compositions.py b/webapi/compositions.py index 751ca0a..f8f19ae 100644 --- a/webapi/compositions.py +++ b/webapi/compositions.py @@ -99,6 +99,40 @@ class CompositionDefinition: improvement_notation = None +class InvalidCategoryGroups(ValueError): + """A composition's category groups (`categoria.grupos` and each label's `grupo`) don't hold together.""" + + +def category_groups(url: str, rule: dict) -> dict[str, str]: + """The groups of a composition's categories (`categoria.grupos`: code -> caption), checked against the labels that + name them (`categoria.etiquetas..grupo`). Optional: without either, there are none. + + A label may name no group (a category kept apart, like «Sin biopsia aún»); every group named is declared, every + declared group has a category, and the no-data category, if grouped, is alone in the group of its own code, as the + indicator page reads it. + """ + grupos = rule.get("grupos") + labels = rule.get("etiquetas", {}) + named = {code: spec["grupo"] for code, spec in labels.items() if isinstance(spec, dict) and "grupo" in spec} + if grupos is None: + if named: + raise InvalidCategoryGroups(f"{url}: categories name groups ({', '.join(sorted(named))}) but `grupos` is missing") + return {} + if not isinstance(grupos, dict) or not grupos or not all( + isinstance(code, str) and code and isinstance(caption, str) and caption.strip() for code, caption in grupos.items()): + raise InvalidCategoryGroups(f"{url}: `grupos` maps each group's code to a non-empty caption") + if unknown := sorted({g for g in named.values() if g not in grupos}): + raise InvalidCategoryGroups(f"{url}: undeclared groups {unknown}") + if unused := sorted(set(grupos) - set(named.values())): + raise InvalidCategoryGroups(f"{url}: groups without categories {unused}") + no_data = rule.get("sin_dato") + if no_data in named and (named[no_data] != no_data or [c for c, g in named.items() if g == no_data and c != no_data]): + raise InvalidCategoryGroups(f"{url}: the no-data category {no_data!r} goes alone in the group {no_data!r}") + if no_data in grupos and named.get(no_data) != no_data: + raise InvalidCategoryGroups(f"{url}: the group {no_data!r} is the no-data category's own") + return dict(grupos) + + def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: """The simple metrics of the manifest whose `meta` declares a composition, by `measure_url`.""" m = json.loads(manifest.read_text(encoding="utf-8")) @@ -112,6 +146,7 @@ def composition_definitions(manifest: Path) -> dict[str, CompositionDefinition]: model = _semantic_model_of(metric, semantic) node = models[model["depends_on"]["nodes"][0]] rule = meta["categoria"] + category_groups(meta["measure_url"], rule) # fails the manifest's load if the groups don't hold together definitions[meta["measure_url"]] = CompositionDefinition( url=meta["measure_url"], version=str(meta["version"]), metric=metric["name"], relation=node["alias"], model_checksum=node["checksum"]["checksum"], time_dimension=model["defaults"]["agg_time_dimension"], diff --git a/webapi/fhir/measures.py b/webapi/fhir/measures.py index 2981340..4bf16d5 100644 --- a/webapi/fhir/measures.py +++ b/webapi/fhir/measures.py @@ -11,7 +11,7 @@ import json from datetime import datetime, timedelta from pathlib import Path -from webapi.compositions import CompositionAnswer, CompositionDefinition +from webapi.compositions import CompositionAnswer, CompositionDefinition, category_groups from webapi.durations import OBSERVATION, DurationAnswer, DurationDefinition from webapi.fhir.common import CODE_SYSTEM, STRUCTURE, canonical, concept from webapi.metrics import EVENT_CUTOFF, HISTORY_ENTRY, KNOWLEDGE_CUTOFF, POPULATION_SYSTEM, Answer, Counts @@ -24,6 +24,7 @@ EXCLUDED = "measure-population-exclusion" FIGURES = f"{STRUCTURE}/figuras" PERIOD_TYPES = f"{STRUCTURE}/tipos-periodo" CATEGORY_LABEL = f"{STRUCTURE}/categoria" +CATEGORY_GROUP = f"{STRUCTURE}/categoria-grupo" CONTRACT = f"{STRUCTURE}/contrato" REQUIRES_VALIDATION = f"{STRUCTURE}/requiere-validacion" POPULATION_LABELS = { @@ -87,9 +88,16 @@ def measure_resource(definition, title: str, description: str) -> dict: *({"url": PERIOD_TYPES, "valueCode": t} for t in meta.get("tipos_periodo", ())), *({"url": FIGURES, "valueString": f} for f in meta.get("figuras", ()))] category = meta.get("categoria", {}) + # Optional and additive: a category's group (`grupo`) and each group's caption (`categoria-grupo`), only when the + # composition declares them; a client that doesn't know them reads the labels alone. extensions += [{"url": CATEGORY_LABEL, "extension": [ {"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": spec["etiqueta"]}, - {"url": "color", "valueString": spec["color"]}]} for code, spec in category.get("etiquetas", {}).items()] + {"url": "color", "valueString": spec["color"]}, + *([{"url": "grupo", "valueCode": spec["grupo"]}] if spec.get("grupo") else [])]} + for code, spec in category.get("etiquetas", {}).items()] + extensions += [{"url": CATEGORY_GROUP, "extension": [ + {"url": "codigo", "valueCode": code}, {"url": "etiqueta", "valueString": caption}]} + for code, caption in category_groups(definition.url, category).items()] if meta.get("requiere_validacion"): extensions.append({"url": REQUIRES_VALIDATION, "valueCode": meta["requiere_validacion"]}) resource = { @@ -141,13 +149,20 @@ def _groups(definition, result) -> list[dict]: result.total)]} labels_of = {c: s["etiqueta"] for c, s in definition.meta.get("categoria", {}).get("etiquetas", {}).items()} category = definition.category.value + # A stratum value's caption, as a proportion's strata have it (`_label`), or from `meta.etiquetas_estrato`, + # which stays out of the strata's spec so the report's key doesn't change. + spec_of = {s.name: s.spec for s in definition.strata} + captions = definition.meta.get("etiquetas_estrato", {}) + + def caption(name: str, value: str) -> str | None: + return _label(spec_of.get(name, {}), value) or captions.get(name, {}).get(value) stratifiers = [{"code": [concept(STRATIFIER_SYSTEM, category)], "stratum": [ {"value": _stratum_value(category, c, labels_of.get(c)), "population": [_count("initial-population", n)]} for c, n in sorted(result.categories.items())]}] for name, by_value in result.strata.items(): stratifiers.append({"code": [concept(STRATIFIER_SYSTEM, name), concept(STRATIFIER_SYSTEM, category)], "stratum": [{"component": [ - {"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v)}, + {"code": concept(STRATIFIER_SYSTEM, name), "value": _stratum_value(name, v, caption(name, v))}, {"code": concept(STRATIFIER_SYSTEM, category), "value": _stratum_value(category, c)}, ], "population": [_count("initial-population", n)]} for v, cs in sorted(by_value.items()) for c, n in sorted(cs.items())]})