From 5ca0a6c2399eb9d20ee4862cfa5778494e0d784c Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Wed, 7 Oct 2026 01:44:28 +0100 Subject: [PATCH] feat: add export to PDF --- AGENTS.md | 5 +- README.md | 7 +- app/pdf.py | 167 +++++++++++++++++++++ app/templates/_schedule_export_form.html | 20 +++ app/templates/admin_schedules.html | 12 +- app/templates/base.html | 1 + app/templates/export_schedule.html | 14 ++ app/web.py | 131 ++++++++++++++++- docs/ARCHITECTURE.md | 4 +- docs/DOMAIN.md | 16 ++ requirements-dev.txt | 1 + requirements.txt | 1 + tests/conftest.py | 118 +++++++++++++++ tests/test_export_schedule.py | 177 +++++++++++++++++++++++ 14 files changed, 666 insertions(+), 8 deletions(-) create mode 100644 app/pdf.py create mode 100644 app/templates/_schedule_export_form.html create mode 100644 app/templates/export_schedule.html create mode 100644 tests/conftest.py create mode 100644 tests/test_export_schedule.py diff --git a/AGENTS.md b/AGENTS.md index 8db2cbf..1ec392f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,7 @@ live in `requirements-dev.txt`. - `app/scheduling.py`: monthly pattern and rotation generation. - `app/bootstrap.py`: initial administrator and seeded schedules. - `app/calendar.py`: iCalendar feeds; `app/i18n.py`: Portuguese labels and formatting. +- `app/pdf.py`: single-page A4 schedule lists using ReportLab. - `app/notifications.py`: synchronous SMTP delivery and notification history. - `app/security.py`: password hashing and CSRF token generation. - `app/cli.py`: database initialization/migration, demo seeding, shell, reminders. @@ -22,7 +23,7 @@ live in `requirements-dev.txt`. - `migrations/`: Alembic environment and the squashed `0001_initial` revision. - `alembic.ini`: migration paths and logging; the database URL comes from settings. - `compose.yaml`: example production deployment with persistent SQLite storage. -- `tests/`: pytest discovery directory; currently empty. +- `tests/`: export behavior tests and isolated database/client fixtures. Read `docs/DOMAIN.md` for business rules and `docs/ARCHITECTURE.md` for lifecycle and deployment details. See `README.md` for the test workflow. @@ -83,7 +84,7 @@ needed. Python 3.12+ with `venv`/pip and `make` are prerequisites. and keep tests independent of local `.env` values and persistent application data. - Prefer behavior and domain invariants over assertions about implementation details. - An empty suite succeeds through `make test`; test failures and pytest errors still - fail the command. No tests or application fixtures have been added yet. + fail the command. PDF tests inspect downloaded documents with pypdf. Run `make test` after relevant changes and report its result accurately. An empty suite verifies the runner only, not application behavior. diff --git a/README.md b/README.md index 1a8d922..70ed8ad 100644 --- a/README.md +++ b/README.md @@ -106,8 +106,9 @@ or run Docker or database setup commands. The framework is **pytest**, with **HTTPX** available for FastAPI's `TestClient`. Configuration is in `pyproject.toml`; tests are discovered under `tests/`. -There are no tests yet: pytest will report `no tests ran`, and `make test` treats -that result as success. Actual failures and pytest errors return a nonzero status. +The suite covers PDF downloads, date boundaries, permissions, preservation of +assignments and single-page A4 output. Fixtures use temporary SQLite storage and +disable SMTP. Actual failures and pytest errors return a nonzero status. Optional pytest arguments use the same command: @@ -115,7 +116,7 @@ Optional pytest arguments use the same command: make test ARGS="-k rotation -v" ``` -## Adding tests later +## Adding tests - Put files in `tests/test_*.py`, name functions `test_*`, and use plain `assert`. - Use pytest's `tmp_path` and `monkeypatch` for isolated data and settings. diff --git a/app/pdf.py b/app/pdf.py new file mode 100644 index 0000000..c827a49 --- /dev/null +++ b/app/pdf.py @@ -0,0 +1,167 @@ +"""Single-page A4 schedule lists, downloaded without a browser print dialog.""" + +from __future__ import annotations + +from collections import defaultdict +from dataclasses import dataclass +from datetime import date +from io import BytesIO +from itertools import combinations +from pathlib import Path +from xml.sax.saxutils import escape + +import reportlab +from reportlab.lib.colors import HexColor +from reportlab.lib.pagesizes import A4 +from reportlab.lib.styles import ParagraphStyle +from reportlab.lib.units import mm +from reportlab.pdfbase import pdfmetrics +from reportlab.pdfbase.ttfonts import TTFont +from reportlab.pdfgen.canvas import Canvas +from reportlab.platypus import Paragraph + +from .config import settings +from .i18n import month_name +from .models import Assignment, Schedule + +# ReportLab ships these Unicode fonts, including Portuguese accents, in its wheel. +FONT_DIR = Path(reportlab.__file__).parent / "fonts" +pdfmetrics.registerFont(TTFont("Rota", str(FONT_DIR / "Vera.ttf"))) +pdfmetrics.registerFont(TTFont("RotaBold", str(FONT_DIR / "VeraBd.ttf"))) +RED = HexColor("#c81018") +GREEN = HexColor("#183c2f") +MUTED = HexColor("#6f6567") + + +@dataclass +class MonthBlock: + title: str + rows: list[tuple[str, Paragraph, float]] + height: float + + +def _columns(blocks: list[MonthBlock], count: int) -> list[list[MonthBlock]]: + """Balance complete months across columns, retaining chronological order.""" + best: list[list[MonthBlock]] = [] + best_height = float("inf") + for cuts in combinations(range(1, len(blocks)), count - 1): + edges = (0, *cuts, len(blocks)) + groups = [blocks[left:right] for left, right in zip(edges, edges[1:])] + height = max(sum(block.height for block in group) for group in groups) + if height < best_height: + best, best_height = groups, height + return best + + +def _layout( + months: dict[tuple[int, int], list[Assignment]], width: float, available: float +) -> tuple[list[list[MonthBlock]], float, float, float]: + """Fit the entire list on one page, wrapping names instead of truncating them.""" + for count in range(1, min(4, len(months)) + 1): + column_width = (width - (count - 1) * 7 * mm) / count + for size in range(16, 7, -1): + style = ParagraphStyle( + "team", fontName="RotaBold", fontSize=size, leading=size * 1.3, + textColor=GREEN, splitLongWords=True, + ) + blocks = [] + for (year, month), assignments in months.items(): + rows = [] + for assignment in assignments: + text = assignment.team.name if assignment.team else "Sem atribuição" + paragraph = Paragraph(escape(text), style) + _, height = paragraph.wrap(column_width - size * 2.5, available) + rows.append((str(assignment.date.day), paragraph, height + size * 0.3)) + if not rows: + paragraph = Paragraph("Sem turnos neste período.", style) + _, height = paragraph.wrap(column_width - size * 2.5, available) + rows.append(("", paragraph, height + size * 0.3)) + blocks.append(MonthBlock( + f"{month_name(month)} {year}", rows, + size * 2 + sum(row[2] for row in rows) + size, + )) + groups = _columns(blocks, count) + height = max(sum(block.height for block in group) for group in groups) + if height <= available: + return groups, column_width, size, 1.0 + # Very dense ranges or unusually long names still retain every row on A4. + return groups, column_width, size, min(1.0, available / height) + + +def build_schedule_pdf( + schedule: Schedule, assignments: list[Assignment], start: date, end: date +) -> bytes: + output = BytesIO() + canvas = Canvas(output, pagesize=A4) + canvas.setTitle(schedule.name) + canvas.setAuthor(settings.app_name) + width, height = A4 + margin = 16 * mm + left_margin = 24 * mm + content_width = width - left_margin - margin + logo = Path(__file__).parent / "static" / "logo-crr.png" + text_x = left_margin + 94 + text_width = content_width - 112 + brand = Paragraph(escape(settings.app_name.upper()), ParagraphStyle( + "brand", fontName="RotaBold", fontSize=9, leading=12, textColor=MUTED, + )) + _, brand_height = brand.wrap(text_width, height) + title = Paragraph(escape(schedule.name), ParagraphStyle( + "title", fontName="RotaBold", fontSize=24, leading=29, textColor=RED, + )) + _, title_height = title.wrap(text_width, height) + header_height = max(94, brand_height + title_height + 43) + header_top = height - margin + header_bottom = header_top - header_height + + # A softly tinted banner and white logo badge frame the CRR identity. + canvas.setFillColor(HexColor("#fff4f4")) + canvas.roundRect(left_margin, header_bottom, content_width, header_height, 10, stroke=0, fill=1) + badge_y = header_bottom + (header_height - 68) / 2 + canvas.setFillColor(HexColor("#ffffff")) + canvas.roundRect(left_margin + 12, badge_y, 68, 68, 8, stroke=0, fill=1) + canvas.drawImage( + str(logo), left_margin + 18, badge_y + 6, width=56, height=56, + preserveAspectRatio=True, anchor="c", mask="auto", + ) + text_top = header_bottom + (header_height + brand_height + 7 + title_height) / 2 + brand.drawOn(canvas, text_x, text_top - brand_height) + title.drawOn(canvas, text_x, text_top - brand_height - 7 - title_height) + + canvas.setStrokeColor(HexColor("#eedada")) + canvas.setLineWidth(0.7) + canvas.line(left_margin, header_bottom - 12, width - margin, header_bottom - 12) + canvas.setStrokeColor(RED) + canvas.setLineWidth(3) + canvas.line(left_margin, header_bottom - 12, left_margin + 44, header_bottom - 12) + top = header_bottom - 30 + available = top - margin + + months: dict[tuple[int, int], list[Assignment]] = defaultdict(list) + for assignment in sorted(assignments, key=lambda row: row.date): + months[(assignment.date.year, assignment.date.month)].append(assignment) + if not months: + months[(start.year, start.month)] = [] + groups, column_width, size, scale = _layout(months, content_width, available) + canvas.saveState() + canvas.translate(left_margin, top) + canvas.scale(scale, scale) + for index, group in enumerate(groups): + x = index * (column_width + 7 * mm) + y = 0.0 + for block in group: + canvas.setFillColor(RED) + canvas.setFont("RotaBold", size) + canvas.drawString(x, y - size, block.title) + y -= size * 2 + for day, paragraph, row_height in block.rows: + canvas.setFillColor(GREEN) + canvas.setFont("RotaBold", size) + canvas.drawRightString(x + size * 1.5, y - size, day) + paragraph.drawOn(canvas, x + size * 2.5, y - paragraph.height) + y -= row_height + y -= size + canvas.restoreState() + canvas.showPage() + canvas.save() + return output.getvalue() diff --git a/app/templates/_schedule_export_form.html b/app/templates/_schedule_export_form.html new file mode 100644 index 0000000..5667555 --- /dev/null +++ b/app/templates/_schedule_export_form.html @@ -0,0 +1,20 @@ +{% if error %}{% endif %} +
+ +
+ + +
+

As datas inicial e final estão incluídas. Máximo de 12 meses; o tamanho do texto adapta-se ao intervalo.

+
+
diff --git a/app/templates/admin_schedules.html b/app/templates/admin_schedules.html index dee5691..4f194de 100644 --- a/app/templates/admin_schedules.html +++ b/app/templates/admin_schedules.html @@ -8,6 +8,13 @@ Atribuir por dia
+{% if schedules %} +
+

Exportar PDF

+

Escolhe uma escala e as datas para descarregar a lista de dias e equipas numa única folha A4.

+ {% include "_schedule_export_form.html" %} +
+{% endif %} {% for card in cards %} {% set schedule = card.schedule %}
@@ -16,7 +23,10 @@

{{ schedule.name }}

{{ card.kind_label }} · {{ schedule|horario }}{% if not schedule.is_active %} · inativa{% endif %}

- Configurar +
+ {% if schedule.is_active %}Exportar PDF{% endif %} + Configurar +
{% if card.kind == 'rotation' %}

Próximas datas

diff --git a/app/templates/base.html b/app/templates/base.html index b9136ab..7568820 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -18,6 +18,7 @@