| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- """Render the selected case template once and reuse stored documents."""
- from datetime import date, datetime
- from pathlib import Path
- from typing import Literal
- from zoneinfo import ZoneInfo
- from docxtpl import DocxTemplate
- from fastapi import HTTPException
- from sqlalchemy import text
- from .file_storage import get_or_create_file
- from .jinja_templates import number_format, templates
- DocumentType = Literal["Mahnung", "Rechnung", "Beitreibungsauftrag"]
- TEMPLATE_DIR = Path(__file__).resolve().parents[1] / "templates/forderungen/details/docs"
- DOCX_MEDIA_TYPE = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
- def generated_document(db, client_db: str, document_no: str, document_type: DocumentType) -> Path:
- key = {"Client_DB": client_db, "Beleg_Nr": document_no}
- filename = f"{document_type}_{client_db}_{document_no}.docx"
- def create(destination):
- query = templates.env.get_template("forderungen/details/queries/forderungen_details.sql").render()
- row = db.execute(text(query), {"client_db": client_db, "beleg_nr": document_no}).mappings().first()
- if not row:
- raise HTTPException(404, "Forderung nicht gefunden")
- context = {
- name: value.strftime("%d.%m.%Y") if isinstance(value, (date, datetime)) else value if value is not None else ""
- for name, value in row.items()
- }
- for name in ("Beleg_Betrag", "Beleg_Offen", "Selbstbeteiligung_Betrag", "Mwst_Betrag"):
- if row.get(name) is not None:
- context[name] = number_format(row[name])
- context.update(
- Datum_heute=datetime.now(ZoneInfo("Europe/Berlin")).strftime("%d.%m.%Y"),
- Betrag_SB=context.get("Selbstbeteiligung_Betrag", ""),
- Betrag_USt=context.get("Mwst_Betrag", ""),
- Rechnung_Nr=document_no,
- Beleg_offen=context.get("Beleg_Offen", ""),
- Verursacher_Text=context.get("Verursacher_Aktuell_Text") or context.get("Verursacher_Text", ""),
- )
- template_path = TEMPLATE_DIR / f"{document_type}.docx"
- if not template_path.is_file():
- raise HTTPException(503, f"Die Vorlage {document_type}.docx ist nicht verfügbar.")
- document = DocxTemplate(template_path)
- document.render(context, autoescape=True)
- document.save(destination)
- return get_or_create_file(key, filename, create)
|