Production
This commit is contained in:
@@ -0,0 +1,236 @@
|
||||
"""Approved-report and company-form PDF generation.
|
||||
|
||||
WeasyPrint (BSD-3-Clause) renders Jinja2 HTML templates, so every layout is plain
|
||||
HTML/CSS that anyone on the team can edit. The approved Daily Call Report and every
|
||||
company form (tour plan, fare chart, sales & stock, ...) extend
|
||||
``templates/forms/_form_base.html``, because each is a copy of the company's printed form;
|
||||
each has its own template (``dcr.html`` or one under ``templates/forms/``). What a form
|
||||
shows is decided in ``app.pdf.forms``.
|
||||
|
||||
WeasyPrint needs system libraries (Pango, HarfBuzz) and DejaVu fonts. They are pinned in
|
||||
the Dockerfile. If they are genuinely absent (a bare dev machine, CI without the apt
|
||||
step) the service falls back to a minimal built-in writer so the workflow still
|
||||
completes and tests still run — and logs a loud warning, because that fallback
|
||||
produces a plain-text PDF, not the designed layout. Production must have WeasyPrint;
|
||||
``pdf_engine_ready()`` lets the health check and startup log say so.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import uuid
|
||||
from html.parser import HTMLParser
|
||||
from pathlib import Path
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.audit.service import AuditService
|
||||
from app.common.enums import AuditAction, EntityType
|
||||
from app.config.settings import settings
|
||||
from app.pdf.forms import approval_signature_line, build_dcr_context, build_form_context
|
||||
from app.reports.models import DailyCallReport
|
||||
from app.users.models import User
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_TEMPLATE_DIR = Path(__file__).parent / "templates"
|
||||
_env = Environment(
|
||||
loader=FileSystemLoader(_TEMPLATE_DIR),
|
||||
autoescape=select_autoescape(["html"]),
|
||||
)
|
||||
_env.globals.update(
|
||||
company_name=settings.PDF_COMPANY_NAME,
|
||||
company_address=settings.PDF_COMPANY_ADDRESS,
|
||||
company_website=settings.PDF_COMPANY_WEBSITE,
|
||||
company_email=settings.PDF_COMPANY_EMAIL,
|
||||
company_phone=settings.PDF_COMPANY_PHONE,
|
||||
)
|
||||
|
||||
try: # pragma: no cover - depends on system libraries
|
||||
from weasyprint import HTML as _WeasyHTML
|
||||
|
||||
WEASYPRINT_AVAILABLE = True
|
||||
except Exception: # noqa: BLE001 - ImportError or OSError from missing libs
|
||||
_WeasyHTML = None
|
||||
WEASYPRINT_AVAILABLE = False
|
||||
|
||||
|
||||
def pdf_engine_ready() -> bool:
|
||||
"""True when the designed (WeasyPrint) layout can be rendered."""
|
||||
return WEASYPRINT_AVAILABLE
|
||||
|
||||
|
||||
def _minimal_pdf(text: str) -> bytes:
|
||||
"""Fallback renderer: a valid single-page PDF containing plain text.
|
||||
|
||||
Used ONLY when WeasyPrint's system libraries are unavailable. It exists so the
|
||||
approval workflow and its tests never depend on native libraries being present.
|
||||
"""
|
||||
lines = [ln[:95] for ln in text.splitlines()][:52]
|
||||
content = ["BT", "/F1 9 Tf", "40 780 Td", "11 TL"]
|
||||
for line in lines:
|
||||
escaped = line.replace("\\", r"\\").replace("(", r"\(").replace(")", r"\)")
|
||||
content.append(f"({escaped}) Tj T*")
|
||||
content.append("ET")
|
||||
stream = "\n".join(content).encode("latin-1", "replace")
|
||||
|
||||
objects = [
|
||||
b"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] "
|
||||
b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>",
|
||||
b"<< /Length " + str(len(stream)).encode() + b" >>\nstream\n" + stream + b"\nendstream",
|
||||
b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
|
||||
]
|
||||
|
||||
out = bytearray(b"%PDF-1.4\n")
|
||||
offsets = [0]
|
||||
for i, body in enumerate(objects, start=1):
|
||||
offsets.append(len(out))
|
||||
out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n"
|
||||
|
||||
xref_pos = len(out)
|
||||
out += f"xref\n0 {len(objects) + 1}\n".encode()
|
||||
out += b"0000000000 65535 f \n"
|
||||
for off in offsets[1:]:
|
||||
out += f"{off:010d} 00000 n \n".encode()
|
||||
out += (
|
||||
f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\n"
|
||||
f"startxref\n{xref_pos}\n%%EOF\n"
|
||||
).encode()
|
||||
return bytes(out)
|
||||
|
||||
|
||||
class _TextExtractor(HTMLParser):
|
||||
"""Flattens a rendered form to lines of text for the plain-text fallback."""
|
||||
|
||||
_SKIP = {"style", "title", "script"}
|
||||
_BREAK = {"tr", "div", "h1", "h2", "p", "br", "table"}
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__()
|
||||
self.parts: list[str] = []
|
||||
self._skipping = 0
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list) -> None:
|
||||
if tag in self._SKIP:
|
||||
self._skipping += 1
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in self._SKIP:
|
||||
self._skipping -= 1
|
||||
elif tag in {"td", "th"}:
|
||||
self.parts.append(" | ")
|
||||
elif tag in self._BREAK:
|
||||
self.parts.append("\n")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if not self._skipping and data.strip():
|
||||
self.parts.append(" ".join(data.split()) + " ")
|
||||
|
||||
|
||||
def _html_to_text(html: str) -> str:
|
||||
parser = _TextExtractor()
|
||||
parser.feed(html)
|
||||
lines = ("".join(parser.parts)).splitlines()
|
||||
cleaned = (" ".join(line.split()).strip(" |") for line in lines)
|
||||
return "\n".join(line for line in cleaned if line)
|
||||
|
||||
|
||||
def _approval_signature_line(
|
||||
table_name: str,
|
||||
approval_status: str | None = None,
|
||||
am_name: str | None = None,
|
||||
am_role: str = "Area Manager",
|
||||
) -> str:
|
||||
return approval_signature_line(table_name, approval_status, am_name)
|
||||
|
||||
|
||||
def csv_table_pdf_bytes(
|
||||
table_name: str,
|
||||
table_label: str,
|
||||
columns: tuple[str, ...],
|
||||
rows: list[dict[str, object]],
|
||||
approval_status: str | None = None,
|
||||
am_name: str | None = None,
|
||||
am_role: str = "Area Manager",
|
||||
approved_at: str | None = None,
|
||||
) -> bytes:
|
||||
"""Render every stored row of an imported table on its own company-form layout."""
|
||||
context = build_form_context(
|
||||
table_name, table_label, columns, rows, approval_status, am_name, approved_at
|
||||
)
|
||||
html = _env.get_template(f"forms/{context['template']}.html").render(**context)
|
||||
if WEASYPRINT_AVAILABLE:
|
||||
return _WeasyHTML(string=html).write_pdf()
|
||||
|
||||
logger.warning(
|
||||
"WeasyPrint unavailable — using the plain-text fallback renderer for %s. "
|
||||
"Install Pango/HarfBuzz (see Dockerfile) before production use.",
|
||||
table_name,
|
||||
)
|
||||
return _minimal_pdf(_html_to_text(html))
|
||||
|
||||
|
||||
def csv_pdf_bytes(table_label: str, row: dict[str, object]) -> bytes:
|
||||
"""Render one imported table row for the row-level PDF action."""
|
||||
columns = tuple(key for key in row if key not in {"id", "source_row_number"})
|
||||
return csv_table_pdf_bytes("row", table_label, columns, [row])
|
||||
|
||||
|
||||
class PDFService:
|
||||
def __init__(self, db: AsyncSession) -> None:
|
||||
self.db = db
|
||||
self.audit = AuditService(db)
|
||||
|
||||
async def _approval(self, dcr: DailyCallReport) -> dict[str, str] | None:
|
||||
"""Who approved the report and when, from the audit trail — the signature cannot be typed in."""
|
||||
if dcr.approved_at is None:
|
||||
return None
|
||||
approvals = [h for h in await self.audit.approval_history_for(dcr.id) if h.action == AuditAction.APPROVE]
|
||||
if not approvals:
|
||||
return None
|
||||
approver = await self.db.get(User, approvals[-1].actor_user_id)
|
||||
if approver is None:
|
||||
return None
|
||||
when = dcr.approved_at.astimezone(ZoneInfo(settings.APP_TIMEZONE)).strftime("%d/%m/%Y %H:%M")
|
||||
return {"name": approver.full_name, "at": when}
|
||||
|
||||
async def _context(self, dcr: DailyCallReport) -> dict:
|
||||
return build_dcr_context(
|
||||
dcr,
|
||||
sorted(dcr.doctor_calls, key=lambda c: c.visit_time),
|
||||
sorted(dcr.chemist_calls, key=lambda c: c.visit_time),
|
||||
await self._approval(dcr),
|
||||
)
|
||||
|
||||
async def render_bytes(self, dcr: DailyCallReport) -> bytes:
|
||||
"""The report as a PDF in the current layout — a pure function of the stored report."""
|
||||
context = await self._context(dcr)
|
||||
html = _env.get_template("dcr.html").render(**context)
|
||||
|
||||
if WEASYPRINT_AVAILABLE:
|
||||
return _WeasyHTML(string=html).write_pdf()
|
||||
|
||||
logger.warning(
|
||||
"WeasyPrint unavailable — using the plain-text fallback renderer. "
|
||||
"Install Pango/cairo (see Dockerfile) before production use."
|
||||
)
|
||||
return _minimal_pdf(_env.get_template("dcr.txt").render(**context))
|
||||
|
||||
async def render_and_store(self, dcr: DailyCallReport, approver: User) -> str:
|
||||
pdf_bytes = await self.render_bytes(dcr)
|
||||
|
||||
directory = Path(settings.PDF_STORAGE_PATH) / str(dcr.report_date.year)
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
path = directory / f"DCR-{dcr.report_date.isoformat()}-{dcr.id}.pdf"
|
||||
path.write_bytes(pdf_bytes)
|
||||
|
||||
await self.audit.log(
|
||||
actor_user_id=approver.id,
|
||||
entity_type=EntityType.DCR,
|
||||
entity_id=dcr.id,
|
||||
action=AuditAction.UPDATE,
|
||||
after={"pdf_generated": str(path)},
|
||||
)
|
||||
return str(path)
|
||||
Reference in New Issue
Block a user