Phase 6: PDF & Polish — PDF generation, admin users/settings, AI tool
Backend: - Setting + GeneratedPdf models, Alembic migration with default settings seed - PDF generation service (WeasyPrint + Jinja2 with autoescape) - Health report HTML template with memory entries + document excerpts - Admin user management: list, create, update (role/max_chats/is_active) - Admin settings: self_registration_enabled, default_max_chats - Self-registration check wired into auth register endpoint - default_max_chats applied to new user registrations - AI tool: generate_pdf creates health compilation PDFs - PDF compile/list/download API endpoints - WeasyPrint system deps added to Dockerfile Frontend: - PDF reports page with generate + download - Admin users page with create/edit/activate/deactivate - Admin settings page with self-registration toggle + max chats - Extended sidebar with PDF reports + admin users/settings links - English + Russian translations for all new UI Review fixes applied: - Jinja2 autoescape enabled (XSS prevention in PDFs) - db.refresh after flush (created_at populated correctly) - storage_path removed from API response (no internal path leak) - Role field uses Literal["user", "admin"] validation - React hooks called before conditional returns (rules of hooks) - default_max_chats setting now applied during registration Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
57
backend/app/services/admin_user_service.py
Normal file
57
backend/app/services/admin_user_service.py
Normal file
@@ -0,0 +1,57 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import hash_password
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
async def list_users(db: AsyncSession, limit: int = 50, offset: int = 0) -> tuple[list[User], int]:
|
||||
total = await db.scalar(select(func.count()).select_from(User))
|
||||
result = await db.execute(
|
||||
select(User).order_by(User.created_at.desc()).limit(limit).offset(offset)
|
||||
)
|
||||
return list(result.scalars().all()), total or 0
|
||||
|
||||
|
||||
async def get_user(db: AsyncSession, user_id: uuid.UUID) -> User:
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one_or_none()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
return user
|
||||
|
||||
|
||||
async def create_user(
|
||||
db: AsyncSession, email: str, username: str, password: str,
|
||||
full_name: str | None = None, role: str = "user", max_chats: int = 10,
|
||||
) -> User:
|
||||
existing = await db.execute(
|
||||
select(User).where((User.email == email) | (User.username == username))
|
||||
)
|
||||
if existing.scalar_one_or_none():
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="User already exists")
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
username=username,
|
||||
hashed_password=hash_password(password),
|
||||
full_name=full_name,
|
||||
role=role,
|
||||
max_chats=max_chats,
|
||||
)
|
||||
db.add(user)
|
||||
await db.flush()
|
||||
return user
|
||||
|
||||
|
||||
async def update_user(db: AsyncSession, user_id: uuid.UUID, **kwargs) -> User:
|
||||
user = await get_user(db, user_id)
|
||||
allowed = {"role", "is_active", "max_chats", "full_name"}
|
||||
for key, value in kwargs.items():
|
||||
if key in allowed and value is not None:
|
||||
setattr(user, key, value)
|
||||
await db.flush()
|
||||
return user
|
||||
@@ -92,6 +92,17 @@ AI_TOOLS = [
|
||||
"required": ["title", "body"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "generate_pdf",
|
||||
"description": "Generate a PDF health report compilation from the user's data. Use this when the user asks for a document or summary of their health information.",
|
||||
"input_schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {"type": "string", "description": "Title for the PDF report"},
|
||||
},
|
||||
"required": ["title"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
@@ -161,6 +172,17 @@ async def _execute_tool(
|
||||
"title": notif.title,
|
||||
})
|
||||
|
||||
elif tool_name == "generate_pdf":
|
||||
from app.services.pdf_service import generate_health_pdf
|
||||
pdf = await generate_health_pdf(db, user_id, title=tool_input["title"])
|
||||
await db.commit()
|
||||
return json.dumps({
|
||||
"status": "generated",
|
||||
"id": str(pdf.id),
|
||||
"title": pdf.title,
|
||||
"download_url": f"/api/v1/pdf/{pdf.id}/download",
|
||||
})
|
||||
|
||||
return json.dumps({"error": f"Unknown tool: {tool_name}"})
|
||||
|
||||
|
||||
|
||||
@@ -61,11 +61,15 @@ async def register_user(
|
||||
detail="User with this email or username already exists",
|
||||
)
|
||||
|
||||
from app.services.setting_service import get_setting_value
|
||||
default_max_chats = await get_setting_value(db, "default_max_chats", 10)
|
||||
|
||||
user = User(
|
||||
email=data.email,
|
||||
username=data.username,
|
||||
hashed_password=hash_password(data.password),
|
||||
full_name=data.full_name,
|
||||
max_chats=int(default_max_chats),
|
||||
)
|
||||
db.add(user)
|
||||
await db.flush()
|
||||
|
||||
107
backend/app/services/pdf_service.py
Normal file
107
backend/app/services/pdf_service.py
Normal file
@@ -0,0 +1,107 @@
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.config import settings
|
||||
from app.models.document import Document
|
||||
from app.models.generated_pdf import GeneratedPdf
|
||||
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(
|
||||
loader=FileSystemLoader(str(TEMPLATE_DIR)),
|
||||
autoescape=select_autoescape(["html"]),
|
||||
)
|
||||
|
||||
|
||||
async def generate_health_pdf(
|
||||
db: AsyncSession,
|
||||
user_id: uuid.UUID,
|
||||
title: str,
|
||||
document_ids: list[uuid.UUID] | None = None,
|
||||
chat_id: uuid.UUID | None = None,
|
||||
) -> GeneratedPdf:
|
||||
# Load user
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
user = result.scalar_one()
|
||||
|
||||
# Load memories
|
||||
memories = await get_user_memories(db, user_id, is_active=True)
|
||||
memory_data = [
|
||||
{"category": m.category, "title": m.title, "content": m.content, "importance": m.importance}
|
||||
for m in memories
|
||||
]
|
||||
|
||||
# Load documents
|
||||
doc_data = []
|
||||
if document_ids:
|
||||
for doc_id in document_ids:
|
||||
result = await db.execute(
|
||||
select(Document).where(Document.id == doc_id, Document.user_id == user_id)
|
||||
)
|
||||
doc = result.scalar_one_or_none()
|
||||
if doc:
|
||||
doc_data.append({
|
||||
"original_filename": doc.original_filename,
|
||||
"doc_type": doc.doc_type,
|
||||
"excerpt": (doc.extracted_text or "")[:2000],
|
||||
})
|
||||
|
||||
# Render HTML
|
||||
template = jinja_env.get_template("health_report.html")
|
||||
html = template.render(
|
||||
title=title,
|
||||
user_name=user.full_name or user.username,
|
||||
generated_at=datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC"),
|
||||
memories=memory_data,
|
||||
documents=doc_data,
|
||||
ai_summary=None,
|
||||
)
|
||||
|
||||
# Generate PDF
|
||||
pdf_id = uuid.uuid4()
|
||||
pdf_dir = Path(settings.UPLOAD_DIR).parent / "pdfs" / str(user_id)
|
||||
pdf_dir.mkdir(parents=True, exist_ok=True)
|
||||
pdf_path = pdf_dir / f"{pdf_id}.pdf"
|
||||
|
||||
try:
|
||||
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")
|
||||
|
||||
# Save record
|
||||
generated = GeneratedPdf(
|
||||
id=pdf_id,
|
||||
user_id=user_id,
|
||||
title=title,
|
||||
storage_path=str(pdf_path),
|
||||
source_document_ids=document_ids,
|
||||
source_chat_id=chat_id,
|
||||
)
|
||||
db.add(generated)
|
||||
await db.flush()
|
||||
await db.refresh(generated)
|
||||
return generated
|
||||
|
||||
|
||||
async def get_user_pdfs(db: AsyncSession, user_id: uuid.UUID) -> list[GeneratedPdf]:
|
||||
result = await db.execute(
|
||||
select(GeneratedPdf).where(GeneratedPdf.user_id == user_id)
|
||||
.order_by(GeneratedPdf.created_at.desc())
|
||||
)
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def get_pdf(db: AsyncSession, pdf_id: uuid.UUID, user_id: uuid.UUID) -> GeneratedPdf | None:
|
||||
result = await db.execute(
|
||||
select(GeneratedPdf).where(GeneratedPdf.id == pdf_id, GeneratedPdf.user_id == user_id)
|
||||
)
|
||||
return result.scalar_one_or_none()
|
||||
33
backend/app/services/setting_service.py
Normal file
33
backend/app/services/setting_service.py
Normal file
@@ -0,0 +1,33 @@
|
||||
import uuid
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.setting import Setting
|
||||
|
||||
|
||||
async def get_setting(db: AsyncSession, key: str) -> Setting | None:
|
||||
result = await db.execute(select(Setting).where(Setting.key == key))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_setting_value(db: AsyncSession, key: str, default=None):
|
||||
setting = await get_setting(db, key)
|
||||
return setting.value if setting else default
|
||||
|
||||
|
||||
async def get_all_settings(db: AsyncSession) -> list[Setting]:
|
||||
result = await db.execute(select(Setting).order_by(Setting.key))
|
||||
return list(result.scalars().all())
|
||||
|
||||
|
||||
async def upsert_setting(db: AsyncSession, key: str, value, admin_user_id: uuid.UUID) -> Setting:
|
||||
setting = await get_setting(db, key)
|
||||
if setting:
|
||||
setting.value = value
|
||||
setting.updated_by = admin_user_id
|
||||
else:
|
||||
setting = Setting(key=key, value=value, updated_by=admin_user_id)
|
||||
db.add(setting)
|
||||
await db.flush()
|
||||
return setting
|
||||
Reference in New Issue
Block a user