feat: export service — DOCX, PDF, MD generation and download API
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.api.deps import get_current_user
|
||||
from app.database import get_db
|
||||
from app.models.export_file import ExportFile, ExportFormat
|
||||
from app.models.protocol import Protocol
|
||||
from app.models.user import User
|
||||
from app.schemas.export_file import ExportFileResponse, ExportRequest
|
||||
from app.services.export import export_docx, export_markdown, export_pdf
|
||||
|
||||
router = APIRouter(prefix="/api/exports", tags=["exports"])
|
||||
|
||||
EXPORTERS = {
|
||||
ExportFormat.md: export_markdown,
|
||||
ExportFormat.docx: export_docx,
|
||||
ExportFormat.pdf: export_pdf,
|
||||
}
|
||||
|
||||
MEDIA_TYPES = {
|
||||
ExportFormat.md: "text/markdown",
|
||||
ExportFormat.docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
ExportFormat.pdf: "application/pdf",
|
||||
}
|
||||
|
||||
|
||||
@router.post("/protocol/{protocol_id}", response_model=ExportFileResponse, status_code=201)
|
||||
async def create_export(
|
||||
protocol_id: uuid.UUID,
|
||||
data: ExportRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
result = await db.execute(
|
||||
select(Protocol).where(Protocol.id == protocol_id)
|
||||
)
|
||||
protocol = result.scalar_one_or_none()
|
||||
if not protocol:
|
||||
raise HTTPException(404, "Protocol not found")
|
||||
|
||||
exporter = EXPORTERS[data.format]
|
||||
file_path = exporter(protocol.content, protocol.id)
|
||||
file_size = os.path.getsize(file_path)
|
||||
|
||||
export_file = ExportFile(
|
||||
protocol_id=protocol_id,
|
||||
format=data.format,
|
||||
file_path=file_path,
|
||||
file_size=file_size,
|
||||
)
|
||||
db.add(export_file)
|
||||
await db.commit()
|
||||
await db.refresh(export_file)
|
||||
return export_file
|
||||
|
||||
|
||||
@router.get("/{export_id}/download")
|
||||
async def download_export(
|
||||
export_id: uuid.UUID,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
user: User = Depends(get_current_user),
|
||||
):
|
||||
result = await db.execute(
|
||||
select(ExportFile).where(ExportFile.id == export_id)
|
||||
)
|
||||
export_file = result.scalar_one_or_none()
|
||||
if not export_file or not os.path.exists(export_file.file_path):
|
||||
raise HTTPException(404, "Export file not found")
|
||||
|
||||
return FileResponse(
|
||||
path=export_file.file_path,
|
||||
media_type=MEDIA_TYPES[export_file.format],
|
||||
filename=f"protocol.{export_file.format.value}",
|
||||
)
|
||||
Reference in New Issue
Block a user