"""Template-based Word renderer for KS-3. DB -> KS3ExportDocument (DTO) -> Template Renderer -> docx bytes The renderer never touches the database or DocumentArtifact service. It loads the versioned template from app/templates_docs/ks3/, fills placeholders and expands the dynamic KS-2 table, and returns bytes. """ from __future__ import annotations import io import json from copy import deepcopy from decimal import Decimal from pathlib import Path from docx import Document from app.exporters.common import MONEY_TEXT, format_date, format_period from app.exporters.ks3_dto import KS3ExportDocument TEMPLATE_TYPE = "ks3" TEMPLATE_VERSION = 1 TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks3" TEMPLATE_FILE = TEMPLATE_DIR / "ks3_ru_v1.docx" MANIFEST_FILE = TEMPLATE_DIR / "manifest.json" _ROWS_MARKER = "##KS3_KS2_ROWS##" _TOTALS_MARKER = "##KS3_TOTALS##" _STORNO_MARKER = "##KS3_STORNO##" class TemplateNotFoundError(FileNotFoundError): """KS-3 template resource is missing.""" def load_template_manifest() -> dict: if not MANIFEST_FILE.is_file(): raise TemplateNotFoundError(f"Template manifest not found: {MANIFEST_FILE}") with MANIFEST_FILE.open("r", encoding="utf-8") as handle: return json.load(handle) def _replace_in_paragraphs(container, mapping: dict[str, str]) -> None: """Replace {{key}} placeholders in all paragraphs/runs of a container.""" for paragraph in container.paragraphs: for run in paragraph.runs: text = run.text for key, value in mapping.items(): text = text.replace("{{" + key + "}}", value if value is not None else "") if text != run.text: run.text = text for table in container.tables: for row in table.rows: for cell in row.cells: _replace_in_paragraphs(cell, mapping) def _find_marker_table(document, marker: str): """Return (table, row_index) containing the marker in the first cell.""" for table in document.tables: for idx, row in enumerate(table.rows): first = row.cells[0].text.strip() if marker in first: return table, idx raise TemplateNotFoundError(f"Marker {marker!r} not found in template") def _clear_cell(cell) -> None: for paragraph in cell.paragraphs: for run in paragraph.runs: run.text = "" def _set_cell(cell, text: str) -> None: if not cell.paragraphs: cell.text = text return paragraph = cell.paragraphs[0] if paragraph.runs: paragraph.runs[0].text = text for extra in paragraph.runs[1:]: extra.text = "" else: paragraph.add_run(text) def _clone_row(table, template_row_idx: int, dest_row_idx: int) -> None: """Copy XML of a template row to a destination row index.""" template_tr = table.rows[template_row_idx]._tr dest_tr = table.rows[dest_row_idx]._tr dest_tr.getparent().replace(dest_tr, deepcopy(template_tr)) def _insert_row_before(table, before_tr, template_tr): """Insert a deep copy of template_tr immediately before before_tr.""" new_tr = deepcopy(template_tr) before_tr.addprevious(new_tr) return new_tr def render_ks3_word(doc: KS3ExportDocument) -> bytes: """Render KS-3 from a template. Returns docx bytes. No DB / no artifact writes.""" if not TEMPLATE_FILE.is_file(): raise TemplateNotFoundError( f"KS-3 template not found: {TEMPLATE_FILE}. " "Add the official template to app/templates_docs/ks3/." ) # Work on an in-memory copy; never modify the template on disk. d = Document(str(TEMPLATE_FILE)) h = doc.header mapping = { "project_name": h.project_name or "", "customer": h.customer or "", "contract_number": h.contract_number or "", "contract_date": format_date(h.contract_date), "currency": h.currency or "", "period": format_period(h.period_from, h.period_to), "comment": h.comment or "", "ks3_number": h.ks3_number or "", "ks3_date": format_date(h.ks3_date), } _replace_in_paragraphs(d, mapping) # Storno banner for paragraph in d.paragraphs: for run in paragraph.runs: if _STORNO_MARKER in run.text: run.text = "СТОРНИРОВАН" if h.status == "cancelled" else "" # Locate template row and totals row in the same table items = list(doc.items) table, rows_idx = _find_marker_table(d, _ROWS_MARKER) totals_table, totals_idx = _find_marker_table(d, _TOTALS_MARKER) if totals_table._tbl is not table._tbl: raise TemplateNotFoundError("KS3_ROWS and KS3_TOTALS must be in the same table") template_tr = table.rows[rows_idx]._tr totals_tr = table.rows[totals_idx]._tr if not items: # Single placeholder row without fake values row = table.rows[rows_idx] _set_cell(row.cells[0], "—") _set_cell(row.cells[1], "—") _set_cell(row.cells[2], "—") _set_cell(row.cells[3], "—") _set_cell(row.cells[4], "—") else: # First item fills the template row row = table.rows[rows_idx] item = items[0] _set_cell(row.cells[0], str(item.row_number)) _set_cell(row.cells[1], f"№{item.ks2_number}") _set_cell(row.cells[2], format_date(item.ks2_date)) _set_cell(row.cells[3], format_period(item.period_from, item.period_to)) _set_cell(row.cells[4], MONEY_TEXT.format(item.amount)) # Insert additional items BEFORE the totals row for item in items[1:]: new_tr = _insert_row_before(table, totals_tr, template_tr) # Re-read the new row from the table object new_row = next(r for r in table.rows if r._tr is new_tr) _set_cell(new_row.cells[0], str(item.row_number)) _set_cell(new_row.cells[1], f"№{item.ks2_number}") _set_cell(new_row.cells[2], format_date(item.ks2_date)) _set_cell(new_row.cells[3], format_period(item.period_from, item.period_to)) _set_cell(new_row.cells[4], MONEY_TEXT.format(item.amount)) # Totals (locate by stable XML identity — index shifts after inserts) total_row = next(r for r in table.rows if r._tr is totals_tr) _set_cell(total_row.cells[0], "Итого:") _set_cell(total_row.cells[4], MONEY_TEXT.format(doc.total)) buf = io.BytesIO() d.save(buf) buf.seek(0) return buf.read()