Files
GostGenerator/web/backend/app/services/espd/content_ctx.py
T
2026-09-09 13:03:41 +03:00

50 lines
1.5 KiB
Python

"""Build docxtpl extra_context from ESPD state / request."""
from __future__ import annotations
from typing import Any
from app.services.espd.html_util import html_to_plain
from app.services.espd.models import CONTENT_CONTEXT_KEYS, DocContent, DocumentType, EspdState
def resolve_doc_html_map(
state: EspdState,
doc_contents: dict[str, DocContent] | dict[str, Any] | None = None,
) -> dict[str, str]:
"""Return {doc_type: html} merging request override with state."""
out: dict[str, str] = {}
for dt in DocumentType:
if dt == DocumentType.SPEC:
continue
key = dt.value
html = ""
if doc_contents and key in doc_contents:
raw = doc_contents[key]
if isinstance(raw, DocContent):
html = raw.html or ""
elif isinstance(raw, dict):
html = str(raw.get("html") or "")
else:
html = str(raw or "")
if not html:
html = state.get_doc_html(key)
if html:
out[key] = html
return out
def content_extra_context(doc_type: DocumentType, html_or_plain: str) -> dict[str, str]:
plain = html_or_plain or ""
if "<" in plain:
plain = html_to_plain(plain)
extra = {"DOC_CONTENT": plain}
key = CONTENT_CONTEXT_KEYS.get(doc_type)
if key:
extra[key] = plain
return extra
def plain_contents_map(html_map: dict[str, str]) -> dict[str, str]:
return {k: html_to_plain(v) if v and "<" in v else (v or "") for k, v in html_map.items()}