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:
Арсентьев Александр
2026-10-03 19:48:29 +03:00
parent 79c7d4f335
commit bd64bb6307
49 changed files with 6917 additions and 353 deletions
+538 -86
View File
@@ -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}"