"""Tests for DOC-B3: template-based KS-2 Excel 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 openpyxl import load_workbook from app.exporters.ks2_dto import KS2ExportDocument, KS2ExportHeader, KS2ExportItem from app.exporters.excel.ks2_renderer import ( MANIFEST_FILE, TEMPLATE_FILE, TEMPLATE_TYPE, TEMPLATE_VERSION, TemplateNotFoundError, load_template_manifest, render_ks2_excel, ) def _dto(items=None, total=None, status="issued"): header = KS2ExportHeader( project_name="Тестовый проект", customer="Заказчик", contract_number="Д-1", contract_date=date(2026, 1, 10), currency="RUB", ks2_number="К2-1", ks2_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 = [ KS2ExportItem( row_number=1, source_number="1", name="Монтаж трубы", unit="м", quantity=Decimal("12.5"), unit_price=Decimal("482.42"), amount=Decimal("6030.25"), ) ] if total is None: total = sum((i.amount for i in items), Decimal("0")) return KS2ExportDocument(header=header, items=items, total=total) def _open(data: bytes): return load_workbook(io.BytesIO(data)) # --------------------------------------------------------------------------- # Template # --------------------------------------------------------------------------- def test_template_exists(): assert TEMPLATE_FILE.is_file() assert TEMPLATE_FILE.suffix == ".xlsx" 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"] == "##KS2_ROWS##" assert manifest["totals_marker"] == "##KS2_TOTALS##" assert manifest["storno_marker"] == "##KS2_STORNO##" assert "project_name" in manifest["placeholders"] def test_renderer_opens_template(): wb = _open(render_ks2_excel(_dto())) assert "КС-2" in wb.sheetnames or wb.active is not None # --------------------------------------------------------------------------- # Header # --------------------------------------------------------------------------- def test_header_number_date_period_requisites(): data = render_ks2_excel(_dto()) ws = _open(data).active text = " | ".join( str(c.value) for row in ws.iter_rows() for c in row if c.value is not None ) assert "К2-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 _find_rows_block(ws): """Return row indexes of the dynamic item table (between header and totals).""" start = None end = None for r in range(1, ws.max_row + 1): a = ws.cell(r, 1).value b = ws.cell(r, 2).value if a == "№" and b == "Наименование работ": start = r + 1 if a == "Итого:": end = r assert start is not None, "table header not found" assert end is not None and end > start, "totals row not found" rows = [] for r in range(start, end): a = ws.cell(r, 1).value b = ws.cell(r, 2).value if a is None and b is None: continue rows.append(r) return rows def test_single_row(): data = render_ks2_excel(_dto()) ws = _open(data).active rows = _find_rows_block(ws) assert len(rows) == 1 assert ws.cell(rows[0], 2).value == "Монтаж трубы" assert ws.cell(rows[0], 3).value == "1" assert ws.cell(rows[0], 4).value == "м" def test_multiple_rows_match_dto(): items = [ KS2ExportItem(1, "1", "Первая", "шт", Decimal("1"), Decimal("10"), Decimal("10")), KS2ExportItem(2, "2", "Вторая", "м", Decimal("2"), Decimal("20"), Decimal("40")), KS2ExportItem(3, "3", "Третья", "т", Decimal("3"), Decimal("30"), Decimal("90")), ] data = render_ks2_excel(_dto(items=items)) ws = _open(data).active rows = _find_rows_block(ws) assert len(rows) == 3 names = [ws.cell(r, 2).value for r in rows] assert names == ["Первая", "Вторая", "Третья"] assert [ws.cell(r, 3).value for r in rows] == ["1", "2", "3"] def test_source_number_displayed(): item = KS2ExportItem(1, "BOQ-77", "X", "шт", Decimal("1"), Decimal("1"), Decimal("1")) data = render_ks2_excel(_dto(items=[item])) ws = _open(data).active rows = _find_rows_block(ws) assert ws.cell(rows[0], 3).value == "BOQ-77" def test_numeric_excel_cells(): item = KS2ExportItem(1, "1", "X", "шт", Decimal("12.50"), Decimal("482.42"), Decimal("6030.25")) data = render_ks2_excel(_dto(items=[item])) ws = _open(data).active rows = _find_rows_block(ws) for col in (5, 6, 7): value = ws.cell(rows[0], col).value assert isinstance(value, (int, float)), f"col {col} is {type(value)}" # number format set assert ws.cell(rows[0], col).number_format not in ("General", "0") def test_decimal_not_float_before_write(): # openpyxl stores Decimal as a number; we assert the precision survives # for a value that is not exactly representable as float. item = KS2ExportItem(1, "1", "X", "шт", Decimal("0.1"), Decimal("0.2"), Decimal("0.3")) data = render_ks2_excel(_dto(items=[item], total=Decimal("0.3"))) ws = _open(data).active rows = _find_rows_block(ws) qty = ws.cell(rows[0], 5).value # 0.1 as float is 0.1000000000000000055…; allow tiny float noise but keep value assert abs(float(qty) - 0.1) < 1e-9 assert isinstance(qty, (int, float)) def test_styles_preserved(): item = KS2ExportItem(1, "1", "X", "шт", Decimal("1"), Decimal("1"), Decimal("1")) data = render_ks2_excel(_dto(items=[item])) ws = _open(data).active rows = _find_rows_block(ws) # cells have borders like the template row assert ws.cell(rows[0], 2).border.left.style is not None assert ws.cell(rows[0], 7).number_format != "General" def test_zero_rows_no_fake_position(): data = render_ks2_excel(_dto(items=[], total=Decimal("0"))) ws = _open(data).active rows = _find_rows_block(ws) # exactly one placeholder row, marked with dashes assert len(rows) == 1 assert ws.cell(rows[0], 2).value == "—" assert ws.cell(rows[0], 1).value == "—" # no numeric position content assert ws.cell(rows[0], 3).value == "—" # --------------------------------------------------------------------------- # Totals # --------------------------------------------------------------------------- def test_total_from_dto(): items = [ KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("100"), Decimal("100")), KS2ExportItem(2, "2", "B", "шт", Decimal("2"), Decimal("50"), Decimal("100")), ] data = render_ks2_excel(_dto(items=items, total=Decimal("200.00"))) ws = _open(data).active # Find "Итого:" total_cell = None for row in ws.iter_rows(): for cell in row: if cell.value == "Итого:": total_cell = ws.cell(cell.row, 7).value assert total_cell is not None assert abs(float(total_cell) - 200.0) < 1e-9 def test_renderer_does_not_recompute_total(): items = [ KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("1"), Decimal("1")), ] # Deliberately inconsistent total: renderer must show DTO total, not 1. data = render_ks2_excel(_dto(items=items, total=Decimal("999.00"))) ws = _open(data).active for row in ws.iter_rows(): for cell in row: if cell.value == "Итого:": assert abs(float(ws.cell(cell.row, 7).value) - 999.0) < 1e-9 # --------------------------------------------------------------------------- # Storno # --------------------------------------------------------------------------- def test_cancelled_output_has_storno_marker(): data = render_ks2_excel(_dto(status="cancelled")) ws = _open(data).active text = " | ".join( str(c.value) for row in ws.iter_rows() for c in row if c.value is not None ) assert "СТОРНИРОВАН" in text def test_issued_output_has_no_storno(): data = render_ks2_excel(_dto(status="issued")) ws = _open(data).active text = " | ".join( str(c.value) for row in ws.iter_rows() for c in row if c.value is not None ) assert "СТОРНИРОВАН" not in text assert "##KS2_STORNO##" not in text def test_template_not_modified(): before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest() render_ks2_excel(_dto()) render_ks2_excel(_dto(status="cancelled")) after = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest() assert before == after # --------------------------------------------------------------------------- # Output # --------------------------------------------------------------------------- def test_returns_bytes(): assert isinstance(render_ks2_excel(_dto()), bytes) def test_result_opens_as_xlsx(): data = render_ks2_excel(_dto()) wb = load_workbook(io.BytesIO(data)) ws = wb.active assert ws.max_row >= 13 def test_rerender_stable(): dto = _dto() a = render_ks2_excel(dto) b = render_ks2_excel(dto) # Same DTO + same template -> identical output assert a == b def test_missing_template_raises(monkeypatch): monkeypatch.setattr( "app.exporters.excel.ks2_renderer.TEMPLATE_FILE", Path("/nonexistent/ks2_ru_v1.xlsx"), ) with pytest.raises(TemplateNotFoundError): render_ks2_excel(_dto()) # --------------------------------------------------------------------------- # B2 integration shape # --------------------------------------------------------------------------- def test_compatible_with_artifact_service(tmp_path, monkeypatch): from app.services.document_artifact_service import ( compute_content_hash, compute_input_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="B2 integ") db.add(p) db.commit() content = render_ks2_excel(_dto()) art = persist_artifact( db, project_id=p.id, document_type="ks2", document_id=1, format="xlsx", 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="ks2", document_id=1, format="xlsx" ) assert body == content db.close() engine.dispose()