Phase 8: Customizable PDF Templates — locale support, admin editor, seed templates
Backend: - PdfTemplate model with locale field + UNIQUE(name, locale) constraint - Migration 007: pdf_templates table + template_id FK on generated_pdfs - Template service: CRUD, Jinja2 validation, render preview with sample data - Admin endpoints: CRUD /admin/pdf-templates + POST preview - User endpoint: GET /pdf/templates (active templates list) - pdf_service: resolves template from DB by ID or falls back to default for the appropriate locale - AI generate_pdf tool accepts optional template_id - Seed script + 4 HTML template files: - Basic Report (en/ru) — general-purpose report - Medical Report (en/ru) — health-focused with disclaimers Frontend: - Admin PDF templates page with editor, locale selector, live preview (iframe), template variables reference panel - PDF page: template selector dropdown in generation form - API clients for admin CRUD + user template listing - Sidebar: admin templates link - English + Russian translations Also added Phase 9 (OAuth) and Phase 10 (Rate Limits) placeholders to GeneralPlan. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -99,6 +99,7 @@ AI_TOOLS = [
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Title for the PDF report"},
|
||||
"template_id": {"type": "string", "description": "Optional UUID of a specific PDF template to use"},
|
||||
},
|
||||
"required": ["title"],
|
||||
},
|
||||
@@ -174,7 +175,8 @@ async def _execute_tool(
|
||||
|
||||
elif tool_name == "generate_pdf":
|
||||
from app.services.pdf_service import generate_pdf_report
|
||||
pdf = await generate_pdf_report(db, user_id, title=tool_input["title"])
|
||||
tmpl_id = uuid.UUID(tool_input["template_id"]) if tool_input.get("template_id") else None
|
||||
pdf = await generate_pdf_report(db, user_id, title=tool_input["title"], template_id=tmpl_id)
|
||||
await db.commit()
|
||||
return json.dumps({
|
||||
"status": "generated",
|
||||
|
||||
@@ -13,10 +13,11 @@ from app.models.user import User
|
||||
from app.services.memory_service import get_user_memories
|
||||
|
||||
TEMPLATE_DIR = Path(__file__).parent.parent / "templates" / "pdf"
|
||||
jinja_env = Environment(
|
||||
_file_jinja_env = Environment(
|
||||
loader=FileSystemLoader(str(TEMPLATE_DIR)),
|
||||
autoescape=select_autoescape(["html"]),
|
||||
)
|
||||
_string_jinja_env = Environment(autoescape=select_autoescape(["html"]))
|
||||
|
||||
|
||||
async def generate_pdf_report(
|
||||
@@ -25,6 +26,7 @@ async def generate_pdf_report(
|
||||
title: str,
|
||||
document_ids: list[uuid.UUID] | None = None,
|
||||
chat_id: uuid.UUID | None = None,
|
||||
template_id: uuid.UUID | None = None,
|
||||
) -> GeneratedPdf:
|
||||
# Load user
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
@@ -52,9 +54,7 @@ async def generate_pdf_report(
|
||||
"excerpt": (doc.extracted_text or "")[:2000],
|
||||
})
|
||||
|
||||
# Render HTML
|
||||
template = jinja_env.get_template("report.html")
|
||||
html = template.render(
|
||||
template_vars = dict(
|
||||
title=title,
|
||||
user_name=user.full_name or user.username,
|
||||
generated_at=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
|
||||
@@ -63,6 +63,23 @@ async def generate_pdf_report(
|
||||
ai_summary=None,
|
||||
)
|
||||
|
||||
# Resolve template
|
||||
resolved_template_id = template_id
|
||||
if template_id:
|
||||
from app.services.pdf_template_service import get_template
|
||||
tmpl = await get_template(db, template_id)
|
||||
jinja_template = _string_jinja_env.from_string(tmpl.html_content)
|
||||
else:
|
||||
from app.services.pdf_template_service import get_default_template
|
||||
default_tmpl = await get_default_template(db)
|
||||
if default_tmpl:
|
||||
resolved_template_id = default_tmpl.id
|
||||
jinja_template = _string_jinja_env.from_string(default_tmpl.html_content)
|
||||
else:
|
||||
jinja_template = _file_jinja_env.get_template("report.html")
|
||||
|
||||
html = jinja_template.render(**template_vars)
|
||||
|
||||
# Generate PDF
|
||||
pdf_id = uuid.uuid4()
|
||||
pdf_dir = Path(settings.UPLOAD_DIR).parent / "pdfs" / str(user_id)
|
||||
@@ -73,7 +90,6 @@ async def generate_pdf_report(
|
||||
from weasyprint import HTML
|
||||
HTML(string=html).write_pdf(str(pdf_path))
|
||||
except ImportError:
|
||||
# WeasyPrint not installed — write HTML as fallback
|
||||
pdf_path = pdf_path.with_suffix(".html")
|
||||
pdf_path.write_text(html, encoding="utf-8")
|
||||
|
||||
@@ -85,6 +101,7 @@ async def generate_pdf_report(
|
||||
storage_path=str(pdf_path),
|
||||
source_document_ids=document_ids,
|
||||
source_chat_id=chat_id,
|
||||
template_id=resolved_template_id,
|
||||
)
|
||||
db.add(generated)
|
||||
await db.flush()
|
||||
|
||||
114
backend/app/services/pdf_template_service.py
Normal file
114
backend/app/services/pdf_template_service.py
Normal file
@@ -0,0 +1,114 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from jinja2 import Environment, TemplateSyntaxError, select_autoescape
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.pdf_template import PdfTemplate
|
||||
|
||||
_jinja_env = Environment(autoescape=select_autoescape(["html"]))
|
||||
|
||||
|
||||
def validate_jinja2(html: str) -> tuple[bool, str]:
|
||||
"""Validate Jinja2 template syntax. Returns (is_valid, error_message)."""
|
||||
try:
|
||||
_jinja_env.parse(html)
|
||||
return True, ""
|
||||
except TemplateSyntaxError as e:
|
||||
return False, f"Template syntax error at line {e.lineno}: {e.message}"
|
||||
|
||||
|
||||
async def list_templates(db: AsyncSession, active_only: bool = True, locale: str | None = None) -> list[PdfTemplate]:
|
||||
stmt = select(PdfTemplate)
|
||||
if active_only:
|
||||
stmt = stmt.where(PdfTemplate.is_active == True) # noqa: E712
|
||||
if locale:
|
||||
stmt = stmt.where(PdfTemplate.locale == locale)
|
||||
stmt = stmt.order_by(PdfTemplate.is_default.desc(), PdfTemplate.name, PdfTemplate.locale)
|
||||
result = await db.execute(stmt)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_template(db: AsyncSession, template_id: uuid.UUID) -> PdfTemplate:
|
||||
result = await db.execute(select(PdfTemplate).where(PdfTemplate.id == template_id))
|
||||
template = result.scalar_one_or_none()
|
||||
if not template:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Template not found")
|
||||
return template
|
||||
|
||||
|
||||
async def get_default_template(db: AsyncSession, locale: str = "en") -> PdfTemplate | None:
|
||||
result = await db.execute(
|
||||
select(PdfTemplate).where(
|
||||
PdfTemplate.is_default == True, # noqa: E712
|
||||
PdfTemplate.locale == locale,
|
||||
)
|
||||
)
|
||||
tmpl = result.scalar_one_or_none()
|
||||
if not tmpl:
|
||||
# Fallback to any default
|
||||
result = await db.execute(
|
||||
select(PdfTemplate).where(PdfTemplate.is_default == True) # noqa: E712
|
||||
)
|
||||
tmpl = result.scalars().first()
|
||||
return tmpl
|
||||
|
||||
|
||||
async def create_template(db: AsyncSession, **kwargs) -> PdfTemplate:
|
||||
html = kwargs.get("html_content", "")
|
||||
valid, error = validate_jinja2(html)
|
||||
if not valid:
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=error)
|
||||
|
||||
template = PdfTemplate(**kwargs)
|
||||
db.add(template)
|
||||
await db.flush()
|
||||
return template
|
||||
|
||||
|
||||
async def update_template(db: AsyncSession, template_id: uuid.UUID, **kwargs) -> PdfTemplate:
|
||||
template = await get_template(db, template_id)
|
||||
|
||||
if "html_content" in kwargs and kwargs["html_content"] is not None:
|
||||
valid, error = validate_jinja2(kwargs["html_content"])
|
||||
if not valid:
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=error)
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if value is not None:
|
||||
setattr(template, key, value)
|
||||
await db.flush()
|
||||
return template
|
||||
|
||||
|
||||
async def delete_template(db: AsyncSession, template_id: uuid.UUID) -> None:
|
||||
template = await get_template(db, template_id)
|
||||
if template.is_default:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Cannot delete the default template",
|
||||
)
|
||||
await db.delete(template)
|
||||
|
||||
|
||||
async def render_preview(html_content: str) -> str:
|
||||
"""Render template with sample data for preview."""
|
||||
valid, error = validate_jinja2(html_content)
|
||||
if not valid:
|
||||
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=error)
|
||||
|
||||
template = _jinja_env.from_string(html_content)
|
||||
return template.render(
|
||||
title="Sample Report",
|
||||
user_name="John Doe",
|
||||
generated_at="2026-03-19 12:00 UTC",
|
||||
memories=[
|
||||
{"category": "health", "title": "Annual Checkup", "content": "Last checkup was in January 2026. All results normal.", "importance": "medium"},
|
||||
{"category": "finance", "title": "Tax Deadline", "content": "Filing deadline: April 15, 2026", "importance": "high"},
|
||||
],
|
||||
documents=[
|
||||
{"original_filename": "report_2026.pdf", "doc_type": "report", "excerpt": "This is a sample document excerpt showing how document content appears in the report..."},
|
||||
],
|
||||
ai_summary="This is a sample AI-generated summary of the user's data.",
|
||||
)
|
||||
Reference in New Issue
Block a user