feat: add template-based KS-2 Excel and KS-3 Word renderers

This commit is contained in:
Арсентьев Александр
2026-09-29 17:50:58 +03:00
parent cddde114fe
commit e66bce0d25
12 changed files with 1643 additions and 176 deletions
+163 -78
View File
@@ -1,92 +1,177 @@
"""Word renderer for KS-3 export using python-docx."""
"""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 docx.enum.section import WD_ORIENT
from docx.enum.table import WD_TABLE_ALIGNMENT
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt, RGBColor
from app.exporters.common import MONEY_TEXT, format_date, format_period, project_requisite_lines
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:
d = Document()
"""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)
section = d.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
# Title
title = d.add_paragraph()
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = title.add_run(f"Акт КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
run.bold = True
run.font.size = Pt(14)
if h.status == "cancelled":
mark = d.add_paragraph()
mark.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = mark.add_run("СТОРНИРОВАН")
run.bold = True
run.font.size = Pt(12)
run.font.color.rgb = RGBColor(0xC0, 0x00, 0x00)
d.add_paragraph()
header_lines = project_requisite_lines(
project_name=h.project_name,
customer=h.customer,
contract_number=h.contract_number,
contract_date=h.contract_date,
currency=h.currency,
period_text=format_period(h.period_from, h.period_to),
extra=[("Комментарий:", h.comment)],
)
for label, value in header_lines:
p = d.add_paragraph()
run = p.add_run(label + " ")
run.bold = True
p.add_run(value)
d.add_paragraph()
# Table
table = d.add_table(rows=1, cols=5)
table.style = "Table Grid"
table.alignment = WD_TABLE_ALIGNMENT.CENTER
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
for idx, col_name in enumerate(columns):
cell = table.rows[0].cells[idx]
cell.text = col_name
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.bold = True
run.font.size = Pt(9)
for item in doc.items:
row = table.add_row()
row.cells[0].text = str(item.row_number)
row.cells[1].text = f"№{item.ks2_number}"
row.cells[2].text = format_date(item.ks2_date)
row.cells[3].text = format_period(item.period_from, item.period_to)
row.cells[4].text = MONEY_TEXT.format(item.amount)
# Total row
total_row = table.add_row()
total_row.cells[0].merge(total_row.cells[3])
total_row.cells[0].text = "Итого:"
for paragraph in total_row.cells[0].paragraphs:
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
# Storno banner
for paragraph in d.paragraphs:
for run in paragraph.runs:
run.bold = True
total_row.cells[4].text = MONEY_TEXT.format(doc.total)
for paragraph in total_row.cells[4].paragraphs:
for run in paragraph.runs:
run.bold = True
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)