diff --git a/pyproject.toml b/pyproject.toml index 51cbb92..2a4976e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,8 @@ dependencies = [ "fastapi-users[sqlalchemy]>=15", "aiosqlite>=0.20", "asyncpg>=0.30", + "fpdf2>=2.8", + "openpyxl>=3.1.5", ] [build-system] diff --git a/tests/test_cacu.py b/tests/test_cacu.py index 722df48..0e0f733 100644 --- a/tests/test_cacu.py +++ b/tests/test_cacu.py @@ -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 diff --git a/tests/test_cacu_exports.py b/tests/test_cacu_exports.py new file mode 100644 index 0000000..184234b --- /dev/null +++ b/tests/test_cacu_exports.py @@ -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 diff --git a/webapi/assets/PROCEDENCIA.txt b/webapi/assets/PROCEDENCIA.txt new file mode 100644 index 0000000..5537a6c --- /dev/null +++ b/webapi/assets/PROCEDENCIA.txt @@ -0,0 +1,14 @@ +Recursos gráficos de las exportaciones PDF (webapi/pdf_report.py) + +isssteleon-logo.png + Logotipo institucional. Idéntico byte a byte (SHA-256 3ff77526...da758) al de + WebApp/public/assets/branding/isssteleon-logo.png. Pendiente: confirmar con ISSSTELEON + que puede incrustarse en documentos exportados. + +fonts/Roboto-Regular.ttf, Roboto-Medium.ttf, Roboto-Italic.ttf, Roboto-MediumItalic.ttf + Roboto 3.016, The Roboto Project Authors (https://github.com/googlefonts/roboto-classic), + SIL Open Font License 1.1 (texto en fonts/LICENSE-Roboto-OFL.txt; el aviso de derechos y de + licencia va también dentro de cada archivo). La licencia permite incrustar y redistribuir + las fuentes con el programa siempre que se conserve el aviso. Pendiente: confirmar la + procedencia exacta de descarga de estos archivos (no consta en el historial) y conservar este + aviso en la entrega, que elimina documentos. diff --git a/webapi/assets/fonts/LICENSE-Roboto-OFL.txt b/webapi/assets/fonts/LICENSE-Roboto-OFL.txt new file mode 100644 index 0000000..e96f4bc --- /dev/null +++ b/webapi/assets/fonts/LICENSE-Roboto-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic) Roboto-Italic[wdth,wght].ttf: Copyright 2011 The Roboto Project Authors (https://github.com/googlefonts/roboto-classic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/webapi/assets/fonts/Roboto-Italic.ttf b/webapi/assets/fonts/Roboto-Italic.ttf new file mode 100644 index 0000000..8eccb95 Binary files /dev/null and b/webapi/assets/fonts/Roboto-Italic.ttf differ diff --git a/webapi/assets/fonts/Roboto-Medium.ttf b/webapi/assets/fonts/Roboto-Medium.ttf new file mode 100644 index 0000000..a2b482f Binary files /dev/null and b/webapi/assets/fonts/Roboto-Medium.ttf differ diff --git a/webapi/assets/fonts/Roboto-MediumItalic.ttf b/webapi/assets/fonts/Roboto-MediumItalic.ttf new file mode 100644 index 0000000..f17b696 Binary files /dev/null and b/webapi/assets/fonts/Roboto-MediumItalic.ttf differ diff --git a/webapi/assets/fonts/Roboto-Regular.ttf b/webapi/assets/fonts/Roboto-Regular.ttf new file mode 100644 index 0000000..648528d Binary files /dev/null and b/webapi/assets/fonts/Roboto-Regular.ttf differ diff --git a/webapi/assets/isssteleon-logo.png b/webapi/assets/isssteleon-logo.png new file mode 100644 index 0000000..df4c1f9 Binary files /dev/null and b/webapi/assets/isssteleon-logo.png differ diff --git a/webapi/exports.py b/webapi/exports.py new file mode 100644 index 0000000..e88677d --- /dev/null +++ b/webapi/exports.py @@ -0,0 +1,90 @@ +"""Local document rendering of explicitly selected display fields.""" + +from io import BytesIO + +from fastapi import APIRouter, HTTPException +from fastapi.responses import Response +from openpyxl import Workbook +from openpyxl.styles import Font, PatternFill +from pydantic import BaseModel, Field + +from webapi.pdf_report import TooLong, render_list, render_record + +router = APIRouter(prefix="/cacu/exports", tags=["exports"]) + + +class Document(BaseModel): + title: str = Field(max_length=150) + parameters: list[list[str]] = Field(max_length=30) + columns: list[str] = Field(min_length=1, max_length=12) + rows: list[list[str]] = Field(max_length=5000) + timeline: list[dict[str, str]] = Field(default_factory=list, max_length=5) + row_stages: list[list[dict[str, str]]] = Field(default_factory=list, max_length=5000) + risk_scales: list[dict] = Field(default_factory=list, max_length=40) + + +@router.get("/capabilities") +def capabilities(): + return {"xlsx_limit": 5000, "pdf_limit": 1000, "version": 1} + + +def literal(cell, value): + cell.value = str(value) + cell.data_type = "s" + + +@router.post("/{kind}") +def export(kind: str, doc: Document): + if kind not in ("xlsx", "pdf"): + raise HTTPException(404, "Unsupported format") + if kind == "pdf" and len(doc.rows) > 1000: + raise HTTPException(422, "PDF limitado a 1000 registros") + if any(len(row) != len(doc.columns) for row in doc.rows): + raise HTTPException(422, "Número de columnas inconsistente") + if any(len(str(v)) > 4000 for row in doc.rows for v in row): + raise HTTPException(422, "Texto demasiado largo") + if kind == "xlsx": + wb = Workbook() + ws = wb.active + ws.title = "Resultados" + ws.append([""] * len(doc.columns)) + for c, value in zip(ws[1], doc.columns, strict=True): + literal(c, value) + c.font = Font(bold=True, color="FFFFFF") + c.fill = PatternFill("solid", fgColor="17324D") + for row in doc.rows: + ws.append([""] * len(doc.columns)) + for c, value in zip(ws[ws.max_row], row, strict=True): + literal(c, value) + ws.freeze_panes = "A2" + ws.auto_filter.ref = ws.dimensions + for col in ws.columns: + ws.column_dimensions[col[0].column_letter].width = min( + 48, max(12, max(len(str(c.value or "")) for c in col) + 2) + ) + meta = wb.create_sheet("Parámetros") + meta.append(["Parámetro", "Valor"]) + for pair in doc.parameters: + meta.append(["", ""]) + for c, value in zip(meta[meta.max_row], pair[:2], strict=False): + literal(c, value) + meta.column_dimensions["A"].width = 28 + meta.column_dimensions["B"].width = 60 + out = BytesIO() + wb.save(out) + return Response( + out.getvalue(), + media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + headers={"Content-Disposition": 'attachment; filename="cacu.xlsx"'}, + ) + try: + content = ( + render_record(doc) if doc.columns == ["Sección", "Información"] else render_list(doc) + ) + except TooLong as error: + raise HTTPException(422, str(error)) from error + return Response( + content, + media_type="application/pdf", + headers={"Content-Disposition": 'attachment; filename="cacu.pdf"'}, + ) diff --git a/webapi/pdf_report.py b/webapi/pdf_report.py new file mode 100644 index 0000000..14d1639 --- /dev/null +++ b/webapi/pdf_report.py @@ -0,0 +1,629 @@ +"""Institutional PDF layout for the CaCu exports. + +Layout only: every value arrives already formatted by the WebApp, and nothing here computes, +infers or reinterprets a clinical result. A missing value is shown as such, never as zero. +""" + +import re +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +from fpdf import FPDF + +ASSETS = Path(__file__).parent / "assets" +INK, ACCENT, MUTED, RULE, BAND = ( + (8, 24, 57), + (168, 194, 67), + (122, 122, 122), + (227, 231, 223), + (240, 243, 232), +) +GREEN, BLUE, CRIMSON, SLATE = (56, 123, 102), (66, 105, 160), (168, 68, 96), (102, 123, 138) +CONFIDENTIAL = "Confidencial · uso interno" +MISSING = "No disponible" +STAGE_LABELS = [ + "Toma de muestra", + "Resultado de citología", + "Colposcopia", + "Reporte de biopsia", + "Diagnóstico", +] +MONTHS = ["ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"] +DATE = re.compile(r"^\d{4}-\d{2}-\d{2}$") +SEGMENTS = ((66, 167, 126), (168, 194, 67), (223, 134, 64), (194, 66, 105)) +MARGIN, TOP, BOTTOM = 12.7, 27, 17 +LINE = {"main": 3.5, "bold": 3.5, "sub": 3.0, "missing": 3.5} + + +class TooLong(ValueError): + pass + + +def stage_kind(stage: dict) -> str: + """Visual class of a stage; provenance and state come from the WebApp unchanged.""" + if stage.get("provenance") == "Inferida temporalmente": + return "inferred" + return {"Registrada": "registered", "Pendiente": "pending", "Ambigua": "ambiguous"}.get( + stage.get("state", ""), "unknown" + ) + + +def valid_probability(value) -> bool: + return isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= 1 + + +def generated_label() -> str: + now = datetime.now(ZoneInfo("America/Mexico_City")) + return f"Generado: {now.day} {MONTHS[now.month - 1]} {now.year}, {now:%H:%M} (hora de la Ciudad de México)" + + +class Report(FPDF): + def __init__(self, orientation: str): + super().__init__(orientation=orientation, unit="mm", format="Letter") + self.set_margins(MARGIN, TOP, MARGIN) + self.set_auto_page_break(False) + self.alias_nb_pages("{nb}") + for style, file in ( + ("", "Roboto-Regular"), + ("B", "Roboto-Medium"), + ("I", "Roboto-Italic"), + ("BI", "Roboto-MediumItalic"), + ): + self.add_font("Roboto", style, str(ASSETS / "fonts" / f"{file}.ttf")) + self.set_author("ISSSTELEON") + self.set_creator("ISSSTELEON") + self.generated = generated_label() + self.width = self.w - 2 * MARGIN + self.on_page: list = [] + + # ---- frame ------------------------------------------------------------------------- + def header(self): + self.image(str(ASSETS / "isssteleon-logo.png"), x=MARGIN, y=7, w=38) + self.set_font("Roboto", "", 13) + self.set_text_color(*INK) + self.set_xy(MARGIN, 9.5) + self.cell(self.width, 7, "Cáncer cervicouterino", align="C") + self.set_draw_color(*ACCENT) + self.set_line_width(0.4) + self.line(MARGIN, 21.5, self.w - MARGIN, 21.5) + self.set_line_width(0.2) + self.set_xy(MARGIN, TOP) + + def footer(self): + self.set_y(-12) + self.set_font("Roboto", "", 7) + self.set_text_color(*MUTED) + third = self.width / 3 + self.cell(third, 4, self.generated) + self.cell(third, 4, CONFIDENTIAL, align="C") + self.cell(third, 4, f"Página {self.page_no()} de {{nb}}", align="R") + self.set_text_color(*INK) + + @property + def limit(self) -> float: + return self.h - BOTTOM + + def new_page(self): + self.add_page() + for hook in self.on_page: + hook() + + def ensure(self, height: float): + if self.get_y() + height > self.limit: + self.new_page() + + # ---- text -------------------------------------------------------------------------- + def font_for(self, kind: str): + if kind == "bold": + self.set_font("Roboto", "B", 7.5) + self.set_text_color(*INK) + elif kind == "sub": + self.set_font("Roboto", "", 6) + self.set_text_color(*MUTED) + elif kind == "missing": + self.set_font("Roboto", "I", 7) + self.set_text_color(*MUTED) + else: + self.set_font("Roboto", "", 7.5) + self.set_text_color(*INK) + + def wrap(self, kind: str, text: str, width: float) -> list[str]: + self.font_for(kind) + return [ + ln for ln in self.multi_cell(width, LINE[kind], text, dry_run=True, output="LINES") + ] or [""] + + def heading(self, text: str, size: float = 15, gap: float = 1.5): + self.ensure(size * 0.5 + 12) + self.set_font("Roboto", "B", size) + self.set_text_color(*INK) + self.set_x(MARGIN) + self.cell(self.width, size * 0.5 + 1, text, new_x="LMARGIN", new_y="NEXT") + self.ln(gap) + + def note(self, text: str, gap: float = 1.5): + self.set_x(MARGIN) + self.font_for("sub") + self.multi_cell(self.width, 3.2, text, new_x="LMARGIN", new_y="NEXT") + self.ln(gap) + + # ---- cells ------------------------------------------------------------------------- + def measure(self, pieces: list, width: float): + """Wrap a cell's pieces; returns the lines to draw and the height they need.""" + items, height = [], 0.0 + for kind, content in pieces: + if kind == "nodes": + items.append((kind, content)) + height += 9.5 + continue + for ln in self.wrap(kind, content, width - 3): + items.append((kind, ln)) + height += LINE[kind] + return items, height + + def draw_items(self, x: float, y: float, width: float, items: list): + for kind, content in items: + if kind == "nodes": + self.stage_nodes(x + 2, y, content) + y += 9.5 + continue + self.font_for(kind) + self.set_xy(x + 1.5, y) + self.cell(width - 3, LINE[kind], content) + y += LINE[kind] + + def stage_nodes(self, x: float, y: float, stages: list, step: float = 6.2, size: float = 3.4): + """Five connected nodes: order, not a time scale; fill and border encode the state.""" + cy = y + 1.2 + size / 2 + self.set_draw_color(*SLATE) + self.set_line_width(0.2) + self.line(x + size / 2, cy, x + 4 * step + size / 2, cy) + for i, stage in enumerate(stages): + self.stage_node(x + i * step, y + 1.2, size, stage_kind(stage)) + self.font_for("sub") + self.set_xy(x + i * step - 1, y + 1.2 + size + 0.3) + self.cell(size + 2, 2.6, str(i + 1), align="C") + + def stage_node(self, x: float, y: float, size: float, kind: str): + pen, fill = { + "registered": (GREEN, GREEN), + "inferred": (BLUE, BLUE), + "pending": (SLATE, (255, 241, 201)), + "ambiguous": (CRIMSON, (255, 255, 255)), + }.get(kind, (SLATE, (255, 255, 255))) + self.set_draw_color(*pen) + self.set_fill_color(*fill) + self.set_line_width(0.35) + if kind == "unknown": + self.set_dash_pattern(dash=0.5, gap=0.4) + self.ellipse(x, y, size, size, style="DF") + self.set_dash_pattern() + if kind in ( + "inferred", + "ambiguous", + ): # a second ring: the "double border" of the WebApp nodes + self.set_draw_color(*((255, 255, 255) if kind == "inferred" else pen)) + self.set_line_width(0.2) + self.ellipse(x + 0.7, y + 0.7, size - 1.4, size - 1.4, style="D") + self.set_line_width(0.2) + + def legend(self): + """Node key shared by every page of a report that draws stage nodes.""" + self.ensure(12) + y = self.get_y() + x = MARGIN + self.font_for("sub") + for kind, label in ( + ("registered", "Registrada"), + ("inferred", "Inferida temporalmente"), + ("pending", "Pendiente"), + ("ambiguous", "Ambigua"), + ("unknown", "Desconocida"), + ): + self.stage_node(x, y + 0.4, 3, kind) + self.set_xy(x + 4, y) + width = self.get_string_width(label) + 3 + self.cell(width, 3.8, label) + x += 4 + width + 3 + text = "Etapas: 1 Toma · 2 Citología · 3 Colposcopia · 4 Biopsia · 5 Diagnóstico (orden, no escala de tiempo)" + if x + 2 + self.get_string_width(text) > self.w - MARGIN: + x, y = MARGIN - 2, y + 4.5 + self.set_xy(x + 2, y) + self.cell(0, 3.8, text) + self.set_xy(MARGIN, y + 6) + + # ---- tables ------------------------------------------------------------------------ + def table( + self, + widths: list[float], + header: list[str], + rows: list[list[list]], + limit: float | None = None, + after_break=None, + ): + """Header on every page, alternating soft bands. `rows` holds one piece list per cell.""" + limit = limit or (self.h - TOP - BOTTOM - 14) + head = [[("bold", text)] for text in header] + + def draw_head(): + items = [self.measure(cell, w) for cell, w in zip(head, widths, strict=True)] + height = max(7.0, max(h for _, h in items) + 3) + x, y = MARGIN, self.get_y() + self.set_fill_color(*ACCENT) + self.rect(x, y, sum(widths), height, style="F") + for (cell_items, _), w in zip(items, widths, strict=True): + self.draw_items(x, y + 1.5, w, cell_items) + x += w + self.set_xy(MARGIN, y + height) + + def restart(): + self.new_page() + if after_break: + after_break() + draw_head() + + self.ensure(7 + 22) + draw_head() + for index, row in enumerate(rows): + items = [self.measure(cell, w) for cell, w in zip(row, widths, strict=True)] + height = max(7.0, max(h for _, h in items) + 3) + if height > limit: + raise TooLong("Una celda es demasiado extensa para el PDF") + if self.get_y() + height > self.limit: + restart() + y, x = self.get_y(), MARGIN + if index % 2 == 1: + self.set_fill_color(*BAND) + self.rect(x, y, sum(widths), height, style="F") + for (cell_items, _), w in zip(items, widths, strict=True): + self.draw_items(x, y + 1.5, w, cell_items) + x += w + self.set_draw_color(*RULE) + self.line(MARGIN, y + height, MARGIN + sum(widths), y + height) + self.set_xy(MARGIN, y + height) + self.ln(2) + + def pairs(self, entries: list[list[str]], per_row: int = 2, key_width: float = 34): + """Label/value grid with hairlines; `per_row` pairs share one line.""" + slot = self.width / per_row + for start in range(0, len(entries), per_row): + chunk = entries[start : start + per_row] + cells = [] + for pair in chunk: + label, value = (pair + [""])[:2] + cells.append( + ( + self.measure([("bold", label)], key_width), + self.measure(styled(value), slot - key_width), + ) + ) + height = max(max(a[1], b[1]) for a, b in cells) + 2.6 + self.ensure(height) + y = self.get_y() + for i, (key, val) in enumerate(cells): + self.draw_items(MARGIN + i * slot, y + 1.3, key_width, key[0]) + self.draw_items(MARGIN + i * slot + key_width, y + 1.3, slot - key_width, val[0]) + self.set_draw_color(*RULE) + self.line(MARGIN, y + height, MARGIN + self.width, y + height) + self.set_xy(MARGIN, y + height) + self.ln(2) + + +def styled(value: str) -> list: + """Plain text, or the discreet "no disponible" style for an absent value.""" + value = (value or "").strip() + return [("missing", MISSING)] if value in ("", "—", MISSING) else [("main", value)] + + +def two_line(value: str, labels: tuple[str, str] = ("", "")) -> list: + """`date · result` becomes the result in the main text and the date underneath.""" + value = (value or "").strip() + if value in ("", "—", MISSING): + return styled(value) + head, sep, tail = value.partition(" · ") + if sep and DATE.match(head): + return [("main", tail.strip() or MISSING), ("sub", f"{labels[0]}{head}")] + return [("main", value)] + + +def paragraph_cells(value: str) -> list: + parts = [p for p in (value or "").split("\n")] + if not any(p.strip() for p in parts): + return styled("") + return [("main", parts[0])] + [("sub", p) for p in parts[1:] if p.strip()] + + +# ---- list report ---------------------------------------------------------------------------- +def render_list(doc) -> bytes: + pdf = Report("L") + pdf.set_title(doc.title) + pdf.add_page() + pdf.heading(doc.title) + pdf.pairs(doc.parameters, per_row=2, key_width=36) + n = len(doc.columns) + weights = [1.5, 0.5, 1.1, 1.5, 1.5, 0.85, 1.3, 0.85, 0.85, 1.0] if n == 10 else [1] * n + widths = [pdf.width * w / sum(weights) for w in weights] + nodes = bool(doc.row_stages) and n == 10 + if doc.row_stages and len(doc.row_stages) != len(doc.rows): + raise TooLong("Número de etapas inconsistente") + pdf.heading("Pacientes", size=11, gap=1) + if nodes: + pdf.legend() + pdf.on_page.append(lambda: pdf.legend()) + rows = [] + for index, row in enumerate(doc.rows): + cells = [] + for col, value in enumerate(row): + if n != 10: + cells.append(paragraph_cells(value)) + elif col == 0: + lines = [p for p in value.split("\n") if p.strip()] + cells.append( + ([("bold", lines[0])] + [("sub", p) for p in lines[1:]]) + if lines + else styled("") + ) + elif col == 3 and nodes: + cells.append([("nodes", doc.row_stages[index])]) + elif col == 4 or col == 6: + cells.append(two_line(value, ("Fecha ", ""))) + elif col == 5: + m = re.match(r"^(.*?)\s*\(([^)]*)\)$", value.strip()) + cells.append( + [("main", m.group(1)), ("sub", f"Genotipos {m.group(2)}")] + if m and m.group(1) + else styled(value) + ) + else: + cells.append(paragraph_cells(value) if col == 3 else styled(value)) + rows.append(cells) + if rows: + pdf.table(widths, doc.columns, rows) + else: + pdf.font_for("missing") + pdf.cell( + 0, 6, "No hay registros para los filtros aplicados.", new_x="LMARGIN", new_y="NEXT" + ) + if nodes and rows: + pdf.on_page.clear() + pdf.new_page() + pdf.heading("Detalle de etapas por paciente", size=11, gap=1) + pdf.note( + "Estado y fecha de cada etapa tal como se registró. «Inferida temporalmente» es una asociación por cercanía de fechas; " + "no constituye un vínculo clínico confirmado. «Desconocida» indica que no hay dato; no se infiere ninguna fecha." + ) + w0 = 44.0 + w = (pdf.width - w0) / 5 + detail = [] + for row, stages in zip(doc.rows, doc.row_stages, strict=True): + first = (row[0].split("\n") or [""])[0] + line = [[("bold", first)]] + for stage in stages: + kind = stage_kind(stage) + state = stage.get("state") or "Desconocida" + if kind == "unknown": + line.append([("missing", state)]) + continue + piece = [("bold" if kind in ("registered", "inferred") else "main", state)] + piece.append( + ("sub", f"Fecha {stage['date']}") if stage.get("date") else ("sub", "Sin fecha") + ) + if kind == "inferred": + piece.append(("sub", "Inferida temporalmente")) + line.append(piece) + detail.append(line) + pdf.table( + [w0] + [w] * 5, + ["Paciente"] + [f"{i + 1}. {s}" for i, s in enumerate(STAGE_LABELS)], + detail, + ) + pdf.note( + "«No disponible» indica dato no registrado, no ausencia clínica. El reporte incluye la consulta completa, " + "independientemente de la paginación visible en pantalla." + ) + return bytes(pdf.output()) + + +# ---- individual record ---------------------------------------------------------------------- +IDENTIFICATION = [ + "Identificador", + "Paciente", + "CURP", + "Expedientes", + "Nacimiento", + "Edad al corte", + "Estatus", +] + + +def risk_scale(pdf: Report, x: float, y: float, width: float, scale: dict) -> float: + """One segmented scale: segments are descriptive quarters, not clinical thresholds.""" + value = scale.get("value") + available = valid_probability(value) + title = scale.get("outcome") + pdf.set_xy(x, y) + if title: + pdf.font_for("bold") + pdf.cell(width, 3.6, f"{title} · {scale.get('model', '')}".strip(" ·")) + pdf.set_xy(x, y + 3.6) + pdf.font_for("sub") + pdf.cell(width, 3, f"Horizonte: {scale.get('horizon', '')}") + y += 7.5 + else: + pdf.font_for("main") + pdf.multi_cell(width, 3.5, str(scale.get("label", "Riesgo")), new_x="LMARGIN", new_y="NEXT") + y = pdf.get_y() + 0.5 + bar_y, bar_x, bar_w = y + 5, x + 1, width - 2 + for i, color in enumerate(SEGMENTS if available else ((217, 223, 226),) * 4): + pdf.set_fill_color(*color) + pdf.rect(bar_x + i * bar_w / 4, bar_y, bar_w / 4 - 0.4, 3.6, style="F") + if available: + mx = bar_x + value * bar_w + pdf.set_draw_color(*INK) + pdf.set_line_width(0.6) + pdf.line(mx, bar_y - 1.2, mx, bar_y + 4.8) + pdf.set_line_width(0.2) + pdf.set_font("Roboto", "B", 8) + pdf.set_text_color(*INK) + pdf.set_xy(max(bar_x, min(mx - 9, bar_x + bar_w - 18)), bar_y - 5.2) + pdf.cell(18, 4, f"{value * 100:.2f} %", align="C") + else: + pdf.font_for("missing") + pdf.set_xy(bar_x, bar_y - 4.4) + pdf.cell(40, 4, MISSING) + pdf.font_for("sub") + for i in range(5): + pdf.set_xy(bar_x + i * bar_w / 4 - 6, bar_y + 4.2) + pdf.cell(12, 2.8, f"{i * 25} %", align="C") + low, high = scale.get("low"), scale.get("high") + end = bar_y + 7.5 + if available and valid_probability(low) and valid_probability(high) and low <= high: + pdf.set_draw_color(*BLUE) + pdf.set_line_width(0.5) + lx, hx = bar_x + low * bar_w, bar_x + high * bar_w + pdf.line(lx, end + 1.2, hx, end + 1.2) + pdf.line(lx, end + 0.2, lx, end + 2.2) + pdf.line(hx, end + 0.2, hx, end + 2.2) + pdf.set_line_width(0.2) + pdf.set_xy(bar_x, end + 2.4) + pdf.cell(bar_w, 3, f"IC 95 %: {low * 100:.2f}–{high * 100:.2f} %") + end += 5.4 + return end + 2.5 + + +def render_record(doc) -> bytes: + pdf = Report("P") + pdf.set_title(doc.title) + pdf.add_page() + pdf.heading(doc.title) + pdf.pairs(doc.parameters, per_row=1, key_width=58) + groups: dict[str, list[list[str]]] = { + k: [] for k in ("id", "stage", "history", "tests", "risk", "other") + } + note = "" + for key, value in ((r[0], r[1]) for r in doc.rows): + if key in IDENTIFICATION: + groups["id"].append([key, value]) + elif key == "Etapa": + groups["stage"].append([key, value]) + elif key == "Etapas": + note = value + elif key == "Historial": + groups["history"].append([key, value]) + elif key == "Pruebas": + groups["tests"].append([key, value]) + elif key == "Riesgo": + groups["risk"].append([key, value]) + else: + groups["other"].append([key, value]) + if groups["id"]: + pdf.heading("Datos de identificación", size=11, gap=1) + pdf.pairs(groups["id"], per_row=2, key_width=30) + if doc.timeline: + pdf.heading("Etapas del tamizaje", size=11, gap=1) + pdf.legend() + record_stages(pdf, doc.timeline) + if not all(t.get("label") for t in doc.timeline): + pdf.pairs(groups["stage"], per_row=1, key_width=30) + if note: + pdf.note(note) + if groups["history"]: + pdf.heading("Historial médico", size=11, gap=1) + rows = [] + for _, text in groups["history"]: + parts = text.split(" · ", 2) if text.count(" · ") >= 2 else ["", "", text] + rows.append([styled(parts[0]), styled(parts[1]), styled(parts[2])]) + pdf.table([24, 32, pdf.width - 56], ["Fecha", "Tipo", "Descripción"], rows) + if groups["tests"]: + pdf.heading("Pruebas y resultados", size=11, gap=1) + rows = [] + for _, text in groups["tests"]: + parts = text.split(" · ", 3) + if len(parts) < 4: + parts = (parts + [""] * 4)[:4] + rows.append( + [ + styled(parts[0]), + styled(parts[1]), + styled(parts[2]), + [("main", ln) for ln in parts[3].split(" · ")] + if parts[3].strip() + else styled(""), + ] + ) + pdf.table( + [22, 40, 30, pdf.width - 92], ["Fecha", "Prueba", "Reportado", "Resultados"], rows + ) + if doc.risk_scales or groups["risk"]: + pdf.heading("Riesgos", size=11, gap=1) + pdf.note( + "Los segmentos son divisiones numéricas descriptivas; no constituyen umbrales clínicos. " + "Un riesgo ausente se muestra como «No disponible», sin marcador." + ) + slot = pdf.width / 2 + scales = doc.risk_scales + for i in range(0, len(scales), 2): + pdf.ensure(34) + y = pdf.get_y() + ends = [ + risk_scale(pdf, MARGIN + j * slot + (3 if j else 0), y, slot - 3, s) + for j, s in enumerate(scales[i : i + 2]) + ] + pdf.set_y(max(ends)) + if not scales: + pdf.table( + [30, pdf.width - 30], + ["Tipo", "Información"], + [[styled(k), styled(v)] for k, v in groups["risk"]], + ) + if groups["other"]: + pdf.heading("Otros datos", size=11, gap=1) + pdf.pairs(groups["other"], per_row=1, key_width=40) + pdf.note( + "La ficha resume la información disponible; los datos ausentes no se interpretan como ausencia clínica y las " + "asociaciones temporales inferidas no constituyen vínculos clínicos confirmados." + ) + return bytes(pdf.output()) + + +def record_stages(pdf: Report, timeline: list[dict]): + count = len(timeline) + pdf.ensure(48) + y = pdf.get_y() + 1 + bottom = y + slot = pdf.width / count + size = 6 + cy = y + size / 2 + pdf.set_draw_color(*SLATE) + pdf.set_line_width(0.25) + pdf.line(MARGIN + slot / 2, cy, MARGIN + slot * (count - 0.5), cy) + for i, stage in enumerate(timeline): + cx = MARGIN + slot * (i + 0.5) + pdf.stage_node(cx - size / 2, y, size, stage_kind(stage)) + lines = [ + ( + "bold", + stage.get("label") or STAGE_LABELS[i] + if i < len(STAGE_LABELS) + else f"Etapa {i + 1}", + ) + ] + state = stage.get("state") or "Desconocida" + lines.append(("missing" if stage_kind(stage) == "unknown" else "main", state)) + if stage.get("provenance"): + lines.append(("sub", stage["provenance"])) + lines.append( + ("sub", f"Fecha {stage['date']}") if stage.get("date") else ("sub", "Sin fecha") + ) + for key, text in (("prev", "Desde anterior"), ("start", "Desde toma")): + if stage.get(key): + lines.append(("sub", f"{text}: {stage[key]}")) + yy = y + size + 2 + for kind, text in [(k, ln) for k, t in lines for ln in pdf.wrap(k, t, slot - 3)]: + pdf.font_for(kind) + pdf.set_xy(MARGIN + slot * i + 1.5, yy) + pdf.cell(slot - 3, LINE[kind], text, align="C") + yy += LINE[kind] + bottom = max(bottom, yy) + pdf.set_y(bottom + 2)