feat: KS-3 official Word form with marker template and single-table flow

Rewrite the KS-3 print renderer on the DOC-C4–DOC-C7 architecture:

- working marker template ks3_ru_markers.docx from the official blank;
  static fields via named markers, values only from KS3ExportHeader/Item
- one dynamic works table with w:tblHeader page-break repetition, no
  page/subtable split; final Итого block once at the end, VAT rows left
  empty (unsupported by the DTO)
- unified money formatter (space thousands, comma decimals)
- UI keeps only КС-3 (Word); Excel endpoint remains for internal tests
- DB, KS3↔KS2 links, issue/cancel, payments and KS-2 untouched
This commit is contained in:
Арсентьев Александр
2026-10-03 22:01:37 +03:00
parent bd64bb6307
commit 2b309b007c
6 changed files with 721 additions and 304 deletions
+271 -169
View File
@@ -1,24 +1,28 @@
"""Tests for DOC-B4: template-based KS-3 Word renderer."""
"""Tests for KS-3 official-form Word renderer (DOC-B4 + DOC-C8).
Marker-template architecture (DOC-C4–DOC-C7):
static fields via named markers, one dynamic works table with natural
pagination and repeating header, final totals only at the end.
"""
from __future__ import annotations
import hashlib
import io
import json
from datetime import date
from decimal import Decimal
from pathlib import Path
import pytest
from docx import Document
from docx.oxml.ns import qn
from app.exporters.ks3_dto import KS3ExportDocument, KS3ExportHeader, KS3ExportItem
from app.exporters.word.ks3_renderer import (
MANIFEST_FILE,
TEMPLATE_FILE,
TEMPLATE_TYPE,
TEMPLATE_VERSION,
TemplateNotFoundError,
load_template_manifest,
build_ks3_template_fields,
render_ks3_word,
)
@@ -36,6 +40,16 @@ def _dto(items=None, total=None, status="issued"):
period_to=date(2026, 2, 28),
comment="Комментарий",
status=status,
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="Петров П.П.",
)
if items is None:
items = [
@@ -53,10 +67,26 @@ def _dto(items=None, total=None, status="issued"):
return KS3ExportDocument(header=header, items=items, total=total)
def _item(n, amount="100.50"):
return KS3ExportItem(
row_number=n,
ks2_number=f"К2-{n}",
ks2_date=date(2026, 2, 1),
period_from=date(2026, 2, 1),
period_to=date(2026, 2, 28),
amount=Decimal(amount),
)
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 _doc_text(document) -> str:
parts = [p.text for p in document.paragraphs]
for table in document.tables:
@@ -65,13 +95,21 @@ def _doc_text(document) -> str:
return "\n".join(parts)
def _table_rows(document):
"""Return rows of the main KS-2 table as lists of cell texts."""
for table in document.tables:
for row in table.rows:
if "КС-2" in [c.text for c in row.cells]:
return [[c.text for c in r.cells] for r in table.rows]
raise AssertionError("KS-2 table not found")
def _works_table(d):
# t2 is the only dynamic works table
return d.tables[2]
def _item_rows(tbl):
"""Numeric № rows with 6 cells (not the 1..6 column-number header)."""
out = []
for ri in range(len(tbl.rows)):
row = _raw_row(tbl, ri)
if len(row) == 6 and row[0].isdigit():
if row[1] == "2" and row[2] == "3":
continue
out.append((ri, row))
return out
# ---------------------------------------------------------------------------
@@ -80,160 +118,237 @@ def _table_rows(document):
def test_template_exists():
assert TEMPLATE_FILE.is_file()
assert TEMPLATE_FILE.suffix == ".docx"
assert "markers" in TEMPLATE_FILE.name
def test_manifest_valid():
manifest = load_template_manifest()
assert manifest["template_type"] == TEMPLATE_TYPE
assert manifest["template_version"] == TEMPLATE_VERSION
assert manifest["file"] == TEMPLATE_FILE.name
assert manifest["table_marker"] == "##KS3_KS2_ROWS##"
assert manifest["totals_marker"] == "##KS3_TOTALS##"
assert manifest["storno_marker"] == "##KS3_STORNO##"
def test_template_type_and_version():
assert TEMPLATE_TYPE == "ks3"
assert TEMPLATE_VERSION == 1
def test_template_opens_with_python_docx():
def test_markers_present_in_working_template():
d = Document(str(TEMPLATE_FILE))
assert len(d.paragraphs) > 0
assert len(d.tables) > 0
text = _doc_text(d)
for marker in (
"{{ks3_number}}", "{{ks3_date}}",
"{{investor}}", "{{customer}}", "{{contractor}}", "{{construction}}",
"{{contract_number}}",
"{{contract_date_day}}", "{{contract_date_month}}", "{{contract_date_year}}",
"{{report_from}}", "{{report_to}}",
"{{contractor_signer_name}}", "{{contractor_signer_position}}",
"{{customer_signer_name}}", "{{customer_signer_position}}",
"##KS3_ROW##",
):
assert marker in text, marker
# the official KS-3 blank has no contract-amount line (unlike KS-2)
assert "{{contract_amount}}" not in text
def test_missing_template_raises(monkeypatch):
monkeypatch.setattr(
"app.exporters.word.ks3_renderer.TEMPLATE_FILE",
Path("/nonexistent/ks3_ru_markers.docx"),
)
with pytest.raises(TemplateNotFoundError):
render_ks3_word(_dto())
# ---------------------------------------------------------------------------
# Header
# Markers replaced
# ---------------------------------------------------------------------------
def test_header_number_date_period_requisites():
data = render_ks3_word(_dto())
text = _doc_text(_open(data))
assert "К3-1" in text
assert "01.03.2026" in text
assert "01.02.2026 — 28.02.2026" in text
assert "Тестовый проект" in text
def test_markers_are_replaced():
d = _open(render_ks3_word(_dto()))
text = _doc_text(d)
assert "{{" not in text
assert "##" not in text
def test_number_and_dates_in_place():
d = _open(render_ks3_word(_dto()))
t1 = d.tables[1]
r2 = _raw_row(t1, 2)
assert "К3-1" in r2[1]
assert "01.03.2026" in r2[2]
assert "01.02.2026" in r2[4]
assert "28.02.2026" in r2[5]
def test_contract_date_split_day_month_year():
d = _open(render_ks3_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_header_requisites():
d = _open(render_ks3_word(_dto()))
text = _doc_text(d)
assert "0322001" 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_build_fields_money_format():
fields = build_ks3_template_fields(_dto())
assert fields["contract_amount"] == "18 600 000,00"
assert fields["ks3_number"] == "К3-1"
# ---------------------------------------------------------------------------
# Rows
# Money
# ---------------------------------------------------------------------------
def test_single_ks2_row():
data = render_ks3_word(_dto())
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
assert len(data_rows) == 1
assert data_rows[0][1] == "№К2-1"
assert data_rows[0][2] == "01.02.2026"
def test_money_formatter():
from app.exporters.word.ks3_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"
def test_multiple_ks2_rows():
items = [
KS3ExportItem(1, "К2-1", date(2026, 2, 1), date(2026, 2, 1), date(2026, 2, 28), Decimal("100")),
KS3ExportItem(2, "К2-2", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("200")),
KS3ExportItem(3, "К2-3", date(2026, 2, 28), date(2026, 2, 1), date(2026, 2, 28), Decimal("300")),
]
data = render_ks3_word(_dto(items=items))
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
assert len(data_rows) == 3
assert [r[1] for r in data_rows] == ["№К2-1", "№К2-2", "№К2-3"]
def test_row_count_matches_dto():
items = [
KS3ExportItem(i, f"К2-{i}", date(2026, 2, i), None, None, Decimal(str(i * 10)))
for i in range(1, 6)
]
data = render_ks3_word(_dto(items=items))
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
assert len(data_rows) == 5
def test_numbers_dates_periods_displayed():
item = KS3ExportItem(1, "К2-9", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("123.45"))
data = render_ks3_word(_dto(items=[item]))
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
assert data_rows[0][1] == "№К2-9"
assert data_rows[0][2] == "15.02.2026"
assert data_rows[0][3] == "01.02.2026 — 28.02.2026"
assert data_rows[0][4] == "123.45"
def test_money_uses_formatter():
item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1234.5"))
data = render_ks3_word(_dto(items=[item]))
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
# MONEY_TEXT format is "{:.2f}"
assert data_rows[0][4] == "1234.50"
def test_decimal_not_via_float():
# Values that are not exact in binary floating point
item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("0.10"))
data = render_ks3_word(_dto(items=[item], total=Decimal("0.30")))
text = _doc_text(_open(data))
assert "0.10" in text
assert "0.30" in text
def test_formatting_preserved():
data = render_ks3_word(_dto())
d = _open(data)
rows = _table_rows(d)
# Table Grid style preserved
table = d.tables[0]
assert table.style.name == "Table Grid"
def test_zero_rows_no_fake_position():
data = render_ks3_word(_dto(items=[], total=Decimal("0")))
rows = _table_rows(_open(data))
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
assert len(data_rows) == 1
assert data_rows[0][0] == "—"
assert data_rows[0][1] == "—"
def test_no_dot_decimal_or_currency():
text = _doc_text(_open(render_ks3_word(_dto())))
assert "100.50" not in text
assert "₽" not in text
assert "RUB" not in text
# ---------------------------------------------------------------------------
# Totals
# One KS2 / several KS2 / summation
# ---------------------------------------------------------------------------
def test_total_from_dto():
items = [
KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("100")),
KS3ExportItem(2, "К2-2", date(2026, 2, 2), None, None, Decimal("100")),
]
data = render_ks3_word(_dto(items=items, total=Decimal("200.00")))
rows = _table_rows(_open(data))
total_row = next(r for r in rows if "Итого:" in r[0])
assert total_row[4] == "200.00"
def test_single_ks2():
d = _open(render_ks3_word(_dto([_item(1, "31293.36")], total=Decimal("31293.36"))))
rows = _item_rows(_works_table(d))
assert len(rows) == 1
assert rows[0][1][0] == "1"
assert "КС-2 №К2-1" in rows[0][1][1]
assert rows[0][1][5] == "31 293,36"
def test_multiple_ks2_presented_once_each():
items = [_item(i) for i in range(1, 4)]
d = _open(render_ks3_word(_dto(items, total=Decimal("301.50"))))
rows = _item_rows(_works_table(d))
assert [r[1][0] for r in rows] == ["1", "2", "3"]
assert [f"КС-2 №К2-{i}" in r[1][1] for r, i in zip(rows, range(1, 4))] == [True, True, True]
def test_summation_matches_dto_total():
items = [_item(i, "1000") for i in range(1, 6)]
d = _open(render_ks3_word(_dto(items, total=Decimal("5000"))))
t = _works_table(d)
itogo = [ri for ri in range(len(t.rows)) if "Итого" in _raw_row(t, ri)[0]]
assert len(itogo) == 1
assert _raw_row(t, itogo[0])[-1] == "5 000,00"
def test_renderer_does_not_recompute_total():
items = [KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1.00"))]
data = render_ks3_word(_dto(items=items, total=Decimal("999.00")))
rows = _table_rows(_open(data))
total_row = next(r for r in rows if "Итого:" in r[0])
assert total_row[4] == "999.00"
items = [_item(1, "100")]
d = _open(render_ks3_word(_dto(items, total=Decimal("999.00"))))
t = _works_table(d)
itogo = next(ri for ri in range(len(t.rows)) if "Итого" in _raw_row(t, ri)[0])
assert _raw_row(t, itogo)[-1] == "999,00"
# ---------------------------------------------------------------------------
# Storno
# DOC-C8: one dynamic table, no page subtotals
# ---------------------------------------------------------------------------
def test_cancelled_output_has_storno():
data = render_ks3_word(_dto(status="cancelled"))
text = _doc_text(_open(data))
def test_single_dynamic_table_no_continuation():
items = [_item(i) for i in range(1, 21)]
d = _open(render_ks3_word(_dto(items, total=Decimal("20100"))))
t = _works_table(d)
assert len(_item_rows(t)) == 20
# no other table contains item rows
for ti, other in enumerate(d.tables):
if ti == 2:
continue
assert _item_rows(other) == [], f"t{ti} has item rows"
def test_no_intermediate_page_subtotal():
items = [_item(i) for i in range(1, 21)]
d = _open(render_ks3_word(_dto(items, total=Decimal("20100"))))
text = _doc_text(d)
# exactly one Итого (final), no page subtotal copies
assert sum(1 for t in d.tables for row in t.rows
if "Итого" in row.cells[0].text and "Всего" not in row.cells[0].text) == 1
def test_final_totals_once_at_end():
items = [_item(i) for i in range(1, 16)]
d = _open(render_ks3_word(_dto(items, total=Decimal("15075"))))
t = _works_table(d)
rows = [_raw_row(t, ri) for ri in range(len(t.rows))]
itogo = [i for i, r in enumerate(rows) if "Итого" in r[0] and "Всего" not in r[0]]
assert len(itogo) == 1
# Итого is after the last item
last_item = max(i for i, r in enumerate(rows) if len(r) == 6 and r[0].isdigit())
assert itogo[0] > last_item
assert rows[itogo[0]][-1] == "15 075,00"
# НДС rows exist in the official blank but stay empty (not supported)
nds = [r for r in rows if "НДС" in r[0]]
assert nds, "official blank has VAT rows"
for r in nds:
assert r[-1] == ""
def test_header_repeat_on_works_table():
d = _open(render_ks3_word(_dto([_item(i) for i in range(1, 6)])))
t = _works_table(d)
for ri in range(3):
trPr = t.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"
# ---------------------------------------------------------------------------
# Signatures after totals / storno
# ---------------------------------------------------------------------------
def test_signatures_after_totals():
d = _open(render_ks3_word(_dto([_item(1)])))
# t2 works, t3 Заказчик, t4 Подрядчик
assert "Заказчик (Генподрядчик)" in _raw_row(d.tables[3], 0)[0]
assert "Подрядчик (Субподрядчик)" in _raw_row(d.tables[4], 0)[0]
t2_last = len(_works_table(d).rows) - 1
assert "НДС" in _raw_row(_works_table(d), t2_last)[0] or "Всего" in _raw_row(_works_table(d), t2_last)[0]
def test_signers_filled():
d = _open(render_ks3_word(_dto()))
t3 = _raw_row(d.tables[3], 0)
t4 = _raw_row(d.tables[4], 0)
assert t3[1] == "Начальник УКС"
assert t3[5] == "Петров П.П."
assert t4[1] == "Директор"
assert t4[5] == "Иванов И.И."
def test_cancelled_has_storno():
d = _open(render_ks3_word(_dto(status="cancelled")))
text = _doc_text(d)
assert "СТОРНИРОВАН" in text
def test_issued_output_has_no_storno():
data = render_ks3_word(_dto(status="issued"))
text = _doc_text(_open(data))
assert "СТОРНИРОВАН" not in text
assert "##KS3_STORNO##" not in text
def test_issued_no_storno():
d = _open(render_ks3_word(_dto(status="issued")))
assert "СТОРНИРОВАН" not in _doc_text(d)
# ---------------------------------------------------------------------------
# Output stability
# ---------------------------------------------------------------------------
def test_returns_bytes_and_opens():
data = render_ks3_word(_dto())
assert isinstance(data, bytes)
d = _open(data)
assert len(d.tables) == 5
def test_template_not_modified():
@@ -244,30 +359,30 @@ def test_template_not_modified():
assert before == after
# ---------------------------------------------------------------------------
# Output / B2
# ---------------------------------------------------------------------------
def test_returns_bytes():
assert isinstance(render_ks3_word(_dto()), bytes)
def test_result_opens_with_python_docx():
data = render_ks3_word(_dto())
d = _open(data)
assert len(d.tables) > 0
def test_rerender_stable():
dto = _dto()
a = _open(render_ks3_word(dto))
b = _open(render_ks3_word(dto))
# python-docx embeds ZIP timestamps, so bytes may differ;
# extracted text content must be identical.
assert _doc_text(a) == _doc_text(b)
assert _table_rows(a) == _table_rows(b)
for ti in range(len(a.tables)):
ta, tb = a.tables[ti], b.tables[ti]
assert len(ta.rows) == len(tb.rows)
for ri in range(len(ta.rows)):
assert _raw_row(ta, ri) == _raw_row(tb, ri)
def test_zero_rows_no_fake_position():
d = _open(render_ks3_word(_dto(items=[], total=Decimal("0"))))
assert _item_rows(_works_table(d)) == []
text = _doc_text(d)
assert "{{" not in text
def test_compatible_with_artifact_service(tmp_path, monkeypatch):
from app.services.document_artifact_service import (
compute_content_hash,
persist_artifact,
resolve_artifact,
)
from app.config import ENV_DOCUMENT_STORAGE_ROOT
from app.database.database import Base
from app.models import ( # noqa: F401
@@ -275,11 +390,6 @@ def test_compatible_with_artifact_service(tmp_path, monkeypatch):
ks2, ks3, payment, project, work_journal,
)
from app.models.project import Project
from app.services.document_artifact_service import (
compute_content_hash,
persist_artifact,
resolve_artifact,
)
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
@@ -287,8 +397,9 @@ def test_compatible_with_artifact_service(tmp_path, monkeypatch):
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "storage"))
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
Base.metadata.create_all(engine)
db = sessionmaker(bind=engine, expire_on_commit=False)()
p = Project(name="B4 integ")
Session = sessionmaker(bind=engine, expire_on_commit=False)
db = Session()
p = Project(name="C8 integ")
db.add(p)
db.commit()
@@ -296,7 +407,7 @@ def test_compatible_with_artifact_service(tmp_path, monkeypatch):
art = persist_artifact(
db,
project_id=p.id,
document_type="ks3",
document_type="KS3",
document_id=1,
format="docx",
template_type=TEMPLATE_TYPE,
@@ -309,17 +420,8 @@ def test_compatible_with_artifact_service(tmp_path, monkeypatch):
assert art.template_version == TEMPLATE_VERSION
assert art.content_hash == compute_content_hash(content)
resolved, body = resolve_artifact(
db, project_id=p.id, document_type="ks3", document_id=1, format="docx"
db, project_id=p.id, document_type="KS3", document_id=1, format="docx"
)
assert body == content
db.close()
engine.dispose()
def test_missing_template_raises(monkeypatch):
monkeypatch.setattr(
"app.exporters.word.ks3_renderer.TEMPLATE_FILE",
Path("/nonexistent/ks3_ru_v1.docx"),
)
with pytest.raises(TemplateNotFoundError):
render_ks3_word(_dto())