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:
2026-04-03 22:32:14 +05:00
parent 29e3047792
commit b1eafa4e0b
5 changed files with 241 additions and 0 deletions
+105
View File
@@ -0,0 +1,105 @@
import json
import os
import uuid
import markdown
from docx import Document
from docx.shared import Pt
from jinja2 import Template
from weasyprint import HTML
from app.config import settings
SECTION_LABELS = {
"date_participants_topic": "Дата, участники, тема встречи",
"process_description": "Описание обследуемого процесса",
"current_state": "Текущее состояние (as-is)",
"problems": "Выявленные проблемы / узкие места",
"agreements": "Договорённости и решения",
"open_questions": "Открытые вопросы",
"tasks": "Задачи с ответственными и сроками",
"next_steps": "Следующие шаги",
"client_goals": "Верхнеуровневые цели клиента",
"project_parameters": "Параметры будущего проекта",
"budget_constraints": "Бюджетные ограничения",
"time_constraints": "Ограничения по срокам",
"decision_makers": "Лица, принимающие решения (ЛПР)",
"beneficiaries": "Бенефициары",
"influencers": "Лица, влияющие на принятие решения",
"discussed_topics": "Обсуждённые вопросы",
"decisions": "Принятые решения",
}
def _format_section_value(value) -> str:
if isinstance(value, list):
if value and isinstance(value[0], dict):
lines = []
for item in value:
parts = [f"{k}: {v}" for k, v in item.items()]
lines.append("- " + ", ".join(parts))
return "\n".join(lines)
return "\n".join(f"- {item}" for item in value)
return str(value)
def _protocol_to_markdown(content: dict) -> str:
lines = ["# Протокол встречи\n"]
for key, value in content.items():
if key == "raw":
lines.append(str(value))
continue
label = SECTION_LABELS.get(key, key)
lines.append(f"## {label}\n")
lines.append(_format_section_value(value))
lines.append("")
return "\n".join(lines)
def export_markdown(content: dict, protocol_id: uuid.UUID) -> str:
os.makedirs(settings.export_dir, exist_ok=True)
file_path = os.path.join(settings.export_dir, f"{protocol_id}.md")
md_text = _protocol_to_markdown(content)
with open(file_path, "w", encoding="utf-8") as f:
f.write(md_text)
return file_path
def export_docx(content: dict, protocol_id: uuid.UUID) -> str:
os.makedirs(settings.export_dir, exist_ok=True)
file_path = os.path.join(settings.export_dir, f"{protocol_id}.docx")
doc = Document()
doc.add_heading("Протокол встречи", level=0)
for key, value in content.items():
if key == "raw":
doc.add_paragraph(str(value))
continue
label = SECTION_LABELS.get(key, key)
doc.add_heading(label, level=1)
text = _format_section_value(value)
for line in text.split("\n"):
doc.add_paragraph(line, style="List Bullet" if line.startswith("- ") else None)
doc.save(file_path)
return file_path
def export_pdf(content: dict, protocol_id: uuid.UUID) -> str:
os.makedirs(settings.export_dir, exist_ok=True)
file_path = os.path.join(settings.export_dir, f"{protocol_id}.pdf")
md_text = _protocol_to_markdown(content)
html_body = markdown.markdown(md_text)
html_full = f"""
<html><head><meta charset="utf-8">
<style>
body {{ font-family: sans-serif; margin: 40px; font-size: 14px; line-height: 1.6; }}
h1 {{ font-size: 22px; }} h2 {{ font-size: 16px; color: #333; border-bottom: 1px solid #ccc; padding-bottom: 4px; }}
ul {{ padding-left: 20px; }}
</style></head>
<body>{html_body}</body></html>
"""
HTML(string=html_full).write_pdf(file_path)
return file_path