"""Tests for KS-3 official-form Word renderer (DOC-B4 + DOC-C8). Marker-template architecture (DOC-C4–DOC-C7): static fields via named markers, one dynamic works table with natural pagination and repeating header, final totals only at the end. """ from __future__ import annotations import hashlib import io from datetime import date from decimal import Decimal from pathlib import Path import pytest from docx import Document from docx.oxml.ns import qn from app.exporters.ks3_dto import KS3ExportDocument, KS3ExportHeader, KS3ExportItem from app.exporters.word.ks3_renderer import ( TEMPLATE_FILE, TEMPLATE_TYPE, TEMPLATE_VERSION, TemplateNotFoundError, build_ks3_template_fields, render_ks3_word, ) def _dto(items=None, total=None, status="issued"): header = KS3ExportHeader( project_name="Тестовый проект", customer="Заказчик", contract_number="Д-1", contract_date=date(2026, 1, 10), currency="RUB", ks3_number="К3-1", ks3_date=date(2026, 3, 1), period_from=date(2026, 2, 1), period_to=date(2026, 2, 28), comment="Комментарий", status=status, investor_name="ООО Инвестор", customer_name="Заказчик", contractor_name="Подрядчик", construction_name="Стройка — коттеджный посёлок", object_name="Жилой дом", contract_amount="18600000", contractor_signer_position="Директор", contractor_signer_name="Иванов И.И.", customer_signer_position="Начальник УКС", customer_signer_name="Петров П.П.", ) if items is None: items = [ KS3ExportItem( row_number=1, ks2_number="К2-1", ks2_date=date(2026, 2, 1), period_from=date(2026, 2, 1), period_to=date(2026, 2, 28), amount=Decimal("100.50"), ) ] if total is None: total = sum((i.amount for i in items), Decimal("0")) return KS3ExportDocument(header=header, items=items, total=total) def _item(n, amount="100.50"): return KS3ExportItem( row_number=n, ks2_number=f"К2-{n}", ks2_date=date(2026, 2, 1), period_from=date(2026, 2, 1), period_to=date(2026, 2, 28), amount=Decimal(amount), ) def _open(data: bytes): return Document(io.BytesIO(data)) def _raw_row(tbl, ri): tr = tbl.rows[ri]._tr return ["".join(t.text or "" for t in tc.iter(qn("w:t"))) for tc in tr.findall(qn("w:tc"))] def _doc_text(document) -> str: parts = [p.text for p in document.paragraphs] for table in document.tables: for row in table.rows: parts.extend(c.text for c in row.cells) return "\n".join(parts) def _works_table(d): # t2 is the only dynamic works table return d.tables[2] def _item_rows(tbl): """Numeric № rows with 6 cells (not the 1..6 column-number header).""" out = [] for ri in range(len(tbl.rows)): row = _raw_row(tbl, ri) if len(row) == 6 and row[0].isdigit(): if row[1] == "2" and row[2] == "3": continue out.append((ri, row)) return out # --------------------------------------------------------------------------- # Template # --------------------------------------------------------------------------- def test_template_exists(): assert TEMPLATE_FILE.is_file() assert TEMPLATE_FILE.suffix == ".docx" assert "markers" in TEMPLATE_FILE.name def test_template_type_and_version(): assert TEMPLATE_TYPE == "ks3" assert TEMPLATE_VERSION == 1 def test_markers_present_in_working_template(): d = Document(str(TEMPLATE_FILE)) text = _doc_text(d) for marker in ( "{{ks3_number}}", "{{ks3_date}}", "{{investor}}", "{{customer}}", "{{contractor}}", "{{construction}}", "{{contract_number}}", "{{contract_date_day}}", "{{contract_date_month}}", "{{contract_date_year}}", "{{report_from}}", "{{report_to}}", "{{contractor_signer_name}}", "{{contractor_signer_position}}", "{{customer_signer_name}}", "{{customer_signer_position}}", "##KS3_ROW##", ): assert marker in text, marker # the official KS-3 blank has no contract-amount line (unlike KS-2) assert "{{contract_amount}}" not in text def test_missing_template_raises(monkeypatch): monkeypatch.setattr( "app.exporters.word.ks3_renderer.TEMPLATE_FILE", Path("/nonexistent/ks3_ru_markers.docx"), ) with pytest.raises(TemplateNotFoundError): render_ks3_word(_dto()) # --------------------------------------------------------------------------- # Markers replaced # --------------------------------------------------------------------------- def test_markers_are_replaced(): d = _open(render_ks3_word(_dto())) text = _doc_text(d) assert "{{" not in text assert "##" not in text def test_number_and_dates_in_place(): d = _open(render_ks3_word(_dto())) t1 = d.tables[1] r2 = _raw_row(t1, 2) assert "К3-1" in r2[1] assert "01.03.2026" in r2[2] assert "01.02.2026" in r2[4] assert "28.02.2026" in r2[5] def test_contract_date_split_day_month_year(): d = _open(render_ks3_word(_dto())) t0 = d.tables[0] for ri in range(len(t0.rows)): row = _raw_row(t0, ri) if "дата" in row: boxes = row[row.index("дата") + 1:] assert boxes[:3] == ["10", "01", "2026"], boxes break else: pytest.fail("дата row not found") def test_header_requisites(): d = _open(render_ks3_word(_dto())) text = _doc_text(d) assert "0322001" in text assert "ООО Инвестор" in text assert "Заказчик" in text assert "Подрядчик" in text assert "Стройка — коттеджный посёлок" in text assert "Д-1" in text def test_build_fields_money_format(): fields = build_ks3_template_fields(_dto()) assert fields["contract_amount"] == "18 600 000,00" assert fields["ks3_number"] == "К3-1" # --------------------------------------------------------------------------- # Money # --------------------------------------------------------------------------- def test_money_formatter(): from app.exporters.word.ks3_renderer import format_money assert format_money(Decimal("31293.36")) == "31 293,36" assert format_money(Decimal("18600000")) == "18 600 000,00" assert format_money(Decimal("1005")) == "1 005,00" def test_no_dot_decimal_or_currency(): text = _doc_text(_open(render_ks3_word(_dto()))) assert "100.50" not in text assert "₽" not in text assert "RUB" not in text # --------------------------------------------------------------------------- # One KS2 / several KS2 / summation # --------------------------------------------------------------------------- def test_single_ks2(): d = _open(render_ks3_word(_dto([_item(1, "31293.36")], total=Decimal("31293.36")))) rows = _item_rows(_works_table(d)) assert len(rows) == 1 assert rows[0][1][0] == "1" assert "КС-2 №К2-1" in rows[0][1][1] assert rows[0][1][5] == "31 293,36" def test_multiple_ks2_presented_once_each(): items = [_item(i) for i in range(1, 4)] d = _open(render_ks3_word(_dto(items, total=Decimal("301.50")))) rows = _item_rows(_works_table(d)) assert [r[1][0] for r in rows] == ["1", "2", "3"] assert [f"КС-2 №К2-{i}" in r[1][1] for r, i in zip(rows, range(1, 4))] == [True, True, True] def test_summation_matches_dto_total(): items = [_item(i, "1000") for i in range(1, 6)] d = _open(render_ks3_word(_dto(items, total=Decimal("5000")))) t = _works_table(d) itogo = [ri for ri in range(len(t.rows)) if "Итого" in _raw_row(t, ri)[0]] assert len(itogo) == 1 assert _raw_row(t, itogo[0])[-1] == "5 000,00" def test_renderer_does_not_recompute_total(): items = [_item(1, "100")] d = _open(render_ks3_word(_dto(items, total=Decimal("999.00")))) t = _works_table(d) itogo = next(ri for ri in range(len(t.rows)) if "Итого" in _raw_row(t, ri)[0]) assert _raw_row(t, itogo)[-1] == "999,00" # --------------------------------------------------------------------------- # DOC-C8: one dynamic table, no page subtotals # --------------------------------------------------------------------------- def test_single_dynamic_table_no_continuation(): items = [_item(i) for i in range(1, 21)] d = _open(render_ks3_word(_dto(items, total=Decimal("20100")))) t = _works_table(d) assert len(_item_rows(t)) == 20 # no other table contains item rows for ti, other in enumerate(d.tables): if ti == 2: continue assert _item_rows(other) == [], f"t{ti} has item rows" def test_no_intermediate_page_subtotal(): items = [_item(i) for i in range(1, 21)] d = _open(render_ks3_word(_dto(items, total=Decimal("20100")))) text = _doc_text(d) # exactly one Итого (final), no page subtotal copies assert sum(1 for t in d.tables for row in t.rows if "Итого" in row.cells[0].text and "Всего" not in row.cells[0].text) == 1 def test_final_totals_once_at_end(): items = [_item(i) for i in range(1, 16)] d = _open(render_ks3_word(_dto(items, total=Decimal("15075")))) t = _works_table(d) rows = [_raw_row(t, ri) for ri in range(len(t.rows))] itogo = [i for i, r in enumerate(rows) if "Итого" in r[0] and "Всего" not in r[0]] assert len(itogo) == 1 # Итого is after the last item last_item = max(i for i, r in enumerate(rows) if len(r) == 6 and r[0].isdigit()) assert itogo[0] > last_item assert rows[itogo[0]][-1] == "15 075,00" # НДС rows exist in the official blank but stay empty (not supported) nds = [r for r in rows if "НДС" in r[0]] assert nds, "official blank has VAT rows" for r in nds: assert r[-1] == "" def test_header_repeat_on_works_table(): d = _open(render_ks3_word(_dto([_item(i) for i in range(1, 6)]))) t = _works_table(d) for ri in range(3): trPr = t.rows[ri]._tr.find(qn("w:trPr")) assert trPr is not None assert trPr.find(qn("w:tblHeader")) is not None, f"r{ri} lacks tblHeader" # --------------------------------------------------------------------------- # Signatures after totals / storno # --------------------------------------------------------------------------- def test_signatures_after_totals(): d = _open(render_ks3_word(_dto([_item(1)]))) # t2 works, t3 Заказчик, t4 Подрядчик assert "Заказчик (Генподрядчик)" in _raw_row(d.tables[3], 0)[0] assert "Подрядчик (Субподрядчик)" in _raw_row(d.tables[4], 0)[0] t2_last = len(_works_table(d).rows) - 1 assert "НДС" in _raw_row(_works_table(d), t2_last)[0] or "Всего" in _raw_row(_works_table(d), t2_last)[0] def test_signers_filled(): d = _open(render_ks3_word(_dto())) t3 = _raw_row(d.tables[3], 0) t4 = _raw_row(d.tables[4], 0) assert t3[1] == "Начальник УКС" assert t3[5] == "Петров П.П." assert t4[1] == "Директор" assert t4[5] == "Иванов И.И." def test_cancelled_has_storno(): d = _open(render_ks3_word(_dto(status="cancelled"))) text = _doc_text(d) assert "СТОРНИРОВАН" in text def test_issued_no_storno(): d = _open(render_ks3_word(_dto(status="issued"))) assert "СТОРНИРОВАН" not in _doc_text(d) # --------------------------------------------------------------------------- # Output stability # --------------------------------------------------------------------------- def test_returns_bytes_and_opens(): data = render_ks3_word(_dto()) assert isinstance(data, bytes) d = _open(data) assert len(d.tables) == 5 def test_template_not_modified(): before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest() render_ks3_word(_dto()) render_ks3_word(_dto(status="cancelled")) after = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest() assert before == after def test_rerender_stable(): dto = _dto() a = _open(render_ks3_word(dto)) b = _open(render_ks3_word(dto)) for ti in range(len(a.tables)): ta, tb = a.tables[ti], b.tables[ti] assert len(ta.rows) == len(tb.rows) for ri in range(len(ta.rows)): assert _raw_row(ta, ri) == _raw_row(tb, ri) def test_zero_rows_no_fake_position(): d = _open(render_ks3_word(_dto(items=[], total=Decimal("0")))) assert _item_rows(_works_table(d)) == [] text = _doc_text(d) assert "{{" not in text def test_compatible_with_artifact_service(tmp_path, monkeypatch): from app.services.document_artifact_service import ( compute_content_hash, persist_artifact, resolve_artifact, ) from app.config import ENV_DOCUMENT_STORAGE_ROOT from app.database.database import Base from app.models import ( # noqa: F401 agreement, boq, daily_report, document_artifact, ks2, ks3, payment, project, work_journal, ) from app.models.project import Project from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.pool import StaticPool monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "storage")) engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool) Base.metadata.create_all(engine) Session = sessionmaker(bind=engine, expire_on_commit=False) db = Session() p = Project(name="C8 integ") db.add(p) db.commit() content = render_ks3_word(_dto()) art = persist_artifact( db, project_id=p.id, document_type="KS3", document_id=1, format="docx", template_type=TEMPLATE_TYPE, template_version=TEMPLATE_VERSION, content=content, dto=_dto(), ) db.commit() assert art.template_type == TEMPLATE_TYPE assert art.template_version == TEMPLATE_VERSION assert art.content_hash == compute_content_hash(content) resolved, body = resolve_artifact( db, project_id=p.id, document_type="KS3", document_id=1, format="docx" ) assert body == content db.close() engine.dispose()