feat: KS-3 official Word form with marker template and single-table flow
Rewrite the KS-3 print renderer on the DOC-C4–DOC-C7 architecture: - working marker template ks3_ru_markers.docx from the official blank; static fields via named markers, values only from KS3ExportHeader/Item - one dynamic works table with w:tblHeader page-break repetition, no page/subtable split; final Итого block once at the end, VAT rows left empty (unsupported by the DTO) - unified money formatter (space thousands, comma decimals) - UI keeps only КС-3 (Word); Excel endpoint remains for internal tests - DB, KS3↔KS2 links, issue/cancel, payments and KS-2 untouched
This commit is contained in:
+228
-131
@@ -1,179 +1,276 @@
|
||||
"""Template-based Word renderer for KS-3.
|
||||
"""Official-form KS-3 Word renderer (DOC-C8, marker-template architecture).
|
||||
|
||||
DB -> KS3ExportDocument (DTO) -> Template Renderer -> docx bytes
|
||||
KS3ExportDocument -> ks3_ru_markers.docx -> generated DOCX
|
||||
|
||||
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.
|
||||
Architecture follows DOC-C4–DOC-C7:
|
||||
- the template owns the geometry (requisites, block titles, signatures);
|
||||
- static fields are named markers filled by fill_template_markers;
|
||||
- one dynamic works table flows across pages (w:tblHeader repeats the
|
||||
column header); no t_left/t_right split and no row-count limits;
|
||||
- money totals sit once at the end (Итого / Сумма НДС / Всего с НДС) —
|
||||
never as a page subtotal.
|
||||
|
||||
Template layout (python-docx tables):
|
||||
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/ОКДП/Договор)
|
||||
t1 Номер документа / Дата составления / Отчетный период + СПРАВКА
|
||||
t2 works table: 3-row header, form rows, data rows, «Итого» block
|
||||
t3 «Заказчик (Генподрядчик)» signatures
|
||||
t4 «Подрядчик (Субподрядчик)» signatures
|
||||
|
||||
Data columns (6): № по порядку | Наименование | Код |
|
||||
с начала проведения работ | с начала года | за отчетный период.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
from app.exporters.common import MONEY_TEXT, format_date, format_period
|
||||
from app.exporters.ks3_dto import KS3ExportDocument
|
||||
from app.exporters.word.template_markers import fill_template_markers
|
||||
from app.exporters.word.ks2_renderer import (
|
||||
_clone_row_before,
|
||||
_delete_row,
|
||||
_set_header_repeat,
|
||||
_set_tc_text,
|
||||
format_money,
|
||||
)
|
||||
|
||||
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"
|
||||
TEMPLATE_FILE = TEMPLATE_DIR / "ks3_ru_markers.docx"
|
||||
|
||||
_ROWS_MARKER = "##KS3_KS2_ROWS##"
|
||||
_TOTALS_MARKER = "##KS3_TOTALS##"
|
||||
_STORNO_MARKER = "##KS3_STORNO##"
|
||||
_ROW_MARKER = "##KS3_ROW##"
|
||||
|
||||
# Column indices inside the 6-column works table.
|
||||
_COL_NUM = 0
|
||||
_COL_NAME = 1
|
||||
_COL_CODE = 2 # always empty
|
||||
_COL_FROM_START = 3 # unsupported by KS3ExportItem
|
||||
_COL_FROM_YEAR = 4 # unsupported by KS3ExportItem
|
||||
_COL_PERIOD = 5 # amount for the reporting period
|
||||
|
||||
# Header rows of the works table that repeat on page breaks.
|
||||
_HEADER_ROWS = 3
|
||||
|
||||
|
||||
class TemplateNotFoundError(FileNotFoundError):
|
||||
"""KS-3 template resource is missing."""
|
||||
pass
|
||||
|
||||
|
||||
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 _tr(tbl, row_idx):
|
||||
return tbl.rows[row_idx]._tr
|
||||
|
||||
|
||||
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 _tcs(tbl, row_idx):
|
||||
"""Raw w:tc elements of a row (merged cells appear once)."""
|
||||
return _tr(tbl, row_idx).findall(qn("w:tc"))
|
||||
|
||||
|
||||
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 _fmt_date(value: date | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return f"{value.day:02d}.{value.month:02d}.{value.year}"
|
||||
|
||||
|
||||
def _clear_cell(cell) -> None:
|
||||
for paragraph in cell.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.text = ""
|
||||
def _split_date(value: date | None) -> tuple[str, str, str]:
|
||||
if value is None:
|
||||
return "", "", ""
|
||||
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
|
||||
|
||||
|
||||
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 = ""
|
||||
def build_ks3_template_fields(doc: KS3ExportDocument) -> dict[str, str]:
|
||||
"""Named marker values for the static KS-3 header (DOC-C4 contract).
|
||||
|
||||
Values only — layout stays in the template (ks3_ru_markers.docx).
|
||||
Fields that the official blank does not contain (e.g. `object`) are
|
||||
simply absent here and never rendered.
|
||||
"""
|
||||
h = doc.header
|
||||
day, month, year = _split_date(h.contract_date)
|
||||
raw_amount = (h.contract_amount or "").strip()
|
||||
if raw_amount:
|
||||
try:
|
||||
amount = format_money(Decimal(raw_amount))
|
||||
except Exception:
|
||||
amount = raw_amount
|
||||
else:
|
||||
paragraph.add_run(text)
|
||||
amount = ""
|
||||
return {
|
||||
"ks3_number": h.ks3_number or "",
|
||||
"ks3_date": _fmt_date(h.ks3_date),
|
||||
"contract_number": h.contract_number or "",
|
||||
"contract_date_day": day,
|
||||
"contract_date_month": month,
|
||||
"contract_date_year": year,
|
||||
"report_from": _fmt_date(h.period_from),
|
||||
"report_to": _fmt_date(h.period_to),
|
||||
"investor": h.investor_name or "",
|
||||
"customer": h.customer or h.customer_name or "",
|
||||
"contractor": h.contractor_name or "",
|
||||
"construction": h.construction_name or "",
|
||||
"contract_amount": amount,
|
||||
"contractor_signer_name": h.contractor_signer_name or "",
|
||||
"contractor_signer_position": h.contractor_signer_position or "",
|
||||
"customer_signer_name": h.customer_signer_name or "",
|
||||
"customer_signer_position": h.customer_signer_position or "",
|
||||
}
|
||||
|
||||
|
||||
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 _find_row_marker(tbl, marker: str) -> int | None:
|
||||
for ri in range(len(tbl.rows)):
|
||||
tcs = _tcs(tbl, ri)
|
||||
if not tcs:
|
||||
continue
|
||||
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||
if marker in "".join(texts):
|
||||
return ri
|
||||
return None
|
||||
|
||||
|
||||
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 _find_text_row(tbl, needle: str) -> int | None:
|
||||
for ri in range(len(tbl.rows)):
|
||||
for tc in _tcs(tbl, ri):
|
||||
texts = [t.text or "" for t in tc.iter(qn("w:t"))]
|
||||
if needle in "".join(texts):
|
||||
return ri
|
||||
return None
|
||||
|
||||
|
||||
def _fill_item_row_tr(tr, item) -> None:
|
||||
"""One KS2 line: number, factual KS2 reference, empty code/cumulative
|
||||
columns (not supported by the DTO), amount in «за отчетный период».
|
||||
"""
|
||||
tcs = tr.findall(qn("w:tc"))
|
||||
if len(tcs) < 6:
|
||||
return
|
||||
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
|
||||
ref = f"КС-2 №{item.ks2_number}" if item.ks2_number else ""
|
||||
if item.ks2_date:
|
||||
ref = f"{ref} от {_fmt_date(item.ks2_date)}" if ref else _fmt_date(item.ks2_date)
|
||||
_set_tc_text(tcs[_COL_NAME], ref, size_pt=9)
|
||||
_set_tc_text(tcs[_COL_CODE], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_FROM_START], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_FROM_YEAR], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_PERIOD], format_money(item.amount), size_pt=9, align="right")
|
||||
|
||||
|
||||
def _expand_works_table(tbl, items) -> None:
|
||||
"""Fill the single dynamic works table; clone/delete template rows as needed.
|
||||
|
||||
No page limits and no second continuation table — Word paginates the one
|
||||
table and repeats the header via w:tblHeader.
|
||||
"""
|
||||
first_data = _find_row_marker(tbl, _ROW_MARKER)
|
||||
if first_data is None:
|
||||
# fall back: first empty 6-cell row after the 3-row header
|
||||
for ri in range(_HEADER_ROWS, len(tbl.rows)):
|
||||
tcs = _tcs(tbl, ri)
|
||||
if len(tcs) == 6:
|
||||
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||
if not "".join(texts).strip():
|
||||
first_data = ri
|
||||
break
|
||||
if first_data is None:
|
||||
return
|
||||
|
||||
itogo_ri = _find_text_row(tbl, "Итого")
|
||||
if itogo_ri is None:
|
||||
return
|
||||
|
||||
needed = len(items)
|
||||
slots = itogo_ri - first_data
|
||||
template_tr = _tr(tbl, first_data)
|
||||
|
||||
# Drop unused data slots (bottom-up).
|
||||
for ri in range(itogo_ri - 1, first_data + needed - 1, -1):
|
||||
if ri >= first_data:
|
||||
_delete_row(tbl, ri)
|
||||
|
||||
# Clone extra rows before the totals block.
|
||||
totals_tr = _tr(tbl, _find_text_row(tbl, "Итого"))
|
||||
for _ in range(max(0, needed - slots)):
|
||||
_clone_row_before(tbl, template_tr, totals_tr)
|
||||
|
||||
start = _find_row_marker(tbl, _ROW_MARKER)
|
||||
if start is None:
|
||||
start = first_data
|
||||
for idx, item in enumerate(items):
|
||||
_fill_item_row_tr(_tr(tbl, start + idx), item)
|
||||
|
||||
|
||||
def _fill_totals(tbl, total) -> None:
|
||||
"""Final money totals at the very end — once, never a page subtotal."""
|
||||
ri = _find_text_row(tbl, "Итого")
|
||||
if ri is None:
|
||||
return
|
||||
tcs = _tcs(tbl, ri)
|
||||
if tcs:
|
||||
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
|
||||
# «Сумма НДС» / «Всего с учетом НДС» stay empty: VAT is not supported
|
||||
# by KS3ExportItem and must not be invented (DOC-C8 §3).
|
||||
|
||||
|
||||
def _place_storno(doc, h) -> None:
|
||||
"""Bold red СТОРНИРОВАН before the СПРАВКА title table (like KS-2)."""
|
||||
if h.status != "cancelled":
|
||||
return
|
||||
body = doc.element.body
|
||||
for child in body:
|
||||
if child.tag != qn("w:tbl"):
|
||||
continue
|
||||
texts = [t.text or "" for t in child.iter(qn("w:t"))]
|
||||
if any("СПРАВКА" in t for t in texts):
|
||||
p = body.makeelement(qn("w:p"), {})
|
||||
child.addprevious(p)
|
||||
pPr = p.makeelement(qn("w:pPr"), {})
|
||||
p.append(pPr)
|
||||
pPr.append(pPr.makeelement(qn("w:jc"), {qn("w:val"): "center"}))
|
||||
run = p.makeelement(qn("w:r"), {})
|
||||
p.append(run)
|
||||
rPr = run.makeelement(qn("w:rPr"), {})
|
||||
run.append(rPr)
|
||||
rPr.append(rPr.makeelement(qn("w:b"), {}))
|
||||
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): "FF0000"}))
|
||||
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): "28"}))
|
||||
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
|
||||
t.text = "СТОРНИРОВАН"
|
||||
run.append(t)
|
||||
break
|
||||
|
||||
|
||||
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
||||
"""Render KS-3 from a template. Returns docx bytes. No DB / no artifact writes."""
|
||||
"""Render official-form KS-3. Returns docx bytes. No DB / no artifact writes."""
|
||||
if not TEMPLATE_FILE.is_file():
|
||||
raise TemplateNotFoundError(f"KS-3 Word template not found: {TEMPLATE_FILE}")
|
||||
|
||||
document = Document(str(TEMPLATE_FILE))
|
||||
h = doc.header
|
||||
|
||||
tables = document.tables
|
||||
if len(tables) < 5:
|
||||
raise TemplateNotFoundError(
|
||||
f"KS-3 template not found: {TEMPLATE_FILE}. "
|
||||
"Add the official template to app/templates_docs/ks3/."
|
||||
f"KS-3 Word template must contain 5 tables, found {len(tables)}"
|
||||
)
|
||||
|
||||
# Work on an in-memory copy; never modify the template on disk.
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
# Static header fields: named template markers own the layout (DOC-C4).
|
||||
fields = build_ks3_template_fields(doc)
|
||||
fill_template_markers(document, fields)
|
||||
|
||||
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)
|
||||
# One dynamic works table (t2); Word paginates it naturally.
|
||||
works = tables[2]
|
||||
_expand_works_table(works, list(doc.items))
|
||||
_set_header_repeat(works, _HEADER_ROWS)
|
||||
_fill_totals(works, doc.total)
|
||||
|
||||
# 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))
|
||||
_place_storno(document, h)
|
||||
|
||||
buf = io.BytesIO()
|
||||
d.save(buf)
|
||||
document.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||
{% endif %}
|
||||
<div class="mt-2">
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">КС-3 (Word)</a>
|
||||
{% if document.status != 'draft' %}
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/artifact" class="btn btn-outline-dark btn-sm">
|
||||
📎 Официальная форма (Word)
|
||||
|
||||
Binary file not shown.
Reference in New Issue
Block a user