"""Official-form KS-3 Word renderer (DOC-C8, marker-template architecture). KS3ExportDocument -> ks3_ru_markers.docx -> generated DOCX 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 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.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_markers.docx" _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): pass 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 _fmt_date(value: date | None) -> str: if value is None: return "" return f"{value.day:02d}.{value.month:02d}.{value.year}" 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 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: 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 _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 _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 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 Word template must contain 5 tables, found {len(tables)}" ) # Static header fields: named template markers own the layout (DOC-C4). fields = build_ks3_template_fields(doc) fill_template_markers(document, fields) # 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) _place_storno(document, h) buf = io.BytesIO() document.save(buf) buf.seek(0) return buf.read()