feat: add template-based KS-2 Excel and KS-3 Word renderers

This commit is contained in:
Арсентьев Александр
2026-09-29 17:50:58 +03:00
parent cddde114fe
commit e66bce0d25
12 changed files with 1643 additions and 176 deletions
+356
View File
@@ -0,0 +1,356 @@
"""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()
+325
View File
@@ -0,0 +1,325 @@
"""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())
+2 -2
View File
@@ -138,7 +138,7 @@ def test_ks2_excel_export_key_values(tmp_path):
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
assert resp.status_code == 200
_, _, text = _excel_text(resp)
assert "Акт КС-2 №7" in text
assert "КС-2 № 7" in text
assert "Export polish" in text
assert "Заказчик ООО" in text
assert "DOG-2026-7" in text
@@ -191,7 +191,7 @@ def test_ks3_export_key_values(tmp_path):
word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word")
assert word.status_code == 200
_, wtext = _word_text(word)
assert "Акт КС-3 №3" in wtext
assert "КС-3 № 3" in wtext
assert "500.00" in wtext
finally:
_clear()