_entries_since/_treatments_since requested a single page via `count`, but Nightscout's /api/v1/entries and /api/v1/treatments ignore a large `count` and cap the response around ~1150/~700 documents regardless of how far back the requested period goes. Every report page relying on fetch_entries_range/fetch_treatments_range (7/14/30/90-day selectors) was silently only getting the most recent ~3-4 days, no matter the selected period. Fixed by paginating with `find[date][$lte]` cursors in a new _paginated_get(), walking back until the requested `since` boundary is reached or the server returns a short/empty page (= genuinely no more data, confirmed by manually paginating against the real instance: entries go back 50+ days, treatments only ~4 days on this install). Also added reporting.completeness_warning(), shared by the interactive pages (via ui_common.render_completeness_warning) and the PDF export, that distinguishes "a structural gap at the start of the period" (data wasn't fetched/available) from "scattered gaps below the clinical AGP coverage threshold" (Danne et al. 2017) — the previous single generic "X% sensor coverage" message read as a CGM/sensor problem even when the real cause was this fetch bug.
143 lines
4.8 KiB
Python
143 lines
4.8 KiB
Python
"""
|
|
PDF-rapportgeneratie voor geselecteerde rapportageonderdelen (FR10).
|
|
|
|
Gebruikt fpdf2 (puur Python, geen systeemdependencies) voor de PDF-opbouw en
|
|
matplotlib voor een eenvoudige statische AGP-grafiek specifiek voor de PDF —
|
|
bewust niet dezelfde Plotly-figuren als op de pagina's zelf (die zouden
|
|
kaleido vereisen, met een ingebakken Chromium-build: een groter image en meer
|
|
Trivy-oppervlak, voor dit doel niet nodig).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
|
|
import matplotlib
|
|
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
import pandas as pd
|
|
from fpdf import FPDF
|
|
from fpdf.enums import XPos, YPos
|
|
|
|
from reporting import (
|
|
agp_percentile_bands,
|
|
completeness_warning,
|
|
gmi_percent,
|
|
percent_cv,
|
|
sensor_active_percent,
|
|
tir_breakdown_5band,
|
|
)
|
|
|
|
SECTION_SUMMARY = "Samenvatting"
|
|
SECTION_AGP = "AGP profiel"
|
|
SECTION_EVENTS = "Hypo-/hyperevents"
|
|
|
|
AVAILABLE_SECTIONS = [SECTION_SUMMARY, SECTION_AGP, SECTION_EVENTS]
|
|
|
|
_LINE_KWARGS = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
|
|
|
|
|
|
def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
|
|
bands = agp_percentile_bands(glucose)
|
|
fig, ax = plt.subplots(figsize=(7, 3))
|
|
hours = bands["minute_of_day"] / 60
|
|
ax.fill_between(hours, bands["p5"], bands["p95"], alpha=0.15, color="#2a78d6", label="5e-95e pct")
|
|
ax.fill_between(hours, bands["p25"], bands["p75"], alpha=0.3, color="#2a78d6", label="25e-75e pct")
|
|
ax.plot(hours, bands["p50"], color="#2a78d6", linewidth=2, label="Mediaan")
|
|
ax.set_xlabel("Uur van de dag")
|
|
ax.set_ylabel("mmol/L")
|
|
ax.set_xlim(0, 24)
|
|
ax.legend(loc="upper right", fontsize=8)
|
|
fig.tight_layout()
|
|
|
|
buf = io.BytesIO()
|
|
fig.savefig(buf, format="png", dpi=150)
|
|
plt.close(fig)
|
|
buf.seek(0)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
|
|
mean_mmol = glucose["mmol"].mean()
|
|
tir = tir_breakdown_5band(glucose)
|
|
active_pct = sensor_active_percent(glucose, start, end)
|
|
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "Samenvatting", **_LINE_KWARGS)
|
|
|
|
warning = completeness_warning(glucose, start, end)
|
|
if warning:
|
|
pdf.set_font("Helvetica", "BI", 10)
|
|
pdf.multi_cell(0, 5, warning)
|
|
pdf.ln(2)
|
|
|
|
pdf.set_font("Helvetica", "", 11)
|
|
pdf.cell(0, 6, f"Sensordekking: {active_pct:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Gemiddelde glucose: {mean_mmol:.1f} mmol/L", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Geschat HbA1c (GMI): {gmi_percent(mean_mmol):.1f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Variabiliteit (%CV): {percent_cv(glucose):.0f}%", **_LINE_KWARGS)
|
|
pdf.ln(2)
|
|
pdf.cell(0, 6, f"Zeer laag (<3.0 mmol/L): {tir['very_low']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Laag (3.0-3.9 mmol/L): {tir['low']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"In bereik (3.9-10.0 mmol/L): {tir['in_range']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Hoog (10.0-13.9 mmol/L): {tir['high']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Zeer hoog (>13.9 mmol/L): {tir['very_high']:.0f}%", **_LINE_KWARGS)
|
|
pdf.ln(4)
|
|
|
|
|
|
def _add_agp_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "AGP profiel", **_LINE_KWARGS)
|
|
png_bytes = _agp_figure_png(glucose)
|
|
pdf.image(io.BytesIO(png_bytes), w=180)
|
|
pdf.ln(4)
|
|
|
|
|
|
def _add_events_section(pdf: FPDF, events_summary: dict[str, dict]) -> None:
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "Hypo-/hyperevents", **_LINE_KWARGS)
|
|
pdf.set_font("Helvetica", "", 11)
|
|
for label, summary in events_summary.items():
|
|
pdf.cell(
|
|
0,
|
|
6,
|
|
f"{label}: {summary['count']} events, gemiddeld {summary['avg_duration_minutes']:.0f} min, "
|
|
f"{summary['events_per_week']:.1f}/week",
|
|
**_LINE_KWARGS,
|
|
)
|
|
pdf.ln(4)
|
|
|
|
|
|
def build_report_pdf(
|
|
sections: list[str],
|
|
glucose: pd.DataFrame,
|
|
events_summary: dict[str, dict],
|
|
start,
|
|
end,
|
|
) -> bytes:
|
|
"""Bouw een PDF met de geselecteerde onderdelen.
|
|
|
|
`events_summary` bevat vooraf berekende hypo/hyper-samenvattingen (label ->
|
|
resultaat van reporting.summarize_events), zodat deze module geen
|
|
event-detectie hoeft te herhalen.
|
|
"""
|
|
pdf = FPDF()
|
|
pdf.add_page()
|
|
pdf.set_font("Helvetica", "B", 16)
|
|
pdf.cell(0, 10, "Glucoserapport", **_LINE_KWARGS)
|
|
pdf.set_font("Helvetica", "", 11)
|
|
pdf.cell(0, 8, f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}", **_LINE_KWARGS)
|
|
pdf.ln(4)
|
|
|
|
if not glucose.empty:
|
|
if SECTION_SUMMARY in sections:
|
|
_add_summary_section(pdf, glucose, start, end)
|
|
if SECTION_AGP in sections:
|
|
_add_agp_section(pdf, glucose)
|
|
|
|
if SECTION_EVENTS in sections and events_summary:
|
|
_add_events_section(pdf, events_summary)
|
|
|
|
return bytes(pdf.output())
|