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:
@@ -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"'},
|
||||
)
|
||||
Reference in New Issue
Block a user