feat: official KS-2 Excel/Word forms with template markers and single-table flow

Replace the simplified KS-2 exports with the official unified form:

- Excel: official blank as working template, merge-safe row insertion,
  compact layout, header/signer polish, 0.00 money format
- Word: official blank via named template markers (DOC-C4), one dynamic
  works table with repeating header rows, separate closing totals block
  (Итого / Всего по акту), system group rows merged across 8 columns
- Word money formatter (space thousands, comma decimals) and split
  contract date day/month/year boxes
- Issue persists both xlsx and docx artifacts; UI keeps Excel and adds
  Word download
- Daily reports: multi-system item selection in the form

Regression tests for renderers, artifacts and layout; docs/tasks +
docs/implementation for the DOC-C* series.
This commit is contained in:
Арсентьев Александр
2026-10-03 19:48:29 +03:00
parent 79c7d4f335
commit bd64bb6307
49 changed files with 6917 additions and 353 deletions
+467 -78
View File
@@ -1,96 +1,485 @@
"""Word renderer for KS-2 export using python-docx."""
"""Official-form KS-2 Word renderer.
KS2ExportDocument -> official DOCX template -> generated DOCX
Working template: app/templates_docs/ks2/ks2_ru_markers.docx
(copied from docs/templates/official/КС-2.docx via ks2_ru_v2.docx;
the original is never modified).
Static header fields (DOC-C4) are named template markers `{{name}}`:
the template owns the layout, Python only supplies data
(build_ks2_template_fields + fill_template_markers). The dynamic works
table is still filled by the code below.
Template layout (python-docx tables):
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/Объект/ОКДП/Договор)
t1 Номер документа / Дата составления / Отчетный период + АКТ
t2 Сметная (договорная) стоимость
t3 one dynamic works table (3-row header + system/item rows);
header rows repeat on page breaks via w:tblHeader
t4 closing totals block only («Итого» + «Всего по акту») after the items
t5 «Сдал» signatures
t6 «Принял» signatures
Data columns (8): № по порядку | № поз. по смете | Наименование |
Номер ед. расценки (always empty) | Ед. изм. | Количество | Цена | Стоимость.
"""
from __future__ import annotations
import io
from copy import deepcopy
from datetime import date
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 docx.oxml.ns import qn
from docx.shared import RGBColor
from app.exporters.common import MONEY_TEXT, QTY_TEXT, format_period, project_requisite_lines
from app.exporters.ks2_dto import KS2ExportDocument
from app.exporters.word.template_markers import fill_template_markers
TEMPLATE_TYPE = "ks2_word"
TEMPLATE_VERSION = 1
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_markers.docx"
class TemplateNotFoundError(FileNotFoundError):
pass
# Column indices inside the 8-column data tables.
_COL_NUM = 0
_COL_SOURCE = 1
_COL_NAME = 2
_COL_RATE = 3 # always empty
_COL_UNIT = 4
_COL_QTY = 5
_COL_PRICE = 6
_COL_AMOUNT = 7
_DATA_COLS = 8
# ---------------------------------------------------------------------------
# Formatters (Word-only; Excel keeps its own numeric formats)
# ---------------------------------------------------------------------------
def format_money(value) -> str:
"""Money: thousands = space, decimal = comma, exactly 2 digits, no currency.
Examples: 31 293,36 / 18 600 000,00 / 1 005,00
"""
if value is None or value == "":
return ""
d = Decimal(str(value)).quantize(Decimal("0.01"))
sign = "-" if d < 0 else ""
d = abs(d)
int_part, frac = f"{d:.2f}".split(".")
groups = []
while len(int_part) > 3:
groups.append(int_part[-3:])
int_part = int_part[:-3]
groups.append(int_part)
int_part = " ".join(reversed(groups))
return f"{sign}{int_part},{frac}"
def format_qty(value) -> str:
"""Quantity: ordinary number with comma decimal and exactly 2 digits (17,00)."""
if value is None or value == "":
return ""
d = Decimal(str(value)).quantize(Decimal("0.01"))
return f"{d:.2f}".replace(".", ",")
def _tr(tbl, row_idx):
return tbl.rows[row_idx]._tr
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 _set_tc_text(tc, text: str, *, bold: bool = False, size_pt: float | None = None,
color: RGBColor | None = None, align=None, no_wrap: bool = False) -> None:
"""Replace all runs of a w:tc with a single run carrying `text`.
Newlines become real OOXML line breaks (w:br).
"""
for p in tc.findall(qn("w:p")):
tc.remove(p)
p = tc.makeelement(qn("w:p"), {})
tc.append(p)
pPr = p.makeelement(qn("w:pPr"), {})
p.append(pPr)
if align is not None:
jc = pPr.makeelement(qn("w:jc"), {qn("w:val"): align})
pPr.append(jc)
if no_wrap:
tcPr = tc.find(qn("w:tcPr"))
if tcPr is None:
tcPr = tc.makeelement(qn("w:tcPr"), {})
tc.insert(0, tcPr)
if tcPr.find(qn("w:noWrap")) is None:
tcPr.append(tcPr.makeelement(qn("w:noWrap"), {}))
run = p.makeelement(qn("w:r"), {})
p.append(run)
rPr = run.makeelement(qn("w:rPr"), {})
run.append(rPr)
if bold:
rPr.append(rPr.makeelement(qn("w:b"), {}))
if size_pt is not None:
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): str(int(size_pt * 2))}))
if color is not None:
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): str(color)}))
parts = text.split("\n")
for i, part in enumerate(parts):
if i > 0:
run.append(run.makeelement(qn("w:br"), {}))
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
t.text = part
run.append(t)
def _find_row_by_text(tbl, needle: str, tc_index: int = 0) -> int | None:
for ri in range(len(tbl.rows)):
tcs = _tcs(tbl, ri)
if tc_index < len(tcs):
texts = [t.text or "" for t in tcs[tc_index].iter(qn("w:t"))]
if needle in "".join(texts):
return ri
return None
def _split_date(value: date | None) -> tuple[str, str, str]:
"""Return (day, month, year) as zero-padded strings; empty when no date."""
if value is None:
return "", "", ""
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
def _fmt_date(value: date | None) -> str:
if value is None:
return ""
return f"{value.day:02d}.{value.month:02d}.{value.year}"
def build_ks2_template_fields(doc: KS2ExportDocument) -> dict[str, str]:
"""Named marker values for the static KS-2 header (DOC-C4).
Values only — layout stays in the template (ks2_ru_markers.docx).
"""
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:
amount = ""
return {
"ks2_number": h.ks2_number or "",
"ks2_date": _fmt_date(h.ks2_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 "",
"object": h.object_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 _data_row_index(tbl) -> int | None:
"""First empty data row (after the 3-row header block, before «Итого»)."""
total_ri = _find_row_by_text(tbl, "Итого", 0)
if total_ri is None:
return None
for ri in range(3, total_ri):
tcs = _tcs(tbl, ri)
if len(tcs) == 8:
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
if not "".join(texts).strip():
return ri
return None
def _totals_row_index(tbl) -> int | None:
return _find_row_by_text(tbl, "Итого", 0)
def _grand_total_row_index(tbl) -> int | None:
return _find_row_by_text(tbl, "Всего по акту", 0)
def _delete_row(tbl, row_idx: int) -> None:
tr = _tr(tbl, row_idx)
tr.getparent().remove(tr)
def _clone_row_before(tbl, template_tr, before_tr):
new_tr = deepcopy(template_tr)
before_tr.addprevious(new_tr)
return new_tr
def _fill_data_row_tr(tr, item) -> None:
tcs = tr.findall(qn("w:tc"))
if len(tcs) < 8:
return
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
_set_tc_text(tcs[_COL_SOURCE], item.source_number or "", size_pt=9, align="center")
_set_tc_text(tcs[_COL_NAME], item.name or "", size_pt=9)
_set_tc_text(tcs[_COL_RATE], "", size_pt=9) # always empty
_set_tc_text(tcs[_COL_UNIT], item.unit or "", size_pt=9, align="center")
_set_tc_text(tcs[_COL_QTY], format_qty(item.quantity), size_pt=9, align="right")
_set_tc_text(tcs[_COL_PRICE], format_money(item.unit_price), size_pt=9, align="right")
_set_tc_text(tcs[_COL_AMOUNT], format_money(item.amount), size_pt=9, align="right")
def _merge_tr_cells(tr) -> object:
"""Merge every w:tc of a row into a single cell spanning all columns."""
tcs = tr.findall(qn("w:tc"))
if len(tcs) <= 1:
return tcs[0] if tcs else None
first = tcs[0]
tcPr = first.find(qn("w:tcPr"))
if tcPr is None:
tcPr = first.makeelement(qn("w:tcPr"), {})
first.insert(0, tcPr)
for gs in tcPr.findall(qn("w:gridSpan")):
tcPr.remove(gs)
gs = tcPr.makeelement(qn("w:gridSpan"), {qn("w:val"): str(len(tcs))})
tcPr.append(gs)
for tc in tcs[1:]:
tr.remove(tc)
return first
def _fill_group_row_tr(tr, title: str) -> None:
"""System/section divider: one merged cell across all 8 columns, bold title.
No row number — text never lands in the № column.
"""
tc = _merge_tr_cells(tr)
if tc is None:
return
_set_tc_text(tc, title, bold=True, size_pt=9, align="left")
def _group_title(code: str | None, name: str) -> str:
code = (code or "").strip()
name = name or ""
return f"{code} — {name}" if code else name
def _fill_totals(tbl, total) -> None:
ri = _totals_row_index(tbl)
if ri is None:
return
tcs = _tcs(tbl, ri)
# [5]'Итого' [1]'' [1]'Х' [1]'' → amount in the last tc
if tcs:
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
def _fill_grand_total(tbl, total) -> None:
ri = _grand_total_row_index(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")
def _delete_intermediate_totals(tbl) -> None:
"""Remove the intermediate «Итого» row (page subtotal) from a data table.
Only the final «Итого» / «Всего по акту» at the very end of the document
may show money totals (DOC-C6).
"""
ri = _totals_row_index(tbl)
if ri is not None:
_delete_row(tbl, ri)
def _set_header_repeat(tbl, n_header_rows: int) -> None:
"""Mark the first rows as a repeating Word header (w:tblHeader).
Word then repeats them automatically when the single works table
flows onto the next page (DOC-C7).
"""
for ri in range(min(n_header_rows, len(tbl.rows))):
tr = _tr(tbl, ri)
trPr = tr.find(qn("w:trPr"))
if trPr is None:
trPr = tr.makeelement(qn("w:trPr"), {})
tr.insert(0, trPr)
if trPr.find(qn("w:tblHeader")) is None:
trPr.append(trPr.makeelement(qn("w:tblHeader"), {}))
def _to_totals_block(tbl, total) -> None:
"""Turn a second data table into a standalone totals block (DOC-C7).
Keeps only the «Итого» and «Всего по акту» rows (already formatted like
the works table) and drops the copied header/data rows — this is not a
continuation table, just the closing money block after the last item.
"""
keep: set[int] = set()
ri_itogo = _totals_row_index(tbl)
ri_vsyo = _grand_total_row_index(tbl)
if ri_itogo is not None:
keep.add(ri_itogo)
if ri_vsyo is not None:
keep.add(ri_vsyo)
# delete every row except the totals rows (bottom-up so indices stay valid)
for ri in range(len(tbl.rows) - 1, -1, -1):
if ri not in keep:
_delete_row(tbl, ri)
_fill_totals(tbl, total)
_fill_grand_total(tbl, total)
def _place_storno(doc, h) -> None:
"""Bold red СТОРНИРОВАН as a body paragraph right before the АКТ title table.
Does not touch any table structure.
"""
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 _expand_data_table(tbl, items, group_headers=None):
"""Fill data rows of a table; clone/delete template rows as needed.
`group_headers` maps id(item) -> (code, name) or a plain string.
Returns the number of item rows written.
"""
first_data = _data_row_index(tbl)
total_ri = _totals_row_index(tbl)
if first_data is None or total_ri is None:
return 0
# Build the sequence: optional group header rows + item rows.
sequence = []
for item in items:
gh = group_headers.get(id(item)) if group_headers else None
if gh:
sequence.append(("group", gh))
sequence.append(("item", item))
if not sequence:
sequence = []
template_tr = _tr(tbl, first_data)
# current number of data slots
slots = total_ri - first_data
needed = len(sequence)
# Delete unused slots (bottom-up).
for ri in range(total_ri - 1, first_data + needed - 1, -1):
if ri >= first_data:
_delete_row(tbl, ri)
# Insert extra clones before the totals row.
totals_tr = _tr(tbl, _totals_row_index(tbl))
for _ in range(max(0, needed - slots)):
_clone_row_before(tbl, template_tr, totals_tr)
# Fill.
data_start = _data_row_index(tbl)
for idx, (kind, payload) in enumerate(sequence):
tr = _tr(tbl, data_start + idx)
if kind == "group":
if isinstance(payload, tuple):
title = _group_title(payload[0], payload[1])
else:
title = str(payload)
_fill_group_row_tr(tr, title)
else:
_fill_data_row_tr(tr, payload)
return sum(1 for k, _ in sequence if k == "item")
def render_ks2_word(doc: KS2ExportDocument) -> bytes:
d = Document()
if not TEMPLATE_FILE.is_file():
raise TemplateNotFoundError(f"KS-2 Word template not found: {TEMPLATE_FILE}")
document = Document(str(TEMPLATE_FILE))
h = doc.header
section = d.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
tables = document.tables
if len(tables) < 7:
raise TemplateNotFoundError(
f"KS-2 Word template must contain 7 tables, found {len(tables)}"
)
# Title
title = d.add_paragraph()
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = title.add_run(f"Акт КС-2 №{h.ks2_number} от {h.ks2_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=7)
table.style = "Table Grid"
table.alignment = WD_TABLE_ALIGNMENT.CENTER
columns = ["№", "Наименование работ", "№ поз. в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
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)
# Static header fields: named template markers own the layout (DOC-C4).
fields = build_ks2_template_fields(doc)
fill_template_markers(document, fields)
# Group headers keyed by item identity (from DTO): (code, name).
group_headers: dict[int, tuple] = {}
for item in doc.items:
row = table.add_row()
row.cells[0].text = str(item.row_number)
row.cells[1].text = item.name
row.cells[2].text = item.source_number
row.cells[3].text = item.unit
row.cells[4].text = QTY_TEXT.format(item.quantity)
row.cells[5].text = MONEY_TEXT.format(item.unit_price)
row.cells[6].text = MONEY_TEXT.format(item.amount)
gh = getattr(item, "group_header", None)
if gh:
group_headers[id(item)] = (
getattr(item, "group_code", None) or "",
gh,
)
# Total row
total_row = table.add_row()
total_row.cells[0].merge(total_row.cells[5])
total_row.cells[0].text = "Итого:"
for paragraph in total_row.cells[0].paragraphs:
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
for run in paragraph.runs:
run.bold = True
total_row.cells[6].text = MONEY_TEXT.format(doc.total)
for paragraph in total_row.cells[6].paragraphs:
for run in paragraph.runs:
run.bold = True
items = list(doc.items)
# DOC-C7: one dynamic works table for every item and system row. Word
# flows it across pages on its own; the header repeats via w:tblHeader.
# No t3/t4 split, no per-page row limits.
_expand_data_table(tables[3], items, group_headers)
_set_header_repeat(tables[3], 3)
# The «Итого» template row of the works table is a page-subtotal slot —
# money totals live only in the separate closing block (DOC-C6).
_delete_intermediate_totals(tables[3])
# t4 used to be a second data table (page 2). It is now only the closing
# totals block: «Итого» + «Всего по акту» after the last position.
_to_totals_block(tables[4], doc.total)
_place_storno(document, h)
buf = io.BytesIO()
d.save(buf)
document.save(buf)
buf.seek(0)
return buf.read()