feat: official KS-2 Excel/Word forms with template markers and single-table flow
Replace the simplified KS-2 exports with the official unified form: - Excel: official blank as working template, merge-safe row insertion, compact layout, header/signer polish, 0.00 money format - Word: official blank via named template markers (DOC-C4), one dynamic works table with repeating header rows, separate closing totals block (Итого / Всего по акту), system group rows merged across 8 columns - Word money formatter (space thousands, comma decimals) and split contract date day/month/year boxes - Issue persists both xlsx and docx artifacts; UI keeps Excel and adds Word download - Daily reports: multi-system item selection in the form Regression tests for renderers, artifacts and layout; docs/tasks + docs/implementation for the DOC-C* series.
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
"""DOC-C5: one Daily Report can hold positions of several systems.
|
||||
|
||||
Regression tests for the bug where, after adding a position of the first
|
||||
system, positions of other systems stopped loading (and added positions
|
||||
disappeared when switching the selected system).
|
||||
"""
|
||||
import re
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.database.database import Base
|
||||
from app.main import app
|
||||
from app.models.project import Project
|
||||
from app.models.boq import BoqDocument, System, Section, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.routers import daily_reports
|
||||
|
||||
|
||||
def _seed(session):
|
||||
project = Project(name="Multi system daily report")
|
||||
session.add(project)
|
||||
session.flush()
|
||||
document = BoqDocument(project_id=project.id, name="BOQ")
|
||||
session.add(document)
|
||||
session.flush()
|
||||
systems = {}
|
||||
items = {}
|
||||
for code, names in (("A", ["POS-A1", "POS-A2"]), ("B", ["POS-B1", "POS-B2"])):
|
||||
system = System(project_id=project.id, name=f"System {code}")
|
||||
session.add(system)
|
||||
session.flush()
|
||||
section = Section(system_id=system.id, name=f"Section {code}")
|
||||
session.add(section)
|
||||
session.flush()
|
||||
systems[code] = system
|
||||
items[code] = []
|
||||
for number, name in enumerate(names, start=1):
|
||||
item = WorkItem(project_id=project.id, boq_document_id=document.id, system_id=system.id,
|
||||
section_id=section.id, source_number=str(number), name=name,
|
||||
unit="pcs", quantity=Decimal("10"), amount=Decimal("100"))
|
||||
items[code].append(item)
|
||||
session.add(item)
|
||||
session.flush()
|
||||
return project.id, document.id, systems, items
|
||||
|
||||
|
||||
def _row_tag(html, name):
|
||||
match = re.search(rf'<tr[^>]*data-name="{re.escape(name)}"[^>]*>', html)
|
||||
assert match, f"row {name} not found in form"
|
||||
return match.group(0)
|
||||
|
||||
|
||||
def test_multi_system_report_create_edit_and_switch():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
with TestingSession() as session:
|
||||
project_id, _document_id, systems, items = _seed(session)
|
||||
session.commit()
|
||||
a_id, b_id = systems["A"].id, systems["B"].id
|
||||
a1, _a2 = (item.id for item in items["A"])
|
||||
b1, _b2 = (item.id for item in items["B"])
|
||||
|
||||
app.dependency_overrides[daily_reports.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
# 2. Система A -> позиции загружаются; форма несёт позиции всех систем.
|
||||
form_a = client.get(f"/projects/{project_id}/daily-reports/new?system_id={a_id}")
|
||||
assert form_a.status_code == 200
|
||||
assert "POS-A1" in form_a.text and "POS-A2" in form_a.text
|
||||
for item_id in (a1, b1):
|
||||
assert f'name="quantity_{item_id}"' in form_a.text
|
||||
|
||||
# 8. Повторный/другой выбор системы снова загружает её позиции.
|
||||
form_b = client.get(f"/projects/{project_id}/daily-reports/new?system_id={b_id}")
|
||||
assert form_b.status_code == 200
|
||||
assert "POS-B1" in form_b.text and "POS-B2" in form_b.text
|
||||
assert "POS-A1" in form_b.text
|
||||
|
||||
# 1./3./5./6./7. Один отчёт содержит позиции обеих систем.
|
||||
created = client.post(f"/projects/{project_id}/daily-reports", data={
|
||||
"report_date": "2026-03-01", "system_id": str(b_id),
|
||||
f"quantity_{a1}": "3", f"quantity_{b1}": "5",
|
||||
}, follow_redirects=False)
|
||||
assert created.status_code == 303
|
||||
report_id = int(created.headers["location"].rsplit("/", 1)[-1])
|
||||
|
||||
with TestingSession() as session:
|
||||
report = session.query(DailyReport).one()
|
||||
assert report.id == report_id
|
||||
lines = {line.work_item_id: line.completed_quantity for line in report.items}
|
||||
assert lines == {a1: Decimal("3"), b1: Decimal("5")}
|
||||
|
||||
view = client.get(f"/projects/{project_id}/daily-reports/{report_id}")
|
||||
assert view.status_code == 200
|
||||
assert "POS-A1" in view.text and "POS-B1" in view.text
|
||||
|
||||
# 4./8. Переключение на систему A в редактировании загружает её позиции,
|
||||
# уже добавленные позиции другой системы остаются в форме.
|
||||
edit_a = client.get(f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id={a_id}")
|
||||
assert edit_a.status_code == 200
|
||||
assert f'name="quantity_{a1}"' in edit_a.text
|
||||
assert f'name="quantity_{b1}"' in edit_a.text
|
||||
assert re.search(rf'name="quantity_{b1}" value="5', edit_a.text)
|
||||
assert "hidden" not in _row_tag(edit_a.text, "POS-B1")
|
||||
assert "hidden" not in _row_tag(edit_a.text, "POS-A2")
|
||||
assert "hidden" in _row_tag(edit_a.text, "POS-B2")
|
||||
|
||||
# Сохранение не удаляет позиции другой системы.
|
||||
edited = client.post(f"/projects/{project_id}/daily-reports/{report_id}/edit", data={
|
||||
"report_date": "2026-03-01", "system_id": str(a_id),
|
||||
f"quantity_{a1}": "3", f"quantity_{b1}": "5",
|
||||
}, follow_redirects=False)
|
||||
assert edited.status_code == 303
|
||||
|
||||
# 8. Снова система B — позиции загружаются.
|
||||
edit_b = client.get(f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id={b_id}")
|
||||
assert edit_b.status_code == 200
|
||||
assert "POS-B1" in edit_b.text and "POS-B2" in edit_b.text
|
||||
|
||||
with TestingSession() as session:
|
||||
report = session.query(DailyReport).one()
|
||||
lines = {line.work_item_id: line.completed_quantity for line in report.items}
|
||||
assert lines == {a1: Decimal("3"), b1: Decimal("5")}
|
||||
finally:
|
||||
app.dependency_overrides.pop(daily_reports.get_db, None)
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_multi_system_edit_switch_to_unclassified_still_works():
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
TestingSession = sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
def override_db():
|
||||
session = TestingSession()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
with TestingSession() as session:
|
||||
project_id, document_id, systems, items = _seed(session)
|
||||
free = WorkItem(project_id=project_id, boq_document_id=document_id, system_id=None,
|
||||
section_id=None, source_number="9", name="POS-FREE",
|
||||
unit="pcs", quantity=Decimal("4"), amount=Decimal("40"))
|
||||
session.add(free)
|
||||
session.commit()
|
||||
a_id = systems["A"].id
|
||||
a1 = items["A"][0].id
|
||||
free_id = free.id
|
||||
|
||||
app.dependency_overrides[daily_reports.get_db] = override_db
|
||||
try:
|
||||
with TestClient(app) as client:
|
||||
created = client.post(f"/projects/{project_id}/daily-reports", data={
|
||||
"report_date": "2026-03-02", "system_id": str(a_id),
|
||||
f"quantity_{a1}": "1", f"quantity_{free_id}": "2",
|
||||
}, follow_redirects=False)
|
||||
assert created.status_code == 303
|
||||
report_id = int(created.headers["location"].rsplit("/", 1)[-1])
|
||||
|
||||
edit_free = client.get(
|
||||
f"/projects/{project_id}/daily-reports/{report_id}/edit?system_id=unclassified")
|
||||
assert edit_free.status_code == 200
|
||||
assert "POS-FREE" in edit_free.text
|
||||
assert f'name="quantity_{a1}"' in edit_free.text
|
||||
finally:
|
||||
app.dependency_overrides.pop(daily_reports.get_db, None)
|
||||
engine.dispose()
|
||||
@@ -1,9 +1,8 @@
|
||||
"""Tests for DOC-B3: template-based KS-2 Excel renderer."""
|
||||
"""Tests for DOC-C2: official KS-2 v2 Excel renderer (7-column template)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
@@ -26,7 +25,7 @@ from app.exporters.excel.ks2_renderer import (
|
||||
def _dto(items=None, total=None, status="issued"):
|
||||
header = KS2ExportHeader(
|
||||
project_name="Тестовый проект",
|
||||
customer="Заказчик",
|
||||
customer="Заказчик Организация",
|
||||
contract_number="Д-1",
|
||||
contract_date=date(2026, 1, 10),
|
||||
currency="RUB",
|
||||
@@ -36,6 +35,12 @@ def _dto(items=None, total=None, status="issued"):
|
||||
period_to=date(2026, 2, 28),
|
||||
comment="Комментарий",
|
||||
status=status,
|
||||
contractor_name="Подрядчик ООО",
|
||||
object_name="Объект строительства",
|
||||
contractor_signer_position="Директор",
|
||||
contractor_signer_name="Иванов И.И.",
|
||||
customer_signer_position="Начальник",
|
||||
customer_signer_name="Петров П.П.",
|
||||
)
|
||||
if items is None:
|
||||
items = [
|
||||
@@ -58,12 +63,17 @@ def _open(data: bytes):
|
||||
return load_workbook(io.BytesIO(data))
|
||||
|
||||
|
||||
# Template column layout: A=1, B=2, C=3, E=5, G=7, I=9, K=11
|
||||
COL_NUM, COL_SRC, COL_NAME, COL_UNIT, COL_QTY, COL_PRICE, COL_AMT = 1, 2, 3, 5, 7, 9, 11
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Template
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_template_exists():
|
||||
assert TEMPLATE_FILE.is_file()
|
||||
assert TEMPLATE_FILE.suffix == ".xlsx"
|
||||
assert "v2" in TEMPLATE_FILE.name
|
||||
|
||||
|
||||
def test_manifest_valid():
|
||||
@@ -72,20 +82,31 @@ def test_manifest_valid():
|
||||
assert manifest["template_version"] == TEMPLATE_VERSION
|
||||
assert manifest["file"] == TEMPLATE_FILE.name
|
||||
assert manifest["table_marker"] == "##KS2_ROWS##"
|
||||
assert manifest["group_marker"] == "##KS2_GROUP##"
|
||||
assert manifest["totals_marker"] == "##KS2_TOTALS##"
|
||||
assert manifest["storno_marker"] == "##KS2_STORNO##"
|
||||
assert "project_name" in manifest["placeholders"]
|
||||
assert "customer" in manifest["placeholders"]
|
||||
assert "unit" in manifest["row_placeholders"]
|
||||
|
||||
|
||||
def test_renderer_opens_template():
|
||||
def test_no_external_links():
|
||||
wb = _open(render_ks2_excel(_dto()))
|
||||
assert "КС-2" in wb.sheetnames or wb.active is not None
|
||||
assert len(wb._external_links) == 0
|
||||
|
||||
|
||||
def test_no_formulas_in_output():
|
||||
data = render_ks2_excel(_dto())
|
||||
ws = _open(data).active
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value is not None:
|
||||
assert not str(cell.value).startswith("="), f"formula in {cell.coordinate}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Header
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_header_number_date_period_requisites():
|
||||
def test_header_requisites():
|
||||
data = render_ks2_excel(_dto())
|
||||
ws = _open(data).active
|
||||
text = " | ".join(
|
||||
@@ -93,49 +114,78 @@ def test_header_number_date_period_requisites():
|
||||
)
|
||||
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 "Заказчик Организация" 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
|
||||
|
||||
|
||||
def test_header_period_from_to():
|
||||
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 "01.02.2026" in text
|
||||
assert "28.02.2026" in text
|
||||
|
||||
|
||||
def test_header_signatures():
|
||||
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 "Директор" in text
|
||||
assert "Иванов И.И." in text
|
||||
assert "Начальник" 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
|
||||
def _find_data_rows(ws):
|
||||
"""Return row indexes of work item rows (between column-number row and totals)."""
|
||||
rows = []
|
||||
in_data = False
|
||||
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:
|
||||
# Column numbering row: A=1, B=2, C=3
|
||||
if a == 1 and ws.cell(r, 2).value == 2 and ws.cell(r, 3).value == 3:
|
||||
in_data = True
|
||||
continue
|
||||
rows.append(r)
|
||||
if in_data and a is not None and "ВСЕГО" in str(a):
|
||||
break
|
||||
if in_data:
|
||||
if isinstance(a, (int, float)):
|
||||
rows.append(r)
|
||||
return rows
|
||||
|
||||
|
||||
def test_single_row():
|
||||
data = render_ks2_excel(_dto())
|
||||
ws = _open(data).active
|
||||
rows = _find_rows_block(ws)
|
||||
rows = _find_data_rows(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 == "м"
|
||||
r = rows[0]
|
||||
assert ws.cell(r, COL_NUM).value == 1
|
||||
assert ws.cell(r, COL_SRC).value == "1"
|
||||
assert ws.cell(r, COL_NAME).value == "Монтаж трубы"
|
||||
assert ws.cell(r, COL_UNIT).value == "м"
|
||||
assert float(ws.cell(r, COL_QTY).value) == 12.5
|
||||
assert float(ws.cell(r, COL_PRICE).value) == 482.42
|
||||
assert float(ws.cell(r, COL_AMT).value) == 6030.25
|
||||
|
||||
|
||||
def test_unit_displayed():
|
||||
"""{{unit}} must be rendered in the unit column."""
|
||||
item = KS2ExportItem(1, "1", "X", "шт", Decimal("1"), Decimal("1"), Decimal("1"))
|
||||
data = render_ks2_excel(_dto(items=[item]))
|
||||
ws = _open(data).active
|
||||
rows = _find_data_rows(ws)
|
||||
assert ws.cell(rows[0], COL_UNIT).value == "шт"
|
||||
|
||||
|
||||
def test_multiple_rows_match_dto():
|
||||
@@ -146,66 +196,91 @@ def test_multiple_rows_match_dto():
|
||||
]
|
||||
data = render_ks2_excel(_dto(items=items))
|
||||
ws = _open(data).active
|
||||
rows = _find_rows_block(ws)
|
||||
rows = _find_data_rows(ws)
|
||||
assert len(rows) == 3
|
||||
names = [ws.cell(r, 2).value for r in rows]
|
||||
names = [ws.cell(r, COL_NAME).value for r in rows]
|
||||
assert names == ["Первая", "Вторая", "Третья"]
|
||||
assert [ws.cell(r, 3).value for r in rows] == ["1", "2", "3"]
|
||||
assert [ws.cell(r, COL_SRC).value for r in rows] == ["1", "2", "3"]
|
||||
assert [ws.cell(r, COL_UNIT).value for r in rows] == ["шт", "м", "т"]
|
||||
|
||||
|
||||
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"
|
||||
rows = _find_data_rows(ws)
|
||||
assert ws.cell(rows[0], COL_SRC).value == "BOQ-77"
|
||||
|
||||
|
||||
def test_numeric_excel_cells():
|
||||
def test_quantity_price_amount():
|
||||
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")
|
||||
rows = _find_data_rows(ws)
|
||||
r = rows[0]
|
||||
assert float(ws.cell(r, COL_QTY).value) == 12.5
|
||||
assert float(ws.cell(r, COL_PRICE).value) == 482.42
|
||||
assert float(ws.cell(r, COL_AMT).value) == 6030.25
|
||||
|
||||
|
||||
def test_unused_columns_empty():
|
||||
"""Columns D,F,H,J,L,M must be empty for items."""
|
||||
item = KS2ExportItem(1, "1", "X", "шт", Decimal("1"), Decimal("100"), Decimal("100"))
|
||||
data = render_ks2_excel(_dto(items=[item]))
|
||||
ws = _open(data).active
|
||||
rows = _find_data_rows(ws)
|
||||
r = rows[0]
|
||||
for col in (4, 6, 8, 10, 12, 13): # D,F,H,J,L,M
|
||||
assert ws.cell(r, col).value is None, f"col {col} should be empty"
|
||||
|
||||
|
||||
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
|
||||
rows = _find_data_rows(ws)
|
||||
qty = ws.cell(rows[0], COL_QTY).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 == "—"
|
||||
text = " | ".join(
|
||||
str(c.value) for row in ws.iter_rows() for c in row if c.value is not None
|
||||
)
|
||||
assert "—" in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Grouping
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_group_headers():
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("10"), Decimal("10"), group_header="Система А"),
|
||||
KS2ExportItem(2, "2", "B", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
KS2ExportItem(3, "3", "C", "шт", Decimal("1"), Decimal("10"), Decimal("10"), group_header="Система Б"),
|
||||
KS2ExportItem(4, "4", "D", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
]
|
||||
data = render_ks2_excel(_dto(items=items))
|
||||
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
|
||||
assert "Система Б" in text
|
||||
|
||||
|
||||
def test_no_groups_flat_list():
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
KS2ExportItem(2, "2", "B", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
]
|
||||
data = render_ks2_excel(_dto(items=items))
|
||||
ws = _open(data).active
|
||||
rows = _find_data_rows(ws)
|
||||
assert len(rows) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -218,27 +293,31 @@ def test_total_from_dto():
|
||||
]
|
||||
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
|
||||
if cell.value and "ВСЕГО" in str(cell.value):
|
||||
val = ws.cell(cell.row, COL_AMT).value
|
||||
assert abs(float(val) - 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.
|
||||
items = [KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("1"), Decimal("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
|
||||
if cell.value and "ВСЕГО" in str(cell.value):
|
||||
assert abs(float(ws.cell(cell.row, COL_AMT).value) - 999.0) < 1e-9
|
||||
|
||||
|
||||
def test_no_vat_calculated():
|
||||
data = render_ks2_excel(_dto())
|
||||
ws = _open(data).active
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value and "НДС" in str(cell.value):
|
||||
val = ws.cell(cell.row, COL_AMT).value
|
||||
assert val is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -263,6 +342,237 @@ def test_issued_output_has_no_storno():
|
||||
assert "##KS2_STORNO##" not in text
|
||||
|
||||
|
||||
def test_cancelled_storno_bold_red_and_visible():
|
||||
"""СТОРНИРОВАН must be bold red and span enough width to avoid clipping."""
|
||||
data = render_ks2_excel(_dto(status="cancelled"))
|
||||
ws = _open(data).active
|
||||
storno_cell = None
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value == "СТОРНИРОВАН":
|
||||
storno_cell = cell
|
||||
break
|
||||
if storno_cell:
|
||||
break
|
||||
assert storno_cell is not None
|
||||
assert storno_cell.font.bold is True
|
||||
color = storno_cell.font.color
|
||||
assert color is not None
|
||||
rgb = color.rgb if color.type == "rgb" else str(color.theme)
|
||||
assert "FF0000" in str(rgb).upper() or str(rgb) == "9" # red or theme red
|
||||
# Must be inside a wide merge (or free) so text is not clipped by col A
|
||||
covering = None
|
||||
for rng in ws.merged_cells.ranges:
|
||||
cr_min_r, cr_min_c = rng.min_row, rng.min_col
|
||||
cr_max_r, cr_max_c = rng.max_row, rng.max_col
|
||||
if cr_min_r <= storno_cell.row <= cr_max_r and cr_min_c <= storno_cell.column <= cr_max_c:
|
||||
covering = (cr_min_r, cr_min_c, cr_max_r, cr_max_c)
|
||||
break
|
||||
if covering is not None:
|
||||
assert covering[3] - covering[1] >= 3, f"STORNO merge too narrow: {covering}"
|
||||
|
||||
|
||||
def test_cancelled_storno_does_not_break_header_merges():
|
||||
issued = _open(render_ks2_excel(_dto(status="issued"))).active
|
||||
cancelled = _open(render_ks2_excel(_dto(status="cancelled"))).active
|
||||
|
||||
def header_merges(ws):
|
||||
out = set()
|
||||
for rng in ws.merged_cells.ranges:
|
||||
if rng.max_row < 29: # strictly above data area
|
||||
out.add(str(rng))
|
||||
return out
|
||||
|
||||
before = header_merges(issued)
|
||||
after = header_merges(cancelled)
|
||||
# Issued header merges must all survive on cancelled
|
||||
assert before.issubset(after) or before == (after - {m for m in after if m.startswith("A25")})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Merge integrity (multi-row insert)
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_header_merges_preserved_with_many_rows():
|
||||
items = [
|
||||
KS2ExportItem(i, str(i), f"Работа {i}", "шт", Decimal("1"), Decimal("10"), Decimal("10"),
|
||||
group_header=f"Группа {i}" if i == 1 else None)
|
||||
for i in range(1, 11)
|
||||
]
|
||||
template_wb = load_workbook(TEMPLATE_FILE)
|
||||
template_ws = template_wb.active
|
||||
template_header = {
|
||||
str(rng) for rng in template_ws.merged_cells.ranges if rng.max_row < 29
|
||||
}
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
out_header = {str(rng) for rng in ws.merged_cells.ranges if rng.max_row < 29}
|
||||
assert template_header == out_header
|
||||
|
||||
|
||||
def test_data_rows_have_item_merges():
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("1"), Decimal("1")),
|
||||
KS2ExportItem(2, "2", "B", "шт", Decimal("1"), Decimal("1"), Decimal("1")),
|
||||
KS2ExportItem(3, "3", "C", "шт", Decimal("1"), Decimal("1"), Decimal("1")),
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
data_rows = _find_data_rows(ws)
|
||||
assert len(data_rows) == 3
|
||||
for r in data_rows:
|
||||
for c1, c2 in ((3, 4), (5, 6), (7, 8), (9, 10), (11, 13)):
|
||||
found = any(
|
||||
rng.min_row == r and rng.max_row == r and rng.min_col == c1 and rng.max_col == c2
|
||||
for rng in ws.merged_cells.ranges
|
||||
)
|
||||
assert found, f"missing item merge {c1}:{c2} on row {r}"
|
||||
|
||||
|
||||
def test_group_rows_have_full_width_merge():
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("1"), Decimal("1"),
|
||||
group_header="Система А"),
|
||||
KS2ExportItem(2, "2", "B", "шт", Decimal("1"), Decimal("1"), Decimal("1")),
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
group_rows = []
|
||||
for r in range(1, ws.max_row + 1):
|
||||
if ws.cell(r, 1).value == "Система А":
|
||||
group_rows.append(r)
|
||||
assert group_rows
|
||||
r = group_rows[0]
|
||||
found = any(
|
||||
rng.min_row == r and rng.max_row == r and rng.min_col == 1 and rng.max_col == 13
|
||||
for rng in ws.merged_cells.ranges
|
||||
)
|
||||
assert found, "group row must merge A:M"
|
||||
|
||||
|
||||
def test_signature_merges_preserved_with_many_rows():
|
||||
items = [
|
||||
KS2ExportItem(i, str(i), f"Работа {i}", "шт", Decimal("1"), Decimal("10"), Decimal("10"))
|
||||
for i in range(1, 8)
|
||||
]
|
||||
template_ws = load_workbook(TEMPLATE_FILE).active
|
||||
# Signature block merges sit below the totals row (original rows 36+)
|
||||
template_sig = {
|
||||
str(rng) for rng in template_ws.merged_cells.ranges if rng.min_row >= 36
|
||||
}
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
out_sig = {str(rng) for rng in ws.merged_cells.ranges if rng.min_row >= 36}
|
||||
# Relative to bottom-of-sheet content, all signature merges must exist somewhere
|
||||
# (row numbers shift). Check count and column spans.
|
||||
assert len(out_sig) >= len(template_sig)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Number format
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_amounts_are_numeric_with_two_decimal_format():
|
||||
item = KS2ExportItem(1, "1", "X", "шт", Decimal("2"), Decimal("100.5"), Decimal("201"))
|
||||
data = render_ks2_excel(_dto(items=[item], total=Decimal("201")))
|
||||
ws = _open(data).active
|
||||
rows = _find_data_rows(ws)
|
||||
r = rows[0]
|
||||
for col in (COL_QTY, COL_PRICE, COL_AMT):
|
||||
cell = ws.cell(r, col)
|
||||
assert isinstance(cell.value, (int, float)), f"col {col} not numeric: {cell.value!r}"
|
||||
fmt = str(cell.number_format).replace(",", ".")
|
||||
assert fmt in ("0.00", "#,##0.00"), f"unexpected format {cell.number_format!r}"
|
||||
assert "₽" not in str(cell.number_format)
|
||||
assert "RUB" not in str(cell.number_format).upper()
|
||||
assert '"' not in str(cell.number_format) # no literal currency suffix
|
||||
|
||||
|
||||
def test_totals_numeric_without_currency():
|
||||
item = KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("100"), Decimal("100"))
|
||||
data = render_ks2_excel(_dto(items=[item], total=Decimal("100")))
|
||||
ws = _open(data).active
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value and "ВСЕГО" in str(cell.value):
|
||||
total_cell = ws.cell(cell.row, COL_AMT)
|
||||
assert isinstance(total_cell.value, (int, float))
|
||||
fmt = str(total_cell.number_format)
|
||||
assert "₽" not in fmt and "RUB" not in fmt.upper()
|
||||
assert "0.00" in fmt.replace(",", ".") or fmt.replace(",", ".") == "0.00"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Layout compactness
|
||||
# ---------------------------------------------------------------------------
|
||||
def _find_row(ws, needle, col=1):
|
||||
for r in range(1, ws.max_row + 1):
|
||||
val = ws.cell(r, col).value
|
||||
if val is not None and needle in str(val):
|
||||
return r
|
||||
return None
|
||||
|
||||
|
||||
def test_no_empty_gap_between_items_and_totals():
|
||||
"""Unused template data slots must be deleted, not left as blank rows."""
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
data_rows = _find_data_rows(ws)
|
||||
vsyo = _find_row(ws, "ВСЕГО")
|
||||
assert data_rows and vsyo
|
||||
last = max(data_rows)
|
||||
for r in range(last + 1, vsyo):
|
||||
for col in range(1, 14):
|
||||
assert ws.cell(r, col).value in (None, ""), f"gap row {r} col {col}"
|
||||
|
||||
|
||||
def test_no_huge_empty_block_before_signatures():
|
||||
"""Reserved empty template rows after ВСЕГО must be removed."""
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
vsyo = _find_row(ws, "ВСЕГО")
|
||||
sdal = _find_row(ws, "Сдал", col=3)
|
||||
assert vsyo and sdal
|
||||
gap = sdal - vsyo - 1
|
||||
assert gap <= 1, f"too many spacer rows between totals and signatures: {gap}"
|
||||
|
||||
|
||||
def test_compact_for_single_item_still_has_totals_and_signatures():
|
||||
items = [KS2ExportItem(1, "1", "X", "шт", Decimal("1"), Decimal("5"), Decimal("5"))]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
assert _find_row(ws, "ВСЕГО")
|
||||
assert _find_row(ws, "Сдал", col=3)
|
||||
assert _find_row(ws, "Принял", col=3)
|
||||
|
||||
|
||||
def test_many_items_compact_no_trailing_empty_rows():
|
||||
items = [
|
||||
KS2ExportItem(i, str(i), f"R{i}", "шт", Decimal("1"), Decimal("1"), Decimal("1"),
|
||||
group_header=f"G{i}" if i == 1 else None)
|
||||
for i in range(1, 11)
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
data_rows = _find_data_rows(ws)
|
||||
assert len(data_rows) == 10
|
||||
vsyo = _find_row(ws, "ВСЕГО")
|
||||
last = max(data_rows)
|
||||
for r in range(last + 1, vsyo):
|
||||
for col in range(1, 14):
|
||||
assert ws.cell(r, col).value in (None, "")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Prices caption text
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_prices_caption_is_universal_without_2020():
|
||||
ws = _open(render_ks2_excel(_dto())).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
|
||||
assert "2020" not in text
|
||||
assert "квартал" not in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Template integrity
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_template_not_modified():
|
||||
before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||
render_ks2_excel(_dto())
|
||||
@@ -271,6 +581,17 @@ def test_template_not_modified():
|
||||
assert before == after
|
||||
|
||||
|
||||
def test_official_structure_preserved():
|
||||
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" in text
|
||||
assert "0322005" in text
|
||||
assert "АКТ" in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Output
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -282,33 +603,56 @@ 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
|
||||
assert ws.max_row >= 20
|
||||
|
||||
|
||||
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
|
||||
a = _open(render_ks2_excel(dto))
|
||||
b = _open(render_ks2_excel(dto))
|
||||
for r in range(1, a.active.max_row + 1):
|
||||
for c in range(1, 14):
|
||||
assert a.active.cell(r, c).value == b.active.cell(r, c).value
|
||||
|
||||
|
||||
def test_missing_template_raises(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.exporters.excel.ks2_renderer.TEMPLATE_FILE",
|
||||
Path("/nonexistent/ks2_ru_v1.xlsx"),
|
||||
Path("/nonexistent/ks2_ru_v2.xlsx"),
|
||||
)
|
||||
with pytest.raises(TemplateNotFoundError):
|
||||
render_ks2_excel(_dto())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Multiple sections
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_multiple_sections_multiple_rows():
|
||||
items = [
|
||||
KS2ExportItem(1, "1", "Работа А1", "шт", Decimal("1"), Decimal("10"), Decimal("10"), group_header="Раздел 1"),
|
||||
KS2ExportItem(2, "2", "Работа А2", "шт", Decimal("2"), Decimal("10"), Decimal("20")),
|
||||
KS2ExportItem(3, "3", "Работа Б1", "шт", Decimal("3"), Decimal("10"), Decimal("30"), group_header="Раздел 2"),
|
||||
KS2ExportItem(4, "4", "Работа Б2", "шт", Decimal("4"), Decimal("10"), Decimal("40")),
|
||||
KS2ExportItem(5, "5", "Работа В1", "шт", Decimal("5"), Decimal("10"), Decimal("50"), group_header="Раздел 3"),
|
||||
]
|
||||
data = render_ks2_excel(_dto(items=items, total=Decimal("150.00")))
|
||||
ws = _open(data).active
|
||||
rows = _find_data_rows(ws)
|
||||
assert len(rows) == 5
|
||||
text = " | ".join(
|
||||
str(c.value) for row in ws.iter_rows() for c in row if c.value is not None
|
||||
)
|
||||
assert "Раздел 1" in text
|
||||
assert "Раздел 2" in text
|
||||
assert "Раздел 3" in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 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,
|
||||
)
|
||||
@@ -354,3 +698,111 @@ def test_compatible_with_artifact_service(tmp_path, monkeypatch):
|
||||
assert body == content
|
||||
db.close()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DOC-C2-VISUAL-fix: header doc block / signers / table padding
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_header_doc_block_values_in_template_cells():
|
||||
"""«Номер документа / Дата составления / Отчётный период» values must land
|
||||
strictly in the template-designated cells (G22..J22)."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
assert ws["G22"].value == "К2-1"
|
||||
assert ws["H22"].value == "01.03.2026"
|
||||
assert ws["I22"].value == "01.02.2026"
|
||||
assert ws["J22"].value == "28.02.2026"
|
||||
# Labels stay on their own rows (long label may contain a soft line break)
|
||||
assert "Номер документа" in str(ws["G20"].value)
|
||||
h20 = str(ws["H20"].value).replace("\n", " ")
|
||||
assert "Дата составления" in h20
|
||||
assert "Отчетный период" in str(ws["I20"].value)
|
||||
assert ws["I21"].value == "с"
|
||||
assert ws["J21"].value == "по"
|
||||
|
||||
|
||||
def test_header_doc_block_merges_not_destroyed():
|
||||
"""G20:G21 / H20:H21 / I20:J20 must survive render untouched."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
header_merges = {str(rng) for rng in ws.merged_cells.ranges if rng.max_row < 29}
|
||||
assert "G20:G21" in header_merges
|
||||
assert "H20:H21" in header_merges
|
||||
assert "I20:J20" in header_merges
|
||||
|
||||
|
||||
def test_header_doc_block_values_vertically_centered():
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
for col in range(7, 11):
|
||||
cell = ws.cell(22, col)
|
||||
assert cell.alignment.vertical == "center", f"col {col} not vcenter"
|
||||
|
||||
|
||||
def test_contractor_position_above_signature_line():
|
||||
"""«Сдал»: position + name on the value row; «(должность)» below the line."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
sdal = _find_row(ws, "Сдал", col=3)
|
||||
assert sdal
|
||||
assert ws.cell(sdal, 5).value == "Директор"
|
||||
assert ws.cell(sdal, 10).value == "Иванов И.И."
|
||||
label = sdal + 1
|
||||
assert ws.cell(label, 5).value == "(должность)"
|
||||
assert ws.cell(label, 9).value == "(подпись)"
|
||||
|
||||
|
||||
def test_customer_position_above_signature_line():
|
||||
"""«Принял»: position must sit on the value row (not on the label row)."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
prinyal = _find_row(ws, "Принял", col=3)
|
||||
assert prinyal
|
||||
# position is on the «Принял» value row (top-left of E:I merge)
|
||||
assert ws.cell(prinyal, 5).value == "Начальник"
|
||||
assert ws.cell(prinyal, 10).value == "Петров П.П."
|
||||
label = prinyal + 1
|
||||
# label row must show the label, NOT the position
|
||||
assert ws.cell(label, 5).value == "(должность)"
|
||||
assert ws.cell(label, 9).value == "(подпись)"
|
||||
assert ws.cell(label, 10).value == "(расшифровка подписи)"
|
||||
|
||||
|
||||
def test_customer_position_with_many_rows():
|
||||
items = [
|
||||
KS2ExportItem(i, str(i), f"R{i}", "шт", Decimal("1"), Decimal("1"), Decimal("1"),
|
||||
group_header=f"G{i}" if i == 1 else None)
|
||||
for i in range(1, 9)
|
||||
]
|
||||
ws = _open(render_ks2_excel(_dto(items=items))).active
|
||||
prinyal = _find_row(ws, "Принял", col=3)
|
||||
assert prinyal
|
||||
assert ws.cell(prinyal, 5).value == "Начальник"
|
||||
assert ws.cell(prinyal + 1, 5).value == "(должность)"
|
||||
|
||||
|
||||
def test_table_text_cells_vertical_center_wrap_indent():
|
||||
"""Text columns: vertical center + wrap + small left indent."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
rows = _find_data_rows(ws)
|
||||
r = rows[0]
|
||||
for col in (COL_SRC, COL_NAME, COL_UNIT):
|
||||
al = ws.cell(r, col).alignment
|
||||
assert al.vertical == "center", f"text col {col} v={al.vertical}"
|
||||
assert al.wrap_text is True, f"text col {col} wrap={al.wrap_text}"
|
||||
assert al.indent == 1, f"text col {col} indent={al.indent}"
|
||||
|
||||
|
||||
def test_table_number_cells_vertical_center_no_indent():
|
||||
"""Numeric columns: vertical center, no indent."""
|
||||
ws = _open(render_ks2_excel(_dto())).active
|
||||
rows = _find_data_rows(ws)
|
||||
r = rows[0]
|
||||
for col in (COL_NUM, COL_QTY, COL_PRICE, COL_AMT):
|
||||
al = ws.cell(r, col).alignment
|
||||
assert al.vertical == "center", f"num col {col} v={al.vertical}"
|
||||
assert al.indent == 0, f"num col {col} indent={al.indent}"
|
||||
|
||||
|
||||
def test_no_unresolved_signer_placeholders():
|
||||
data = render_ks2_excel(_dto())
|
||||
ws = _open(data).active
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if isinstance(cell.value, str):
|
||||
assert "{{" not in cell.value, f"unresolved marker in {cell.coordinate}"
|
||||
|
||||
@@ -131,7 +131,7 @@ def test_issue_ks2_creates_current_xlsx_artifact(storage_root, db_session, proje
|
||||
).scalar_one_or_none()
|
||||
assert art is not None
|
||||
assert art.template_type == "ks2"
|
||||
assert art.template_version == 1
|
||||
assert art.template_version == 2
|
||||
assert art.is_current is True or art.is_current == 1
|
||||
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
@@ -140,7 +140,7 @@ def test_issue_ks2_creates_current_xlsx_artifact(storage_root, db_session, proje
|
||||
assert art.content_hash == compute_content_hash(content)
|
||||
|
||||
dto = build_ks2_export_dto(db_session, ks2)
|
||||
assert art.input_hash == compute_input_hash(dto, "ks2", 1)
|
||||
assert art.input_hash == compute_input_hash(dto, "ks2", 2)
|
||||
|
||||
|
||||
def test_issue_ks3_creates_current_docx_artifact(storage_root, db_session, project_id):
|
||||
@@ -336,10 +336,15 @@ def test_issue_ks3_rollback_leaves_no_orphan(storage_root, db_session, project_i
|
||||
assert arts == []
|
||||
# Only KS3 artifacts are orphans of this failed attempt; the committed
|
||||
# KS-2 artifact file must remain untouched.
|
||||
ks3_files = list((storage_root / "projects").rglob("*/*.docx")) if storage_root.exists() else []
|
||||
assert [f for f in ks3_files if f.is_file()] == []
|
||||
ks3_arts = db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.document_type == "KS3")
|
||||
).all()
|
||||
assert ks3_arts == []
|
||||
ks2_files = list((storage_root / "projects").rglob("*/*.xlsx")) if storage_root.exists() else []
|
||||
assert len([f for f in ks2_files if f.is_file()]) == 1
|
||||
ks2_docx = list((storage_root / "projects").rglob("*/*.docx")) if storage_root.exists() else []
|
||||
# the committed KS-2 Word artifact remains; the failed KS3 attempt added none
|
||||
assert len([f for f in ks2_docx if f.is_file()]) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -357,6 +362,7 @@ def test_cancel_ks2_preserves_issued_artifact(storage_root, db_session, project_
|
||||
select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.document_id == ks2.id,
|
||||
DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)
|
||||
).scalar_one()
|
||||
@@ -423,7 +429,8 @@ def test_issued_document_cannot_be_issued_again(storage_root, db_session, projec
|
||||
art_count = db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2")
|
||||
).all()
|
||||
assert len(art_count) == 1
|
||||
# xlsx + docx artifacts are persisted on issue
|
||||
assert len(art_count) == 2
|
||||
|
||||
with pytest.raises(KS2ValidationError, match="черновик"):
|
||||
issue_ks2(db_session, project_id, ks2.id)
|
||||
@@ -432,7 +439,7 @@ def test_issued_document_cannot_be_issued_again(storage_root, db_session, projec
|
||||
arts = db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2")
|
||||
).all()
|
||||
assert len(arts) == 1
|
||||
assert len(arts) == 2
|
||||
|
||||
|
||||
def test_issued_document_cannot_be_edited(storage_root, db_session, project_id):
|
||||
@@ -460,6 +467,7 @@ def test_ks3_issue_does_not_touch_ks2_artifacts(storage_root, db_session, projec
|
||||
ks2_art = db_session.execute(
|
||||
select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)
|
||||
).scalar_one()
|
||||
@@ -477,12 +485,10 @@ def test_ks3_issue_does_not_touch_ks2_artifacts(storage_root, db_session, projec
|
||||
ks2_art = db_session.get(DocumentArtifact, ks2_art_id)
|
||||
assert ks2_art.is_current in (True, 1)
|
||||
assert ks2_art.content_hash == ks2_hash
|
||||
# Only one KS-2 artifact
|
||||
assert db_session.execute(
|
||||
# xlsx + docx KS-2 artifacts (DOC-C3)
|
||||
assert len(db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2")
|
||||
).all() and len(db_session.execute(
|
||||
select(DocumentArtifact).where(DocumentArtifact.document_type == "KS2")
|
||||
).all()) == 1
|
||||
).all()) == 2
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -117,6 +117,7 @@ def test_ks2_issued_download_xlsx(storage_root, db_session, ctx):
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.document_id == ks2.id,
|
||||
DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
@@ -137,6 +138,7 @@ def test_ks2_download_does_not_mutate_artifact(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
art_id, is_current, ch, ih = art.id, art.is_current, art.content_hash, art.input_hash
|
||||
@@ -153,13 +155,15 @@ def test_ks2_download_does_not_mutate_artifact(storage_root, db_session, ctx):
|
||||
assert art.input_hash == ih
|
||||
count = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2")).all()
|
||||
assert len(count) == 1
|
||||
# xlsx + docx artifacts are persisted on issue
|
||||
assert len(count) == 2
|
||||
|
||||
|
||||
def test_ks2_cancelled_download_same_artifact(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
@@ -191,7 +195,8 @@ def test_ks2_missing_artifact_404(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
# Delete the physical file
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
resolve_storage_path(art.storage_key).unlink()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
@@ -206,7 +211,8 @@ def test_ks2_missing_artifact_404(storage_root, db_session, ctx):
|
||||
def test_ks2_hash_mismatch_not_served(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.format == "xlsx",
|
||||
DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
path.write_bytes(b"tampered")
|
||||
|
||||
@@ -324,22 +330,24 @@ def test_ks3_cross_project_rejected(storage_root, db_session, ctx):
|
||||
# ---------------------------------------------------------------------------
|
||||
# UI visibility
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ks2_ui_shows_official_button_only_non_draft(storage_root, db_session, ctx):
|
||||
def test_ks2_ui_shows_single_export_button(storage_root, db_session, ctx):
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
# Draft: no official button
|
||||
# Draft: single working KS-2 button, no legacy "Официальная форма"
|
||||
draft = save_ks2_draft(db_session, ctx["project_id"], "K2-UI", date(2026, 3, 1), None,
|
||||
[(ctx["work_item_id"], Decimal("5"))],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{draft.id}")
|
||||
assert "КС-2 (Excel)" in resp.text
|
||||
assert "Официальная форма" not in resp.text
|
||||
|
||||
# Issued: button present
|
||||
# Issued: same single button
|
||||
ks2 = issue_ks2(db_session, ctx["project_id"], draft.id)
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}")
|
||||
assert "Официальная форма" in resp.text
|
||||
assert "/artifact" in resp.text
|
||||
assert "КС-2 (Excel)" in resp.text
|
||||
assert "/export/excel" in resp.text
|
||||
assert "Официальная форма" not in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
@@ -350,7 +358,8 @@ def test_ks2_ui_cancelled_shows_storno_badge(storage_root, db_session, ctx):
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}")
|
||||
assert "Официальная форма" in resp.text
|
||||
assert "КС-2 (Excel)" in resp.text
|
||||
assert "Официальная форма" not in resp.text
|
||||
assert "СТОРНИРОВАН" in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
@@ -98,17 +98,19 @@ def test_export_includes_issued_ks2_artifact(db_session):
|
||||
zf = zipfile.ZipFile(io.BytesIO(data))
|
||||
assert "document_artifacts.json" in zf.namelist()
|
||||
arts = json.loads(zf.read("document_artifacts.json"))
|
||||
assert len(arts) == 1
|
||||
assert arts[0]["document_type"] == "KS2"
|
||||
assert arts[0]["format"] == "xlsx"
|
||||
assert arts[0]["document_export_id"] == "ks2:00000001"
|
||||
assert arts[0]["is_current"] is True
|
||||
assert "artifacts/ks2/" in arts[0]["archive_path"]
|
||||
# Physical file present
|
||||
assert arts[0]["archive_path"] in zf.namelist()
|
||||
# Checksum matches
|
||||
file_bytes = zf.read(arts[0]["archive_path"])
|
||||
assert compute_content_hash(file_bytes) == arts[0]["content_hash"]
|
||||
assert len(arts) == 2 # xlsx + docx (DOC-C3)
|
||||
by_fmt = {a["format"]: a for a in arts}
|
||||
assert set(by_fmt) == {"xlsx", "docx"}
|
||||
for a in arts:
|
||||
assert a["document_type"] == "KS2"
|
||||
assert a["document_export_id"] == "ks2:00000001"
|
||||
assert a["is_current"] is True
|
||||
assert "artifacts/ks2/" in a["archive_path"]
|
||||
assert a["archive_path"] in zf.namelist()
|
||||
file_bytes = zf.read(a["archive_path"])
|
||||
assert compute_content_hash(file_bytes) == a["content_hash"]
|
||||
assert by_fmt["xlsx"]["archive_path"].endswith(".xlsx")
|
||||
assert by_fmt["docx"]["archive_path"].endswith(".docx")
|
||||
|
||||
|
||||
def test_export_includes_issued_ks3_artifact(db_session):
|
||||
@@ -131,10 +133,11 @@ def test_export_includes_cancelled_artifact(db_session):
|
||||
data, _ = export_project(db_session, pid)
|
||||
zf = zipfile.ZipFile(io.BytesIO(data))
|
||||
arts = json.loads(zf.read("document_artifacts.json"))
|
||||
assert len(arts) == 1
|
||||
assert arts[0]["document_type"] == "KS2"
|
||||
# Cancelled artifact is the original issued one
|
||||
assert arts[0]["is_current"] is True
|
||||
assert len(arts) == 2 # xlsx + docx (DOC-C3)
|
||||
for a in arts:
|
||||
assert a["document_type"] == "KS2"
|
||||
# Cancelled artifact is the original issued one
|
||||
assert a["is_current"] is True
|
||||
|
||||
|
||||
def test_export_skips_draft_artifacts(db_session):
|
||||
@@ -157,7 +160,7 @@ def test_export_manifest_count(db_session):
|
||||
_issue_ks2(db_session, pid, wi_id)
|
||||
data, _ = export_project(db_session, pid)
|
||||
manifest = json.loads(zipfile.ZipFile(io.BytesIO(data)).read("manifest.json"))
|
||||
assert manifest["counts"]["document_artifacts"] == 1
|
||||
assert manifest["counts"]["document_artifacts"] == 2 # xlsx + docx
|
||||
|
||||
|
||||
def test_export_checksums_include_artifact_files(db_session):
|
||||
@@ -180,12 +183,12 @@ def test_import_restores_artifact(db_session):
|
||||
reset_database(db_session)
|
||||
imported = import_project(db_session, data)
|
||||
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id, format="xlsx").one()
|
||||
assert art.document_type == "KS2"
|
||||
assert art.format == "xlsx"
|
||||
assert art.is_current is True
|
||||
assert art.template_type == "ks2"
|
||||
assert art.template_version == 1
|
||||
assert art.template_version == 2
|
||||
# New IDs
|
||||
assert art.project_id == imported.id
|
||||
new_ks2 = db_session.query(KS2).filter_by(project_id=imported.id).one()
|
||||
@@ -200,16 +203,16 @@ def test_import_restores_artifact(db_session):
|
||||
def test_import_preserves_hashes_and_template(db_session):
|
||||
pid, wi_id = _seed(db_session)
|
||||
ks2 = _issue_ks2(db_session, pid, wi_id)
|
||||
orig_art = db_session.query(DocumentArtifact).filter_by(project_id=pid).one()
|
||||
orig_art = db_session.query(DocumentArtifact).filter_by(project_id=pid, format="xlsx").one()
|
||||
ch, ih = orig_art.content_hash, orig_art.input_hash
|
||||
data, _ = export_project(db_session, pid)
|
||||
reset_database(db_session)
|
||||
imported = import_project(db_session, data)
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id, format="xlsx").one()
|
||||
assert art.content_hash == ch
|
||||
assert art.input_hash == ih
|
||||
assert art.template_type == "ks2"
|
||||
assert art.template_version == 1
|
||||
assert art.template_version == 2
|
||||
|
||||
|
||||
def test_import_cancelled_artifact(db_session):
|
||||
@@ -219,7 +222,7 @@ def test_import_cancelled_artifact(db_session):
|
||||
data, _ = export_project(db_session, pid)
|
||||
reset_database(db_session)
|
||||
imported = import_project(db_session, data)
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id, format="xlsx").one()
|
||||
assert art.is_current is True
|
||||
assert resolve_storage_path(art.storage_key).is_file()
|
||||
|
||||
@@ -350,14 +353,14 @@ def test_roundtrip_export_reset_import_export(db_session):
|
||||
|
||||
data1, _ = export_project(db_session, pid)
|
||||
arts1 = json.loads(zipfile.ZipFile(io.BytesIO(data1)).read("document_artifacts.json"))
|
||||
assert len(arts1) == 2 # KS2 + KS3
|
||||
assert len(arts1) == 3 # KS2(xlsx) + KS2(docx) + KS3
|
||||
|
||||
reset_database(db_session)
|
||||
imported = import_project(db_session, data1)
|
||||
|
||||
# Verify artifacts restored
|
||||
new_arts = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).all()
|
||||
assert len(new_arts) == 2
|
||||
assert len(new_arts) == 3
|
||||
for art in new_arts:
|
||||
assert art.is_current is True
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
@@ -367,7 +370,7 @@ def test_roundtrip_export_reset_import_export(db_session):
|
||||
# Second export
|
||||
data2, _ = export_project(db_session, imported.id)
|
||||
arts2 = json.loads(zipfile.ZipFile(io.BytesIO(data2)).read("document_artifacts.json"))
|
||||
assert len(arts2) == 2
|
||||
assert len(arts2) == 3
|
||||
# Hashes match original
|
||||
h1 = {a["content_hash"] for a in arts1}
|
||||
h2 = {a["content_hash"] for a in arts2}
|
||||
@@ -382,13 +385,13 @@ def test_roundtrip_cancelled_artifact_preserved(db_session):
|
||||
ks2 = _issue_ks2(db_session, pid, wi_id)
|
||||
cancel_ks2(db_session, pid, ks2.id)
|
||||
orig_bytes = resolve_storage_path(
|
||||
db_session.query(DocumentArtifact).filter_by(project_id=pid).one().storage_key
|
||||
db_session.query(DocumentArtifact).filter_by(project_id=pid, format="xlsx").one().storage_key
|
||||
).read_bytes()
|
||||
|
||||
data, _ = export_project(db_session, pid)
|
||||
reset_database(db_session)
|
||||
imported = import_project(db_session, data)
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id, format="xlsx").one()
|
||||
new_bytes = resolve_storage_path(art.storage_key).read_bytes()
|
||||
assert new_bytes == orig_bytes
|
||||
# Cancelled status preserved
|
||||
|
||||
@@ -89,7 +89,7 @@ def test_reset_deletes_db_rows_and_storage(storage_root, db_session):
|
||||
pid = _seed_project_with_artifact(db_session)
|
||||
storage_dir = project_storage_path(pid)
|
||||
assert storage_dir.is_dir()
|
||||
assert db_session.query(DocumentArtifact).count() == 1
|
||||
assert db_session.query(DocumentArtifact).count() == 2 # xlsx + docx
|
||||
|
||||
result = reset_database(db_session)
|
||||
|
||||
@@ -262,7 +262,7 @@ def test_export_reset_import_artifacts_survive(storage_root, db_session):
|
||||
assert result.storage_removed is True
|
||||
|
||||
imported = import_project(db_session, data)
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
|
||||
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id, format="xlsx").one()
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
assert path.is_file()
|
||||
# New project storage exists
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
"""Tests for DOC-C3: official-form KS-2 Word renderer."""
|
||||
from __future__ import annotations
|
||||
|
||||
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.ks2_dto import KS2ExportDocument, KS2ExportHeader, KS2ExportItem
|
||||
from app.exporters.word.ks2_renderer import (
|
||||
TEMPLATE_FILE,
|
||||
TEMPLATE_TYPE,
|
||||
TEMPLATE_VERSION,
|
||||
TemplateNotFoundError,
|
||||
render_ks2_word,
|
||||
)
|
||||
|
||||
|
||||
def _header(status="issued"):
|
||||
return KS2ExportHeader(
|
||||
project_name="P",
|
||||
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,
|
||||
contractor_name="ООО Подрядчик",
|
||||
object_name="Объект",
|
||||
investor_name="ООО Инвестор",
|
||||
construction_name="Стройка",
|
||||
contractor_signer_position="Директор",
|
||||
contractor_signer_name="Иванов И.И.",
|
||||
customer_signer_position="Начальник",
|
||||
customer_signer_name="Петров П.П.",
|
||||
)
|
||||
|
||||
|
||||
def _item(n=1, group=None, code=None, name=None):
|
||||
return KS2ExportItem(
|
||||
row_number=n,
|
||||
source_number=str(n),
|
||||
name=name or f"Работа {n}",
|
||||
unit="шт",
|
||||
quantity=Decimal("10"),
|
||||
unit_price=Decimal("100.5"),
|
||||
amount=Decimal("1005"),
|
||||
group_header=group,
|
||||
group_code=code,
|
||||
)
|
||||
|
||||
|
||||
def _dto(items=None, total=None, status="issued"):
|
||||
items = items if items is not None else [_item()]
|
||||
total = total if total is not None else sum((i.amount for i in items), Decimal("0"))
|
||||
return KS2ExportDocument(header=_header(status), items=items, total=total)
|
||||
|
||||
|
||||
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 _all_text(doc):
|
||||
parts = [p.text for p in doc.paragraphs]
|
||||
for t in doc.tables:
|
||||
for row in t.rows:
|
||||
for c in row.cells:
|
||||
parts.append(c.text)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Template
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_template_exists():
|
||||
assert TEMPLATE_FILE.is_file()
|
||||
assert TEMPLATE_FILE.suffix == ".docx"
|
||||
|
||||
|
||||
def test_template_type_and_version():
|
||||
assert TEMPLATE_TYPE == "ks2_word"
|
||||
assert TEMPLATE_VERSION == 1
|
||||
|
||||
|
||||
def test_missing_template_raises(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
"app.exporters.word.ks2_renderer.TEMPLATE_FILE",
|
||||
Path("/nonexistent/ks2_ru_v2.docx"),
|
||||
)
|
||||
with pytest.raises(TemplateNotFoundError):
|
||||
render_ks2_word(_dto())
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Header
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_header_requisites():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
text = _all_text(d)
|
||||
assert "0322005" in text
|
||||
assert "ООО Инвестор" in text
|
||||
assert "ООО Заказчик" in text
|
||||
assert "ООО Подрядчик" in text
|
||||
assert "Стройка" in text
|
||||
assert "Объект" in text
|
||||
assert "Д-1" in text
|
||||
|
||||
|
||||
def test_header_number_date_period():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
t1 = d.tables[1]
|
||||
r0 = _raw_row(t1, 0)
|
||||
r1 = _raw_row(t1, 1)
|
||||
r2 = _raw_row(t1, 2)
|
||||
# labels in row 0; marker value row (r2) holds the filled values
|
||||
assert "Номер документа" in r0[1]
|
||||
assert "К2-1" in r2[1]
|
||||
assert "Дата составления" in r0[2]
|
||||
assert "01.03.2026" in r2[2]
|
||||
assert "01.02.2026" in r2[4]
|
||||
assert "28.02.2026" in r2[5]
|
||||
# с / по labels stay in row 1
|
||||
assert "с" in r1[4] and "по" in r1[5]
|
||||
|
||||
|
||||
def test_header_block_vmerge_preserved():
|
||||
"""The tall label/value cells must stay merged — same geometry as the blank."""
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
t1 = d.tables[1]
|
||||
tcs0 = t1.rows[0]._tr.findall(qn("w:tc"))
|
||||
tcs1 = t1.rows[1]._tr.findall(qn("w:tc"))
|
||||
# label cells (c1, c2) keep vMerge=restart / continue
|
||||
for idx in (1, 2):
|
||||
tcPr0 = tcs0[idx].find(qn("w:tcPr"))
|
||||
vm0 = tcPr0.find(qn("w:vMerge")) if tcPr0 is not None else None
|
||||
assert vm0 is not None and (vm0.get(qn("w:val")) or "continue") == "restart"
|
||||
tcPr1 = tcs1[idx].find(qn("w:tcPr"))
|
||||
vm1 = tcPr1.find(qn("w:vMerge")) if tcPr1 is not None else None
|
||||
assert vm1 is not None
|
||||
|
||||
|
||||
def test_contract_date_split_into_day_month_year():
|
||||
d = _open(render_ks2_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_empty_okpo_okdp_left_blank():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
text = _all_text(d)
|
||||
assert "по ОКПО" in text # labels stay
|
||||
# no invented values after the OKPO labels in requisites table
|
||||
t0 = d.tables[0]
|
||||
row2 = _raw_row(t0, 2)
|
||||
assert row2[3] == "" # OKPO value cell empty
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Table / 8 columns
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_table_eight_columns():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
t3 = d.tables[3]
|
||||
header = _raw_row(t3, 2)
|
||||
assert header == ["1", "2", "3", "4", "5", "6", "7", "8"]
|
||||
|
||||
|
||||
def test_single_item_all_columns():
|
||||
d = _open(render_ks2_word(_dto([_item(1, name="Монтаж трубы")])))
|
||||
t3 = d.tables[3]
|
||||
row = _raw_row(t3, 3)
|
||||
assert row[0] == "1" # № по порядку
|
||||
assert row[1] == "1" # № позиции по смете
|
||||
assert row[2] == "Монтаж трубы"
|
||||
assert row[3] == "" # № единичной расценки — always empty
|
||||
assert row[4] == "шт"
|
||||
assert row[5] == "10,00"
|
||||
assert row[6] == "100,50"
|
||||
assert row[7] == "1 005,00"
|
||||
|
||||
|
||||
def test_rate_column_always_empty():
|
||||
items = [_item(i) for i in range(1, 4)]
|
||||
d = _open(render_ks2_word(_dto(items)))
|
||||
for ti in (3, 4):
|
||||
tbl = d.tables[ti]
|
||||
for ri in range(3, len(tbl.rows)):
|
||||
row = _raw_row(tbl, ri)
|
||||
if len(row) == 8 and row[0].isdigit():
|
||||
assert row[3] == "", f"rate column filled at t{ti} r{ri}"
|
||||
|
||||
|
||||
def test_multiple_rows_match_dto():
|
||||
items = [_item(i, name=f"Позиция {i}") for i in range(1, 4)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("3015"))))
|
||||
t3 = d.tables[3]
|
||||
rows = [_raw_row(t3, ri) for ri in range(3, 6)]
|
||||
assert [r[2] for r in rows] == ["Позиция 1", "Позиция 2", "Позиция 3"]
|
||||
assert [r[7] for r in rows] == ["1 005,00", "1 005,00", "1 005,00"]
|
||||
|
||||
|
||||
def test_long_name_present():
|
||||
long_name = "Очень длинное наименование работы, которое должно переноситься в ячейке таблицы"
|
||||
d = _open(render_ks2_word(_dto([_item(1, name=long_name)])))
|
||||
assert long_name in _all_text(d)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Totals
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_totals():
|
||||
items = [_item(i) for i in range(1, 4)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("3015"))))
|
||||
t4 = d.tables[4]
|
||||
last = _raw_row(t4, len(t4.rows) - 1)
|
||||
assert "Всего по акту" in last[0]
|
||||
assert last[-1] == "3 015,00"
|
||||
# Итого sits just before Всего по акту
|
||||
prev = _raw_row(t4, len(t4.rows) - 2)
|
||||
assert "Итого" in prev[0]
|
||||
assert prev[-1] == "3 015,00"
|
||||
|
||||
|
||||
def test_grand_total_on_page2():
|
||||
items = [_item(i) for i in range(1, 13)]
|
||||
total = Decimal("12060")
|
||||
d = _open(render_ks2_word(_dto(items, total=total)))
|
||||
t4 = d.tables[4]
|
||||
texts = [_raw_row(t4, ri) for ri in range(len(t4.rows))]
|
||||
vsyo = [r for r in texts if "Всего по акту" in r[0]]
|
||||
assert vsyo and vsyo[0][-1] == "12 060,00"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DOC-C6: no intermediate page subtotal
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_no_intermediate_totals_in_middle_of_table():
|
||||
"""No «Итого» between item rows — money totals only at the end."""
|
||||
items = [_item(i, group="Система А" if i == 1 else None, code="А" if i == 1 else None)
|
||||
for i in range(1, 16)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("15000"))))
|
||||
all_rows = []
|
||||
for ti in (3, 4):
|
||||
t = d.tables[ti]
|
||||
for ri in range(len(t.rows)):
|
||||
all_rows.append((ti, ri, _raw_row(t, ri)))
|
||||
|
||||
itogo_rows = [(ti, ri, r) for ti, ri, r in all_rows if "Итого" in r[0] and "Всего" not in r[0]]
|
||||
vsyo_rows = [(ti, ri, r) for ti, ri, r in all_rows if "Всего по акту" in r[0]]
|
||||
|
||||
# exactly one final Итого and one Всего по акту
|
||||
assert len(itogo_rows) == 1, itogo_rows
|
||||
assert len(vsyo_rows) == 1, vsyo_rows
|
||||
|
||||
# both live at the very end of the last data table
|
||||
last_ti = max(ti for ti, _, _ in all_rows)
|
||||
t_last = d.tables[last_ti]
|
||||
n = len(t_last.rows)
|
||||
assert itogo_rows[0][0] == last_ti and itogo_rows[0][1] == n - 2
|
||||
assert vsyo_rows[0][0] == last_ti and vsyo_rows[0][1] == n - 1
|
||||
|
||||
# final sums equal total of all items
|
||||
assert itogo_rows[0][2][-1] == "15 000,00"
|
||||
assert vsyo_rows[0][2][-1] == "15 000,00"
|
||||
|
||||
# no page subtotal: first data table must not contain any money total
|
||||
t3_rows = [_raw_row(d.tables[3], ri) for ri in range(len(d.tables[3].rows))]
|
||||
assert not any("Итого" in r[0] for r in t3_rows)
|
||||
|
||||
|
||||
def test_no_intermediate_totals_all_items_on_page1():
|
||||
"""Even when everything fits on page 1, no extra Итого inside the table."""
|
||||
items = [_item(i) for i in range(1, 5)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("4000"))))
|
||||
t3_rows = [_raw_row(d.tables[3], ri) for ri in range(len(d.tables[3].rows))]
|
||||
assert not any("Итого" in r[0] for r in t3_rows)
|
||||
t4_rows = [_raw_row(d.tables[4], ri) for ri in range(len(d.tables[4].rows))]
|
||||
assert sum(1 for r in t4_rows if "Итого" in r[0] and "Всего" not in r[0]) == 1
|
||||
assert sum(1 for r in t4_rows if "Всего по акту" in r[0]) == 1
|
||||
|
||||
|
||||
def test_system_rows_preserved_without_totals():
|
||||
items = [
|
||||
_item(1, group="Система А", code="АУПС", name="А1"),
|
||||
_item(2, name="А2"),
|
||||
_item(3, group="Система Б", code="ОВ", name="Б1"),
|
||||
]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("3000"))))
|
||||
text = _all_text(d)
|
||||
assert "АУПС — Система А" in text
|
||||
assert "ОВ — Система Б" in text
|
||||
# one final Итого only
|
||||
assert sum(1 for t in d.tables for row in t.rows
|
||||
for c in [row.cells[0]] if "Итого" in c.text and "Всего" not in c.text) == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# DOC-C7: one dynamic works table + separate totals block
|
||||
# ---------------------------------------------------------------------------
|
||||
def _item_rows(tbl):
|
||||
"""Item rows of the works table: 8 cells, numeric №, not the 1..8 header row."""
|
||||
out = []
|
||||
for ri in range(len(tbl.rows)):
|
||||
row = _raw_row(tbl, ri)
|
||||
if len(row) != 8 or not row[0].isdigit():
|
||||
continue
|
||||
if row[1] == "2" and row[2] == "3": # column-number header row
|
||||
continue
|
||||
out.append((ri, row))
|
||||
return out
|
||||
|
||||
|
||||
def _count_label_in_tables(d, label):
|
||||
"""Count rows whose first cell text equals `label` (merged cells counted once)."""
|
||||
n = 0
|
||||
for t in d.tables:
|
||||
for row in t.rows:
|
||||
tcs = row._tr.findall(qn("w:tc"))
|
||||
if not tcs:
|
||||
continue
|
||||
txt = "".join(x.text or "" for x in tcs[0].iter(qn("w:t")))
|
||||
if txt.strip() == label:
|
||||
n += 1
|
||||
return n
|
||||
|
||||
|
||||
def test_single_works_table_two_items():
|
||||
items = [_item(1, name="А1"), _item(2, name="А2")]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("2000"))))
|
||||
# all item rows live in the one works table
|
||||
rows3 = _item_rows(d.tables[3])
|
||||
assert [r[1][2] for r in rows3] == ["А1", "А2"]
|
||||
# second table is only the closing totals block
|
||||
t4 = d.tables[4]
|
||||
assert len(t4.rows) == 2
|
||||
assert "Итого" in _raw_row(t4, 0)[0]
|
||||
assert "Всего по акту" in _raw_row(t4, 1)[0]
|
||||
|
||||
|
||||
def test_single_works_table_20_items_no_split():
|
||||
items = [_item(i, group="Система А" if i == 1 else None, code="А" if i == 1 else None)
|
||||
for i in range(1, 21)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("20000"))))
|
||||
rows3 = _item_rows(d.tables[3])
|
||||
assert len(rows3) == 20
|
||||
assert [r[1][0] for r in rows3] == [str(i) for i in range(1, 21)]
|
||||
# no second data table with item rows
|
||||
rows4 = _item_rows(d.tables[4])
|
||||
assert rows4 == []
|
||||
# totals block is exactly 2 rows
|
||||
assert len(d.tables[4].rows) == 2
|
||||
|
||||
|
||||
def test_no_second_data_table_as_continuation():
|
||||
"""t4 must not be a copy of the works table (header + item rows)."""
|
||||
items = [_item(i) for i in range(1, 16)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("15000"))))
|
||||
t4 = d.tables[4]
|
||||
# only money totals rows — no column-header text, no item numbers
|
||||
texts = [_raw_row(t4, ri) for ri in range(len(t4.rows))]
|
||||
assert all("Наименование" not in " ".join(r) for r in texts)
|
||||
assert all(not (len(r) == 8 and r[0].isdigit()) for r in texts)
|
||||
|
||||
|
||||
def test_all_items_present_once():
|
||||
items = [_item(i, name=f"Позиция {i}") for i in range(1, 16)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("15000"))))
|
||||
names = [r[1][2] for r in _item_rows(d.tables[3])]
|
||||
assert names == [f"Позиция {i}" for i in range(1, 16)]
|
||||
|
||||
|
||||
def test_system_rows_present_once():
|
||||
items = [_item(i, group="Система А" if i == 1 else "Система Б" if i == 11 else None,
|
||||
code="А" if i == 1 else "Б" if i == 11 else None)
|
||||
for i in range(1, 16)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("15000"))))
|
||||
assert _count_label_in_tables(d, "А — Система А") == 1
|
||||
assert _count_label_in_tables(d, "Б — Система Б") == 1
|
||||
|
||||
|
||||
def test_single_itogo_and_vsyo():
|
||||
items = [_item(i) for i in range(1, 16)]
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("15000"))))
|
||||
itogo = vsyo = 0
|
||||
for t in d.tables:
|
||||
for row in t.rows:
|
||||
txt = row.cells[0].text
|
||||
if "Всего по акту" in txt:
|
||||
vsyo += 1
|
||||
elif "Итого" in txt:
|
||||
itogo += 1
|
||||
assert itogo == 1 and vsyo == 1
|
||||
|
||||
|
||||
def test_final_sum_correct():
|
||||
items = [_item(i) for i in range(1, 21)] # 20 × 1005
|
||||
d = _open(render_ks2_word(_dto(items, total=Decimal("20100"))))
|
||||
t4 = d.tables[4]
|
||||
assert _raw_row(t4, 0)[-1] == "20 100,00"
|
||||
assert _raw_row(t4, 1)[-1] == "20 100,00"
|
||||
|
||||
|
||||
def test_header_repeat_on_works_table():
|
||||
items = [_item(i) for i in range(1, 6)]
|
||||
d = _open(render_ks2_word(_dto(items)))
|
||||
t3 = d.tables[3]
|
||||
for ri in range(3):
|
||||
trPr = t3.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"
|
||||
|
||||
|
||||
def test_signatures_after_totals():
|
||||
items = [_item(i) for i in range(1, 6)]
|
||||
d = _open(render_ks2_word(_dto(items)))
|
||||
order = [id(t._tbl) for t in d.tables]
|
||||
# works table, totals block, Сдал, Принял
|
||||
idx_works = 3
|
||||
idx_totals = 4
|
||||
idx_sdal = 5
|
||||
idx_prinyal = 6
|
||||
assert idx_works < idx_totals < idx_sdal < idx_prinyal
|
||||
assert "Итого" in _raw_row(d.tables[idx_totals], 0)[0]
|
||||
assert _raw_row(d.tables[idx_sdal], 0)[0] == "Сдал"
|
||||
assert _raw_row(d.tables[idx_prinyal], 0)[0] == "Принял"
|
||||
|
||||
|
||||
def test_storno_still_works_with_single_table():
|
||||
d = _open(render_ks2_word(_dto([_item(1)], status="cancelled")))
|
||||
text = _all_text(d)
|
||||
assert "СТОРНИРОВАН" in text
|
||||
assert len(d.tables[3].rows) >= 4
|
||||
assert "Итого" in _raw_row(d.tables[4], 0)[0]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Grouping
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_group_headers():
|
||||
items = [
|
||||
_item(1, group="Автоматическая установка", code="АУПС", name="А1"),
|
||||
_item(2, name="А2"),
|
||||
_item(3, group="Отопление", code="ОВ", name="Б1"),
|
||||
]
|
||||
d = _open(render_ks2_word(_dto(items)))
|
||||
text = _all_text(d)
|
||||
assert "АУПС — Автоматическая установка" in text
|
||||
assert "ОВ — Отопление" in text
|
||||
t3 = d.tables[3]
|
||||
# group row is a single merged cell (8 columns combined)
|
||||
tr = t3.rows[3]._tr
|
||||
tcs = tr.findall(qn("w:tc"))
|
||||
assert len(tcs) == 1, f"group row must merge all cells, got {len(tcs)}"
|
||||
gs = tcs[0].find(qn("w:tcPr")).find(qn("w:gridSpan"))
|
||||
assert gs is not None and gs.get(qn("w:val")) == "8"
|
||||
assert "АУПС — Автоматическая установка" in "".join(
|
||||
t.text or "" for t in tcs[0].iter(qn("w:t"))
|
||||
)
|
||||
|
||||
|
||||
def test_group_header_without_code():
|
||||
items = [_item(1, group="Система А", name="А1")]
|
||||
d = _open(render_ks2_word(_dto(items)))
|
||||
text = _all_text(d)
|
||||
assert "Система А" in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Money / qty formatters
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_format_money():
|
||||
from app.exporters.word.ks2_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"
|
||||
assert format_money(Decimal("0.5")) == "0,50"
|
||||
assert format_money(Decimal("1234567.891")) == "1 234 567,89"
|
||||
assert format_money(Decimal("-1234.5")) == "-1 234,50"
|
||||
|
||||
|
||||
def test_format_qty():
|
||||
from app.exporters.word.ks2_renderer import format_qty
|
||||
assert format_qty(Decimal("17")) == "17,00"
|
||||
assert format_qty(Decimal("12.345")) == "12,34"
|
||||
assert format_qty(Decimal("17.5")) == "17,50"
|
||||
|
||||
|
||||
def test_no_dot_decimal_or_currency_in_table():
|
||||
d = _open(render_ks2_word(_dto([_item(1)])))
|
||||
text = _all_text(d)
|
||||
assert "100.50" not in text
|
||||
assert "1005.00" not in text
|
||||
assert "₽" not in text
|
||||
assert "RUB" not in text
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Signatures
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_signatures():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
t5 = d.tables[5]
|
||||
row0 = _raw_row(t5, 0)
|
||||
assert row0[0] == "Сдал"
|
||||
assert row0[1] == "Директор"
|
||||
assert row0[5] == "Иванов И.И."
|
||||
t6 = d.tables[6]
|
||||
row0 = _raw_row(t6, 0)
|
||||
assert row0[0] == "Принял"
|
||||
assert row0[1] == "Начальник"
|
||||
assert row0[5] == "Петров П.П."
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# STORNO
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_cancelled_storno_present_and_formatted():
|
||||
d = _open(render_ks2_word(_dto(status="cancelled")))
|
||||
found = False
|
||||
for p in d.paragraphs:
|
||||
if "СТОРНИРОВАН" in p.text:
|
||||
found = True
|
||||
for run in p.runs:
|
||||
if "СТОРНИРОВАН" in run.text:
|
||||
assert run.bold
|
||||
assert run.font.color is not None and run.font.color.rgb is not None
|
||||
assert str(run.font.color.rgb) == "FF0000"
|
||||
assert found
|
||||
|
||||
|
||||
def test_issued_no_storno():
|
||||
d = _open(render_ks2_word(_dto(status="issued")))
|
||||
assert "СТОРНИРОВАН" not in _all_text(d)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Structure preserved
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_no_unresolved_markers():
|
||||
text = _all_text(_open(render_ks2_word(_dto())))
|
||||
assert "{{" not in text
|
||||
assert "##" not in text
|
||||
|
||||
|
||||
def test_returns_bytes_and_opens():
|
||||
data = render_ks2_word(_dto())
|
||||
assert isinstance(data, bytes)
|
||||
d = _open(data)
|
||||
assert len(d.tables) == 7
|
||||
|
||||
|
||||
def test_template_not_modified():
|
||||
import hashlib
|
||||
before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||
render_ks2_word(_dto())
|
||||
render_ks2_word(_dto(status="cancelled"))
|
||||
after = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||
assert before == after
|
||||
|
||||
|
||||
def test_original_official_template_untouched():
|
||||
from pathlib import Path
|
||||
official = Path("docs/templates/official/КС-2.docx")
|
||||
if official.is_file():
|
||||
import hashlib
|
||||
# rendering must not touch the official source
|
||||
before = hashlib.sha256(official.read_bytes()).hexdigest()
|
||||
render_ks2_word(_dto())
|
||||
after = hashlib.sha256(official.read_bytes()).hexdigest()
|
||||
assert before == after
|
||||
@@ -0,0 +1,287 @@
|
||||
"""Tests for DOC-C4: named template markers in the KS-2 Word template.
|
||||
|
||||
The template (ks2_ru_markers.docx) owns the layout; Python owns the data.
|
||||
Static header fields are `{{name}}` markers replaced by fill_template_markers().
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
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.ks2_dto import KS2ExportDocument, KS2ExportHeader, KS2ExportItem
|
||||
from app.exporters.word.ks2_renderer import (
|
||||
TEMPLATE_FILE,
|
||||
build_ks2_template_fields,
|
||||
render_ks2_word,
|
||||
)
|
||||
from app.exporters.word.template_markers import (
|
||||
MARKER_RE,
|
||||
REQUIRED_KS2_MARKERS,
|
||||
fill_template_markers,
|
||||
)
|
||||
|
||||
OFFICIAL_BLANK = Path("docs/templates/official/КС-2.docx")
|
||||
|
||||
|
||||
def _header(**overrides):
|
||||
values = dict(
|
||||
project_name="P",
|
||||
customer="ООО Заказчик",
|
||||
contract_number="Д-21",
|
||||
contract_date=date(2026, 9, 21),
|
||||
currency="RUB",
|
||||
ks2_number="К2-7",
|
||||
ks2_date=date(2026, 3, 1),
|
||||
period_from=date(2026, 2, 1),
|
||||
period_to=date(2026, 2, 28),
|
||||
comment="",
|
||||
status="issued",
|
||||
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="Петров П.П.",
|
||||
)
|
||||
values.update(overrides)
|
||||
return KS2ExportHeader(**values)
|
||||
|
||||
|
||||
def _item(n=1):
|
||||
return KS2ExportItem(
|
||||
row_number=n,
|
||||
source_number=str(n),
|
||||
name=f"Работа {n}",
|
||||
unit="шт",
|
||||
quantity=Decimal("10"),
|
||||
unit_price=Decimal("100.5"),
|
||||
amount=Decimal("1005"),
|
||||
)
|
||||
|
||||
|
||||
def _dto(header=None, items=None):
|
||||
items = items if items is not None else [_item()]
|
||||
total = sum((i.amount for i in items), Decimal("0"))
|
||||
return KS2ExportDocument(header=header or _header(), items=items, total=total)
|
||||
|
||||
|
||||
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 _all_text(doc):
|
||||
parts = [p.text for p in doc.paragraphs]
|
||||
for t in doc.tables:
|
||||
for row in t.rows:
|
||||
for c in row.cells:
|
||||
parts.append(c.text)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. All required markers live in the working template
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_template_exists():
|
||||
assert TEMPLATE_FILE.is_file()
|
||||
assert TEMPLATE_FILE.name == "ks2_ru_markers.docx"
|
||||
|
||||
|
||||
def test_all_required_markers_present_in_template():
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
text = "\n".join(t.text or "" for t in d.element.iter(qn("w:t")))
|
||||
missing = [n for n in REQUIRED_KS2_MARKERS if "{{" + n + "}}" not in text]
|
||||
assert not missing, f"missing markers: {missing}"
|
||||
|
||||
|
||||
def test_each_marker_sits_in_a_single_run():
|
||||
"""Word may split text across runs; in this template every marker is whole."""
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
for t in d.element.iter(qn("w:t")):
|
||||
text = t.text or ""
|
||||
assert text.count("{{") == len(MARKER_RE.findall(text)), text
|
||||
assert text.count("}}") == len(MARKER_RE.findall(text)), text
|
||||
|
||||
|
||||
def test_marker_template_keeps_official_blank_geometry():
|
||||
"""Static cells are markers only — tables/merges match the official blank."""
|
||||
if not OFFICIAL_BLANK.is_file():
|
||||
pytest.skip("official blank not present")
|
||||
|
||||
def structure(path):
|
||||
sig = []
|
||||
for tbl in Document(str(path)).tables:
|
||||
rows = []
|
||||
for row in tbl.rows:
|
||||
cells = []
|
||||
for tc in row._tr.findall(qn("w:tc")):
|
||||
tcPr = tc.find(qn("w:tcPr"))
|
||||
vm = gs = None
|
||||
if tcPr is not None:
|
||||
v = tcPr.find(qn("w:vMerge"))
|
||||
vm = (v.get(qn("w:val")) or "continue") if v is not None else None
|
||||
g = tcPr.find(qn("w:gridSpan"))
|
||||
gs = g.get(qn("w:val")) if g is not None else None
|
||||
cells.append((vm, gs))
|
||||
rows.append(tuple(cells))
|
||||
sig.append(tuple(rows))
|
||||
return sig
|
||||
|
||||
official = structure(OFFICIAL_BLANK)
|
||||
marked = structure(TEMPLATE_FILE)
|
||||
# header, doc block, contract sum and both signature tables (not the
|
||||
# dynamic works tables, whose slot count is renderer-managed)
|
||||
for ti in (0, 1, 2, 5, 6):
|
||||
assert marked[ti] == official[ti], f"geometry differs in table t{ti}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2-3. fill_template_markers() replaces values; nothing {{...}} is left
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_fill_template_markers_replaces_markers_with_values():
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
fields = build_ks2_template_fields(_dto())
|
||||
replaced = fill_template_markers(d, fields)
|
||||
assert replaced == len(REQUIRED_KS2_MARKERS)
|
||||
text = _all_text(d)
|
||||
assert "К2-7" in text
|
||||
assert "ООО Инвестор" in text
|
||||
assert "{{" not in text and "}}" not in text
|
||||
|
||||
|
||||
def test_build_fields_covers_every_required_marker():
|
||||
fields = build_ks2_template_fields(_dto())
|
||||
assert set(fields) == set(REQUIRED_KS2_MARKERS)
|
||||
for name in REQUIRED_KS2_MARKERS:
|
||||
assert isinstance(fields[name], str)
|
||||
|
||||
|
||||
def test_no_unresolved_markers_in_rendered_docx():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
raw = "\n".join(t.text or "" for t in d.element.iter(qn("w:t")))
|
||||
assert not MARKER_RE.search(raw)
|
||||
assert "{{" not in raw and "}}" not in raw
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Money field
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_contract_amount_formatted_as_money():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
t2 = d.tables[2]
|
||||
row = _raw_row(t2, 0)
|
||||
assert row[1] == "18 600 000,00"
|
||||
assert "18 600 000,00" in _all_text(d)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Contract date 21 | 09 | 2026
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_contract_date_day_month_year_boxes():
|
||||
d = _open(render_ks2_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] == ["21", "09", "2026"], boxes
|
||||
break
|
||||
else:
|
||||
pytest.fail("дата row not found")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 6. Other static fields get correct values
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_static_header_fields_values():
|
||||
d = _open(render_ks2_word(_dto()))
|
||||
text = _all_text(d)
|
||||
for expected in (
|
||||
"ООО Инвестор",
|
||||
"ООО Заказчик",
|
||||
"ООО Подрядчик",
|
||||
"Стройка — коттеджный посёлок",
|
||||
"Жилой дом",
|
||||
"Д-21",
|
||||
):
|
||||
assert expected in text, expected
|
||||
|
||||
t1 = d.tables[1]
|
||||
r0 = _raw_row(t1, 0)
|
||||
r1 = _raw_row(t1, 1)
|
||||
r2 = _raw_row(t1, 2)
|
||||
# labels in row 0; marker value row r2 holds filled values (DOC-C4 layout)
|
||||
assert "Номер документа" in r0[1]
|
||||
assert "К2-7" in r2[1]
|
||||
assert "Дата составления" in r0[2]
|
||||
assert "01.03.2026" in r2[2]
|
||||
assert "с" in r1[4] and "по" in r1[5]
|
||||
assert "01.02.2026" in r2[4]
|
||||
assert "28.02.2026" in r2[5]
|
||||
|
||||
t5 = _raw_row(d.tables[5], 0)
|
||||
assert t5[1] == "Директор"
|
||||
assert t5[5] == "Иванов И.И."
|
||||
t6 = _raw_row(d.tables[6], 0)
|
||||
assert t6[1] == "Начальник УКС"
|
||||
assert t6[5] == "Петров П.П."
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 7. A missing optional marker never breaks the export
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_missing_optional_marker_value_does_not_break_export():
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
# only one value provided: every other marker must degrade to ""
|
||||
replaced = fill_template_markers(d, {"ks2_number": "X"})
|
||||
assert replaced == len(REQUIRED_KS2_MARKERS)
|
||||
raw = "\n".join(t.text or "" for t in d.element.iter(qn("w:t")))
|
||||
assert "{{" not in raw and "}}" not in raw
|
||||
assert "X" in raw
|
||||
|
||||
|
||||
def test_render_with_empty_optional_fields():
|
||||
h = _header(
|
||||
contract_amount="",
|
||||
investor_name="",
|
||||
construction_name="",
|
||||
object_name="",
|
||||
contract_date=None,
|
||||
period_from=None,
|
||||
period_to=None,
|
||||
contractor_signer_name="",
|
||||
contractor_signer_position="",
|
||||
customer_signer_name="",
|
||||
customer_signer_position="",
|
||||
)
|
||||
d = _open(render_ks2_word(_dto(header=h)))
|
||||
raw = "\n".join(t.text or "" for t in d.element.iter(qn("w:t")))
|
||||
assert not MARKER_RE.search(raw)
|
||||
assert "{{" not in raw and "}}" not in raw
|
||||
assert "К2-7" in raw # required fields still fill
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# The dynamic works table is untouched by markers
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_dynamic_works_table_still_filled_by_code():
|
||||
items = [_item(i) for i in range(1, 4)]
|
||||
d = _open(render_ks2_word(_dto(items=items)))
|
||||
t3 = d.tables[3]
|
||||
rows = [_raw_row(t3, ri) for ri in range(3, 6)]
|
||||
assert [r[2] for r in rows] == ["Работа 1", "Работа 2", "Работа 3"]
|
||||
assert [r[7] for r in rows] == ["1 005,00", "1 005,00", "1 005,00"]
|
||||
@@ -216,8 +216,8 @@ def test_excel_total_matches(tmp_path):
|
||||
total_found = False
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value == "Итого:":
|
||||
total_cell = ws.cell(row=cell.row, column=7)
|
||||
if cell.value and "ВСЕГО" in str(cell.value):
|
||||
total_cell = ws.cell(row=cell.row, column=11)
|
||||
assert abs(float(total_cell.value) - 1500.0) < 0.01
|
||||
total_found = True
|
||||
assert total_found
|
||||
|
||||
@@ -138,16 +138,15 @@ 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 "Export polish" in text
|
||||
assert "К2-7" in text or "Унифицированная форма" in text
|
||||
assert "Заказчик ООО" in text
|
||||
assert "DOG-2026-7" in text
|
||||
assert "15.01.2026" in text
|
||||
assert "RUB" in text
|
||||
assert "01.03.2026 — 31.03.2026" in text
|
||||
assert "01.03.2026" in text
|
||||
assert "31.03.2026" in text
|
||||
assert "Монтаж трубопровода" in text
|
||||
assert "500" in text
|
||||
assert "Итого:" in text
|
||||
assert "ВСЕГО" in text
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
@@ -162,12 +161,14 @@ def test_ks2_word_export_key_values(tmp_path):
|
||||
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word")
|
||||
assert resp.status_code == 200
|
||||
_, text = _word_text(resp)
|
||||
assert "Акт КС-2 №7" in text
|
||||
# Official form (DOC-C3): template-based KS-2 Word
|
||||
assert "Унифицированная форма № КС-2" in text
|
||||
assert "0322005" in text
|
||||
assert "DOG-2026-7" in text
|
||||
assert "15.01.2026" in text
|
||||
assert "RUB" in text
|
||||
assert "Итого:" in text
|
||||
assert "500.00" in text
|
||||
# contract date is split into day / month / year boxes
|
||||
assert "15" in text and "2026" in text
|
||||
assert "Итого" in text
|
||||
assert "500,00" in text
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
Reference in New Issue
Block a user