"""Tests for DOC-B4: template-based KS-3 Word renderer.""" from __future__ import annotations import hashlib import io import json from datetime import date from decimal import Decimal from pathlib import Path import pytest from docx import Document from app.exporters.ks3_dto import KS3ExportDocument, KS3ExportHeader, KS3ExportItem from app.exporters.word.ks3_renderer import ( MANIFEST_FILE, TEMPLATE_FILE, TEMPLATE_TYPE, TEMPLATE_VERSION, TemplateNotFoundError, load_template_manifest, 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, ) 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 _open(data: bytes): return Document(io.BytesIO(data)) 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 _table_rows(document): """Return rows of the main KS-2 table as lists of cell texts.""" for table in document.tables: for row in table.rows: if "КС-2" in [c.text for c in row.cells]: return [[c.text for c in r.cells] for r in table.rows] raise AssertionError("KS-2 table not found") # --------------------------------------------------------------------------- # Template # --------------------------------------------------------------------------- def test_template_exists(): assert TEMPLATE_FILE.is_file() assert TEMPLATE_FILE.suffix == ".docx" def test_manifest_valid(): manifest = load_template_manifest() assert manifest["template_type"] == TEMPLATE_TYPE assert manifest["template_version"] == TEMPLATE_VERSION assert manifest["file"] == TEMPLATE_FILE.name assert manifest["table_marker"] == "##KS3_KS2_ROWS##" assert manifest["totals_marker"] == "##KS3_TOTALS##" assert manifest["storno_marker"] == "##KS3_STORNO##" def test_template_opens_with_python_docx(): d = Document(str(TEMPLATE_FILE)) assert len(d.paragraphs) > 0 assert len(d.tables) > 0 # --------------------------------------------------------------------------- # Header # --------------------------------------------------------------------------- def test_header_number_date_period_requisites(): data = render_ks3_word(_dto()) text = _doc_text(_open(data)) assert "К3-1" in text assert "01.03.2026" in text assert "01.02.2026 — 28.02.2026" in text assert "Тестовый проект" in text assert "Заказчик" in text assert "Д-1" in text assert "10.01.2026" in text assert "RUB" in text assert "Комментарий" in text # --------------------------------------------------------------------------- # Rows # --------------------------------------------------------------------------- def test_single_ks2_row(): data = render_ks3_word(_dto()) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] assert len(data_rows) == 1 assert data_rows[0][1] == "№К2-1" assert data_rows[0][2] == "01.02.2026" def test_multiple_ks2_rows(): items = [ KS3ExportItem(1, "К2-1", date(2026, 2, 1), date(2026, 2, 1), date(2026, 2, 28), Decimal("100")), KS3ExportItem(2, "К2-2", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("200")), KS3ExportItem(3, "К2-3", date(2026, 2, 28), date(2026, 2, 1), date(2026, 2, 28), Decimal("300")), ] data = render_ks3_word(_dto(items=items)) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] assert len(data_rows) == 3 assert [r[1] for r in data_rows] == ["№К2-1", "№К2-2", "№К2-3"] def test_row_count_matches_dto(): items = [ KS3ExportItem(i, f"К2-{i}", date(2026, 2, i), None, None, Decimal(str(i * 10))) for i in range(1, 6) ] data = render_ks3_word(_dto(items=items)) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] assert len(data_rows) == 5 def test_numbers_dates_periods_displayed(): item = KS3ExportItem(1, "К2-9", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("123.45")) data = render_ks3_word(_dto(items=[item])) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] assert data_rows[0][1] == "№К2-9" assert data_rows[0][2] == "15.02.2026" assert data_rows[0][3] == "01.02.2026 — 28.02.2026" assert data_rows[0][4] == "123.45" def test_money_uses_formatter(): item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1234.5")) data = render_ks3_word(_dto(items=[item])) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] # MONEY_TEXT format is "{:.2f}" assert data_rows[0][4] == "1234.50" def test_decimal_not_via_float(): # Values that are not exact in binary floating point item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("0.10")) data = render_ks3_word(_dto(items=[item], total=Decimal("0.30"))) text = _doc_text(_open(data)) assert "0.10" in text assert "0.30" in text def test_formatting_preserved(): data = render_ks3_word(_dto()) d = _open(data) rows = _table_rows(d) # Table Grid style preserved table = d.tables[0] assert table.style.name == "Table Grid" def test_zero_rows_no_fake_position(): data = render_ks3_word(_dto(items=[], total=Decimal("0"))) rows = _table_rows(_open(data)) data_rows = [r for r in rows if r[0] not in ("№", "Итого:")] assert len(data_rows) == 1 assert data_rows[0][0] == "—" assert data_rows[0][1] == "—" # --------------------------------------------------------------------------- # Totals # --------------------------------------------------------------------------- def test_total_from_dto(): items = [ KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("100")), KS3ExportItem(2, "К2-2", date(2026, 2, 2), None, None, Decimal("100")), ] data = render_ks3_word(_dto(items=items, total=Decimal("200.00"))) rows = _table_rows(_open(data)) total_row = next(r for r in rows if "Итого:" in r[0]) assert total_row[4] == "200.00" def test_renderer_does_not_recompute_total(): items = [KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1.00"))] data = render_ks3_word(_dto(items=items, total=Decimal("999.00"))) rows = _table_rows(_open(data)) total_row = next(r for r in rows if "Итого:" in r[0]) assert total_row[4] == "999.00" # --------------------------------------------------------------------------- # Storno # --------------------------------------------------------------------------- def test_cancelled_output_has_storno(): data = render_ks3_word(_dto(status="cancelled")) text = _doc_text(_open(data)) assert "СТОРНИРОВАН" in text def test_issued_output_has_no_storno(): data = render_ks3_word(_dto(status="issued")) text = _doc_text(_open(data)) assert "СТОРНИРОВАН" not in text assert "##KS3_STORNO##" not in text 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 # --------------------------------------------------------------------------- # Output / B2 # --------------------------------------------------------------------------- def test_returns_bytes(): assert isinstance(render_ks3_word(_dto()), bytes) def test_result_opens_with_python_docx(): data = render_ks3_word(_dto()) d = _open(data) assert len(d.tables) > 0 def test_rerender_stable(): dto = _dto() a = _open(render_ks3_word(dto)) b = _open(render_ks3_word(dto)) # python-docx embeds ZIP timestamps, so bytes may differ; # extracted text content must be identical. assert _doc_text(a) == _doc_text(b) assert _table_rows(a) == _table_rows(b) def test_compatible_with_artifact_service(tmp_path, monkeypatch): 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 app.services.document_artifact_service import ( compute_content_hash, persist_artifact, resolve_artifact, ) 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) db = sessionmaker(bind=engine, expire_on_commit=False)() p = Project(name="B4 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() def test_missing_template_raises(monkeypatch): monkeypatch.setattr( "app.exporters.word.ks3_renderer.TEMPLATE_FILE", Path("/nonexistent/ks3_ru_v1.docx"), ) with pytest.raises(TemplateNotFoundError): render_ks3_word(_dto())