Add CaCu PDF and spreadsheet exports
Adapted from Angel Capetillo Zavala commit 4934f99. Roboto notices are included; institutional logo authorization remains pending.
This commit is contained in:
+61
-1
@@ -55,6 +55,50 @@ CODES = { # platform code -> the current platform's
|
||||
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
|
||||
"result": "citologia_alto_grado"} # fmt: skip
|
||||
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
|
||||
# Measures with no legacy reference fixture: checked by invariants.
|
||||
NEW_MEASURES = {"CACU_VPH_GENOTIPO", "CACU_BIOPSIA_RESULTADOS", "CACU_BIOPSIA_SOLICITUD_CONFIRMACION",
|
||||
"CACU_TIEMPO_DIAGNOSTICO_CIE10", "CACU_VPP_COLPOSCOPIA", "CACU_VPP_BIOPSIA"}
|
||||
NEW_STRATA = {"screening_round", "result_initial", "result_subsequent"} # of CACU_EU7
|
||||
RESULTS = set(CODES) | set(CODES.values()) | {"ASC-US", "ASC-H", "AGC", "CIS", "adenocarcinoma"}
|
||||
|
||||
|
||||
def _count(stratum: dict, key: str, code: str = "initial-population") -> int:
|
||||
return stratum.get(key, {}).get(code, 0)
|
||||
|
||||
|
||||
def _check_eu7_rounds(populations: dict, strata: dict, where: tuple) -> None:
|
||||
"""The screening rounds partition the evaluated patients, and each round's results do too."""
|
||||
rounds = strata.get("screening_round", {})
|
||||
assert sum(c["initial-population"] for c in rounds.values()) == populations["initial-population"], where
|
||||
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
|
||||
for rnd in ("initial", "subsequent"):
|
||||
results = strata.get(f"result_{rnd}", {})
|
||||
assert sum(c["initial-population"] for c in results.values()) == _count(rounds, rnd), where
|
||||
assert set(results) <= RESULTS, where
|
||||
|
||||
|
||||
def _check_ppv(populations: dict, score, extensions: dict, strata: dict, where: tuple) -> None:
|
||||
"""A referral PPV: counts of patients, one denominator, nested numerators and groups."""
|
||||
total, den = populations["numerator"], populations["denominator"]
|
||||
assert populations["initial-population"] == den and 0 <= total <= den, where
|
||||
if den:
|
||||
assert score == pytest.approx(total / den) and 0 <= extensions["ic-bajo"] <= score <= extensions["ic-alto"] <= 1, where
|
||||
else:
|
||||
assert score is None and not extensions, where
|
||||
levels = strata.get("histology_level", {})
|
||||
if den:
|
||||
assert set(levels) == {"LIEBG+", "LIEAG+", "invasive"}, where
|
||||
assert all(c["denominator"] == den for c in levels.values()), where
|
||||
low, high, invasive = (levels[k]["numerator"] for k in ("LIEBG+", "LIEAG+", "invasive"))
|
||||
assert total == low >= high >= invasive >= 0, where
|
||||
cytology = strata.get("referral_cytology", {})
|
||||
nested = [_count(cytology, g, "denominator") for g in ("ASCUS+", "LSIL+", "HSIL+")]
|
||||
assert nested == sorted(nested, reverse=True), where
|
||||
for cell in cytology.values():
|
||||
assert 0 <= cell["numerator"] <= cell["denominator"] <= den, where
|
||||
rounds = strata.get("screening_round", {})
|
||||
assert sum(c["denominator"] for c in rounds.values()) == den, where
|
||||
assert set(rounds) <= {"initial", "subsequent", "SIN_DATO"}, where
|
||||
|
||||
|
||||
def _patients(q) -> dict[str, int]:
|
||||
@@ -109,7 +153,20 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
|
||||
# (no risk batch yet, so the risk bands are empty as they were).
|
||||
reference = json.loads((REFERENCE / "indicators.json").read_text())
|
||||
(measures,) = pages(api, "/cacu/fhir/Measure")
|
||||
published = {e["resource"]["name"] for e in measures["entry"]}
|
||||
assert published == set(reference) | NEW_MEASURES
|
||||
for measure in [e["resource"] for e in measures["entry"]]:
|
||||
if measure["name"] not in reference: # New measures have no legacy fixture.
|
||||
if measure["name"].startswith("CACU_VPP_"):
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
reports = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
assert len(reports) == len(PERIODS), measure["name"]
|
||||
for entry in reports:
|
||||
populations, score, extensions, strata = _report(entry, measure["name"])
|
||||
_check_ppv(populations, score, extensions, strata,
|
||||
(measure["name"], entry["resource"]["period"]["start"]))
|
||||
continue
|
||||
params = {"measure": measure["id"], "reporting-period": ",".join(PERIODS),
|
||||
"event-cutoff": CAPTURED_ON} # fmt: skip
|
||||
found = [e for b in pages(api, "/cacu/fhir/MeasureReport", params) for e in b["entry"]]
|
||||
@@ -118,7 +175,10 @@ def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform, tmp_path)
|
||||
for ours, theirs in zip(found, reference[name]["body"]["entry"], strict=True):
|
||||
a, b = _report(ours, name), _report(theirs, name)
|
||||
where = (name, ours["resource"]["period"]["start"])
|
||||
assert a[0] == b[0] and a[3] == b[3], where
|
||||
legacy = {k: v for k, v in a[3].items() if name != "CACU_EU7" or k not in NEW_STRATA}
|
||||
assert a[0] == b[0] and legacy == b[3], where
|
||||
if name == "CACU_EU7": # the new round breakdowns leave every legacy figure as it was
|
||||
_check_eu7_rounds(a[0], a[3], where)
|
||||
if cohort: # scores its count; the current platform gave none
|
||||
assert b[1] is None and a[1] == a[0]["initial-population"], where
|
||||
continue
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""CaCu's PDF and Excel exports: what the WebApp sends already formatted is laid out, never
|
||||
computed; limits are enforced; every cell is text (nothing becomes a formula); a long query
|
||||
runs over several pages with the institutional frame on each; absent values stay absent."""
|
||||
|
||||
import re
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from webapi import exports, pdf_report
|
||||
|
||||
COLUMNS = ["Paciente", "Edad", "Estatus", "Etapas", "Última citología", "VPH", "Biopsia",
|
||||
"Riesgo", "Riesgo cáncer", "Días a diagnóstico"] # fmt: skip
|
||||
STAGES = [
|
||||
{"state": "Registrada", "date": "2026-11-01"},
|
||||
{"state": "Desconocida"},
|
||||
{"state": "Pendiente"},
|
||||
{"state": "Ambigua"},
|
||||
{"state": "Registrada", "date": "2026-11-09", "provenance": "Inferida temporalmente"},
|
||||
]
|
||||
|
||||
|
||||
def pages(pdf: bytes) -> int:
|
||||
return len(re.findall(rb"/Type\s*/Page\b", pdf))
|
||||
|
||||
|
||||
def listing(n: int, **extra) -> exports.Document:
|
||||
rows = [[f"Paciente {i}\nCURP{i}", "40", "Precolposcopia", "x", "—", "—", "—",
|
||||
"No disponible", "0.0 %", "—"] for i in range(n)] # fmt: skip
|
||||
return exports.Document(
|
||||
title="Resultados de seguimiento",
|
||||
parameters=[["Fecha de corte", "2026-11-22"]],
|
||||
columns=COLUMNS,
|
||||
rows=rows,
|
||||
row_stages=[STAGES] * n,
|
||||
**extra,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
app = FastAPI()
|
||||
app.include_router(exports.router)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
def test_the_assets_ship_with_the_package():
|
||||
for name in ("isssteleon-logo.png", "fonts/Roboto-Regular.ttf", "fonts/Roboto-Medium.ttf",
|
||||
"fonts/Roboto-Italic.ttf", "fonts/Roboto-MediumItalic.ttf",
|
||||
"fonts/LICENSE-Roboto-OFL.txt"): # fmt: skip
|
||||
assert (pdf_report.ASSETS / name).is_file(), name
|
||||
|
||||
|
||||
def test_the_limits_are_published(client):
|
||||
assert client.get("/cacu/exports/capabilities").json() == {
|
||||
"xlsx_limit": 5000, "pdf_limit": 1000, "version": 1} # fmt: skip
|
||||
|
||||
|
||||
def test_excel_cells_are_text_so_nothing_runs_as_a_formula():
|
||||
doc = exports.Document(title="x", parameters=[["Filtro", "=1+1"]], columns=["=2+2"],
|
||||
rows=[["=1+1"], ["+cmd"], ["@SUM(A1)"]]) # fmt: skip
|
||||
book = load_workbook(BytesIO(exports.export("xlsx", doc).body))
|
||||
assert book.sheetnames == ["Resultados", "Parámetros"]
|
||||
cells = [book["Resultados"]["A1"], book["Resultados"]["A2"], book["Resultados"]["A4"],
|
||||
book["Parámetros"]["B2"]] # fmt: skip
|
||||
assert {c.data_type for c in cells} == {"s"}
|
||||
assert book["Resultados"]["A2"].value == "=1+1"
|
||||
|
||||
|
||||
def test_excel_keeps_every_row_of_the_query_up_to_its_limit():
|
||||
doc = listing(5000).model_copy(update={"row_stages": []})
|
||||
sheet = load_workbook(BytesIO(exports.export("xlsx", doc).body))["Resultados"]
|
||||
assert sheet.max_row == 5001 # the header and every patient
|
||||
with pytest.raises(ValueError): # the model itself refuses more
|
||||
exports.Document.model_validate({**doc.model_dump(), "rows": doc.rows + [doc.rows[0]]})
|
||||
|
||||
|
||||
def test_pdf_stops_at_a_thousand_records_and_columns_must_agree():
|
||||
too_many = exports.Document(title="x", parameters=[], columns=["a"], rows=[["x"]] * 1001)
|
||||
with pytest.raises(exports.HTTPException) as caught:
|
||||
exports.export("pdf", too_many)
|
||||
assert caught.value.status_code == 422
|
||||
with pytest.raises(exports.HTTPException):
|
||||
exports.export("xlsx", exports.Document(title="x", parameters=[], columns=["a"],
|
||||
rows=[["x", "y"]])) # fmt: skip
|
||||
with pytest.raises(exports.HTTPException) as unknown:
|
||||
exports.export("docx", too_many)
|
||||
assert unknown.value.status_code == 404
|
||||
|
||||
|
||||
def test_a_long_listing_runs_over_several_pages_and_keeps_its_rows_and_stages():
|
||||
body = exports.export("pdf", listing(120)).body
|
||||
assert body.startswith(b"%PDF")
|
||||
assert pages(body) > 4
|
||||
short = exports.export("pdf", listing(2)).body
|
||||
assert pages(short) < pages(body)
|
||||
with pytest.raises(exports.HTTPException): # one stage line per row, or none
|
||||
exports.export("pdf", listing(5).model_copy(update={"row_stages": [STAGES] * 3}))
|
||||
|
||||
|
||||
def test_a_listing_with_nothing_found_and_with_absent_values_still_renders():
|
||||
empty = exports.Document(title="Resultados de seguimiento", parameters=[], columns=COLUMNS,
|
||||
rows=[]) # fmt: skip
|
||||
assert exports.export("pdf", empty).body.startswith(b"%PDF")
|
||||
blank = listing(3).model_copy(update={"row_stages": [[{}] * 5] * 3})
|
||||
assert exports.export("pdf", blank).body.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_the_record_pdf_draws_extreme_and_absent_risks():
|
||||
scales = [
|
||||
{"label": "a", "value": v, "outcome": "Cáncer", "model": "M", "horizon": "Inmediato"}
|
||||
for v in (0, 0.02, 0.5, 0.98, 1)
|
||||
]
|
||||
scales.append({"label": "Riesgo a 5 años: No disponible"})
|
||||
doc = exports.Document(
|
||||
title="Ficha individual",
|
||||
parameters=[],
|
||||
columns=["Sección", "Información"],
|
||||
rows=[
|
||||
["Identificador", "1"],
|
||||
["Historial", "2026-01-01 · Diagnóstico · " + "texto " * 300],
|
||||
],
|
||||
timeline=[{"state": "Registrada", "label": "Toma de muestra", "date": "2026-01-01"}] * 5,
|
||||
risk_scales=scales,
|
||||
)
|
||||
assert exports.export("pdf", doc).body.startswith(b"%PDF")
|
||||
|
||||
|
||||
def test_the_http_route_returns_the_documents(client):
|
||||
payload = listing(3).model_dump()
|
||||
pdf = client.post("/cacu/exports/pdf", json=payload)
|
||||
assert pdf.status_code == 200 and pdf.headers["content-type"] == "application/pdf"
|
||||
xlsx = client.post("/cacu/exports/xlsx", json=payload)
|
||||
assert xlsx.status_code == 200 and "spreadsheetml" in xlsx.headers["content-type"]
|
||||
assert client.post("/cacu/exports/csv", json=payload).status_code == 404
|
||||
assert client.post("/cacu/exports/pdf", json={**payload, "columns": []}).status_code == 422
|
||||
Reference in New Issue
Block a user