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:
+228
-131
@@ -1,179 +1,276 @@
|
||||
"""Template-based Word renderer for KS-3.
|
||||
"""Official-form KS-3 Word renderer (DOC-C8, marker-template architecture).
|
||||
|
||||
DB -> KS3ExportDocument (DTO) -> Template Renderer -> docx bytes
|
||||
KS3ExportDocument -> ks3_ru_markers.docx -> generated DOCX
|
||||
|
||||
The renderer never touches the database or DocumentArtifact service.
|
||||
It loads the versioned template from app/templates_docs/ks3/, fills
|
||||
placeholders and expands the dynamic KS-2 table, and returns bytes.
|
||||
Architecture follows DOC-C4–DOC-C7:
|
||||
- the template owns the geometry (requisites, block titles, signatures);
|
||||
- static fields are named markers filled by fill_template_markers;
|
||||
- one dynamic works table flows across pages (w:tblHeader repeats the
|
||||
column header); no t_left/t_right split and no row-count limits;
|
||||
- money totals sit once at the end (Итого / Сумма НДС / Всего с НДС) —
|
||||
never as a page subtotal.
|
||||
|
||||
Template layout (python-docx tables):
|
||||
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/ОКДП/Договор)
|
||||
t1 Номер документа / Дата составления / Отчетный период + СПРАВКА
|
||||
t2 works table: 3-row header, form rows, data rows, «Итого» block
|
||||
t3 «Заказчик (Генподрядчик)» signatures
|
||||
t4 «Подрядчик (Субподрядчик)» signatures
|
||||
|
||||
Data columns (6): № по порядку | Наименование | Код |
|
||||
с начала проведения работ | с начала года | за отчетный период.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
from copy import deepcopy
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.oxml.ns import qn
|
||||
|
||||
from app.exporters.common import MONEY_TEXT, format_date, format_period
|
||||
from app.exporters.ks3_dto import KS3ExportDocument
|
||||
from app.exporters.word.template_markers import fill_template_markers
|
||||
from app.exporters.word.ks2_renderer import (
|
||||
_clone_row_before,
|
||||
_delete_row,
|
||||
_set_header_repeat,
|
||||
_set_tc_text,
|
||||
format_money,
|
||||
)
|
||||
|
||||
TEMPLATE_TYPE = "ks3"
|
||||
TEMPLATE_VERSION = 1
|
||||
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks3"
|
||||
TEMPLATE_FILE = TEMPLATE_DIR / "ks3_ru_v1.docx"
|
||||
MANIFEST_FILE = TEMPLATE_DIR / "manifest.json"
|
||||
TEMPLATE_FILE = TEMPLATE_DIR / "ks3_ru_markers.docx"
|
||||
|
||||
_ROWS_MARKER = "##KS3_KS2_ROWS##"
|
||||
_TOTALS_MARKER = "##KS3_TOTALS##"
|
||||
_STORNO_MARKER = "##KS3_STORNO##"
|
||||
_ROW_MARKER = "##KS3_ROW##"
|
||||
|
||||
# Column indices inside the 6-column works table.
|
||||
_COL_NUM = 0
|
||||
_COL_NAME = 1
|
||||
_COL_CODE = 2 # always empty
|
||||
_COL_FROM_START = 3 # unsupported by KS3ExportItem
|
||||
_COL_FROM_YEAR = 4 # unsupported by KS3ExportItem
|
||||
_COL_PERIOD = 5 # amount for the reporting period
|
||||
|
||||
# Header rows of the works table that repeat on page breaks.
|
||||
_HEADER_ROWS = 3
|
||||
|
||||
|
||||
class TemplateNotFoundError(FileNotFoundError):
|
||||
"""KS-3 template resource is missing."""
|
||||
pass
|
||||
|
||||
|
||||
def load_template_manifest() -> dict:
|
||||
if not MANIFEST_FILE.is_file():
|
||||
raise TemplateNotFoundError(f"Template manifest not found: {MANIFEST_FILE}")
|
||||
with MANIFEST_FILE.open("r", encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
def _tr(tbl, row_idx):
|
||||
return tbl.rows[row_idx]._tr
|
||||
|
||||
|
||||
def _replace_in_paragraphs(container, mapping: dict[str, str]) -> None:
|
||||
"""Replace {{key}} placeholders in all paragraphs/runs of a container."""
|
||||
for paragraph in container.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
text = run.text
|
||||
for key, value in mapping.items():
|
||||
text = text.replace("{{" + key + "}}", value if value is not None else "")
|
||||
if text != run.text:
|
||||
run.text = text
|
||||
for table in container.tables:
|
||||
for row in table.rows:
|
||||
for cell in row.cells:
|
||||
_replace_in_paragraphs(cell, mapping)
|
||||
def _tcs(tbl, row_idx):
|
||||
"""Raw w:tc elements of a row (merged cells appear once)."""
|
||||
return _tr(tbl, row_idx).findall(qn("w:tc"))
|
||||
|
||||
|
||||
def _find_marker_table(document, marker: str):
|
||||
"""Return (table, row_index) containing the marker in the first cell."""
|
||||
for table in document.tables:
|
||||
for idx, row in enumerate(table.rows):
|
||||
first = row.cells[0].text.strip()
|
||||
if marker in first:
|
||||
return table, idx
|
||||
raise TemplateNotFoundError(f"Marker {marker!r} not found in template")
|
||||
def _fmt_date(value: date | None) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
return f"{value.day:02d}.{value.month:02d}.{value.year}"
|
||||
|
||||
|
||||
def _clear_cell(cell) -> None:
|
||||
for paragraph in cell.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.text = ""
|
||||
def _split_date(value: date | None) -> tuple[str, str, str]:
|
||||
if value is None:
|
||||
return "", "", ""
|
||||
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
|
||||
|
||||
|
||||
def _set_cell(cell, text: str) -> None:
|
||||
if not cell.paragraphs:
|
||||
cell.text = text
|
||||
return
|
||||
paragraph = cell.paragraphs[0]
|
||||
if paragraph.runs:
|
||||
paragraph.runs[0].text = text
|
||||
for extra in paragraph.runs[1:]:
|
||||
extra.text = ""
|
||||
def build_ks3_template_fields(doc: KS3ExportDocument) -> dict[str, str]:
|
||||
"""Named marker values for the static KS-3 header (DOC-C4 contract).
|
||||
|
||||
Values only — layout stays in the template (ks3_ru_markers.docx).
|
||||
Fields that the official blank does not contain (e.g. `object`) are
|
||||
simply absent here and never rendered.
|
||||
"""
|
||||
h = doc.header
|
||||
day, month, year = _split_date(h.contract_date)
|
||||
raw_amount = (h.contract_amount or "").strip()
|
||||
if raw_amount:
|
||||
try:
|
||||
amount = format_money(Decimal(raw_amount))
|
||||
except Exception:
|
||||
amount = raw_amount
|
||||
else:
|
||||
paragraph.add_run(text)
|
||||
amount = ""
|
||||
return {
|
||||
"ks3_number": h.ks3_number or "",
|
||||
"ks3_date": _fmt_date(h.ks3_date),
|
||||
"contract_number": h.contract_number or "",
|
||||
"contract_date_day": day,
|
||||
"contract_date_month": month,
|
||||
"contract_date_year": year,
|
||||
"report_from": _fmt_date(h.period_from),
|
||||
"report_to": _fmt_date(h.period_to),
|
||||
"investor": h.investor_name or "",
|
||||
"customer": h.customer or h.customer_name or "",
|
||||
"contractor": h.contractor_name or "",
|
||||
"construction": h.construction_name or "",
|
||||
"contract_amount": amount,
|
||||
"contractor_signer_name": h.contractor_signer_name or "",
|
||||
"contractor_signer_position": h.contractor_signer_position or "",
|
||||
"customer_signer_name": h.customer_signer_name or "",
|
||||
"customer_signer_position": h.customer_signer_position or "",
|
||||
}
|
||||
|
||||
|
||||
def _clone_row(table, template_row_idx: int, dest_row_idx: int) -> None:
|
||||
"""Copy XML of a template row to a destination row index."""
|
||||
template_tr = table.rows[template_row_idx]._tr
|
||||
dest_tr = table.rows[dest_row_idx]._tr
|
||||
dest_tr.getparent().replace(dest_tr, deepcopy(template_tr))
|
||||
def _find_row_marker(tbl, marker: str) -> int | None:
|
||||
for ri in range(len(tbl.rows)):
|
||||
tcs = _tcs(tbl, ri)
|
||||
if not tcs:
|
||||
continue
|
||||
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||
if marker in "".join(texts):
|
||||
return ri
|
||||
return None
|
||||
|
||||
|
||||
def _insert_row_before(table, before_tr, template_tr):
|
||||
"""Insert a deep copy of template_tr immediately before before_tr."""
|
||||
new_tr = deepcopy(template_tr)
|
||||
before_tr.addprevious(new_tr)
|
||||
return new_tr
|
||||
def _find_text_row(tbl, needle: str) -> int | None:
|
||||
for ri in range(len(tbl.rows)):
|
||||
for tc in _tcs(tbl, ri):
|
||||
texts = [t.text or "" for t in tc.iter(qn("w:t"))]
|
||||
if needle in "".join(texts):
|
||||
return ri
|
||||
return None
|
||||
|
||||
|
||||
def _fill_item_row_tr(tr, item) -> None:
|
||||
"""One KS2 line: number, factual KS2 reference, empty code/cumulative
|
||||
columns (not supported by the DTO), amount in «за отчетный период».
|
||||
"""
|
||||
tcs = tr.findall(qn("w:tc"))
|
||||
if len(tcs) < 6:
|
||||
return
|
||||
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
|
||||
ref = f"КС-2 №{item.ks2_number}" if item.ks2_number else ""
|
||||
if item.ks2_date:
|
||||
ref = f"{ref} от {_fmt_date(item.ks2_date)}" if ref else _fmt_date(item.ks2_date)
|
||||
_set_tc_text(tcs[_COL_NAME], ref, size_pt=9)
|
||||
_set_tc_text(tcs[_COL_CODE], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_FROM_START], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_FROM_YEAR], "", size_pt=9)
|
||||
_set_tc_text(tcs[_COL_PERIOD], format_money(item.amount), size_pt=9, align="right")
|
||||
|
||||
|
||||
def _expand_works_table(tbl, items) -> None:
|
||||
"""Fill the single dynamic works table; clone/delete template rows as needed.
|
||||
|
||||
No page limits and no second continuation table — Word paginates the one
|
||||
table and repeats the header via w:tblHeader.
|
||||
"""
|
||||
first_data = _find_row_marker(tbl, _ROW_MARKER)
|
||||
if first_data is None:
|
||||
# fall back: first empty 6-cell row after the 3-row header
|
||||
for ri in range(_HEADER_ROWS, len(tbl.rows)):
|
||||
tcs = _tcs(tbl, ri)
|
||||
if len(tcs) == 6:
|
||||
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
|
||||
if not "".join(texts).strip():
|
||||
first_data = ri
|
||||
break
|
||||
if first_data is None:
|
||||
return
|
||||
|
||||
itogo_ri = _find_text_row(tbl, "Итого")
|
||||
if itogo_ri is None:
|
||||
return
|
||||
|
||||
needed = len(items)
|
||||
slots = itogo_ri - first_data
|
||||
template_tr = _tr(tbl, first_data)
|
||||
|
||||
# Drop unused data slots (bottom-up).
|
||||
for ri in range(itogo_ri - 1, first_data + needed - 1, -1):
|
||||
if ri >= first_data:
|
||||
_delete_row(tbl, ri)
|
||||
|
||||
# Clone extra rows before the totals block.
|
||||
totals_tr = _tr(tbl, _find_text_row(tbl, "Итого"))
|
||||
for _ in range(max(0, needed - slots)):
|
||||
_clone_row_before(tbl, template_tr, totals_tr)
|
||||
|
||||
start = _find_row_marker(tbl, _ROW_MARKER)
|
||||
if start is None:
|
||||
start = first_data
|
||||
for idx, item in enumerate(items):
|
||||
_fill_item_row_tr(_tr(tbl, start + idx), item)
|
||||
|
||||
|
||||
def _fill_totals(tbl, total) -> None:
|
||||
"""Final money totals at the very end — once, never a page subtotal."""
|
||||
ri = _find_text_row(tbl, "Итого")
|
||||
if ri is None:
|
||||
return
|
||||
tcs = _tcs(tbl, ri)
|
||||
if tcs:
|
||||
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
|
||||
# «Сумма НДС» / «Всего с учетом НДС» stay empty: VAT is not supported
|
||||
# by KS3ExportItem and must not be invented (DOC-C8 §3).
|
||||
|
||||
|
||||
def _place_storno(doc, h) -> None:
|
||||
"""Bold red СТОРНИРОВАН before the СПРАВКА title table (like KS-2)."""
|
||||
if h.status != "cancelled":
|
||||
return
|
||||
body = doc.element.body
|
||||
for child in body:
|
||||
if child.tag != qn("w:tbl"):
|
||||
continue
|
||||
texts = [t.text or "" for t in child.iter(qn("w:t"))]
|
||||
if any("СПРАВКА" in t for t in texts):
|
||||
p = body.makeelement(qn("w:p"), {})
|
||||
child.addprevious(p)
|
||||
pPr = p.makeelement(qn("w:pPr"), {})
|
||||
p.append(pPr)
|
||||
pPr.append(pPr.makeelement(qn("w:jc"), {qn("w:val"): "center"}))
|
||||
run = p.makeelement(qn("w:r"), {})
|
||||
p.append(run)
|
||||
rPr = run.makeelement(qn("w:rPr"), {})
|
||||
run.append(rPr)
|
||||
rPr.append(rPr.makeelement(qn("w:b"), {}))
|
||||
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): "FF0000"}))
|
||||
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): "28"}))
|
||||
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
|
||||
t.text = "СТОРНИРОВАН"
|
||||
run.append(t)
|
||||
break
|
||||
|
||||
|
||||
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
||||
"""Render KS-3 from a template. Returns docx bytes. No DB / no artifact writes."""
|
||||
"""Render official-form KS-3. Returns docx bytes. No DB / no artifact writes."""
|
||||
if not TEMPLATE_FILE.is_file():
|
||||
raise TemplateNotFoundError(f"KS-3 Word template not found: {TEMPLATE_FILE}")
|
||||
|
||||
document = Document(str(TEMPLATE_FILE))
|
||||
h = doc.header
|
||||
|
||||
tables = document.tables
|
||||
if len(tables) < 5:
|
||||
raise TemplateNotFoundError(
|
||||
f"KS-3 template not found: {TEMPLATE_FILE}. "
|
||||
"Add the official template to app/templates_docs/ks3/."
|
||||
f"KS-3 Word template must contain 5 tables, found {len(tables)}"
|
||||
)
|
||||
|
||||
# Work on an in-memory copy; never modify the template on disk.
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
# Static header fields: named template markers own the layout (DOC-C4).
|
||||
fields = build_ks3_template_fields(doc)
|
||||
fill_template_markers(document, fields)
|
||||
|
||||
h = doc.header
|
||||
mapping = {
|
||||
"project_name": h.project_name or "",
|
||||
"customer": h.customer or "",
|
||||
"contract_number": h.contract_number or "",
|
||||
"contract_date": format_date(h.contract_date),
|
||||
"currency": h.currency or "",
|
||||
"period": format_period(h.period_from, h.period_to),
|
||||
"comment": h.comment or "",
|
||||
"ks3_number": h.ks3_number or "",
|
||||
"ks3_date": format_date(h.ks3_date),
|
||||
}
|
||||
_replace_in_paragraphs(d, mapping)
|
||||
# One dynamic works table (t2); Word paginates it naturally.
|
||||
works = tables[2]
|
||||
_expand_works_table(works, list(doc.items))
|
||||
_set_header_repeat(works, _HEADER_ROWS)
|
||||
_fill_totals(works, doc.total)
|
||||
|
||||
# Storno banner
|
||||
for paragraph in d.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
if _STORNO_MARKER in run.text:
|
||||
run.text = "СТОРНИРОВАН" if h.status == "cancelled" else ""
|
||||
|
||||
# Locate template row and totals row in the same table
|
||||
items = list(doc.items)
|
||||
table, rows_idx = _find_marker_table(d, _ROWS_MARKER)
|
||||
totals_table, totals_idx = _find_marker_table(d, _TOTALS_MARKER)
|
||||
if totals_table._tbl is not table._tbl:
|
||||
raise TemplateNotFoundError("KS3_ROWS and KS3_TOTALS must be in the same table")
|
||||
|
||||
template_tr = table.rows[rows_idx]._tr
|
||||
totals_tr = table.rows[totals_idx]._tr
|
||||
|
||||
if not items:
|
||||
# Single placeholder row without fake values
|
||||
row = table.rows[rows_idx]
|
||||
_set_cell(row.cells[0], "—")
|
||||
_set_cell(row.cells[1], "—")
|
||||
_set_cell(row.cells[2], "—")
|
||||
_set_cell(row.cells[3], "—")
|
||||
_set_cell(row.cells[4], "—")
|
||||
else:
|
||||
# First item fills the template row
|
||||
row = table.rows[rows_idx]
|
||||
item = items[0]
|
||||
_set_cell(row.cells[0], str(item.row_number))
|
||||
_set_cell(row.cells[1], f"№{item.ks2_number}")
|
||||
_set_cell(row.cells[2], format_date(item.ks2_date))
|
||||
_set_cell(row.cells[3], format_period(item.period_from, item.period_to))
|
||||
_set_cell(row.cells[4], MONEY_TEXT.format(item.amount))
|
||||
# Insert additional items BEFORE the totals row
|
||||
for item in items[1:]:
|
||||
new_tr = _insert_row_before(table, totals_tr, template_tr)
|
||||
# Re-read the new row from the table object
|
||||
new_row = next(r for r in table.rows if r._tr is new_tr)
|
||||
_set_cell(new_row.cells[0], str(item.row_number))
|
||||
_set_cell(new_row.cells[1], f"№{item.ks2_number}")
|
||||
_set_cell(new_row.cells[2], format_date(item.ks2_date))
|
||||
_set_cell(new_row.cells[3], format_period(item.period_from, item.period_to))
|
||||
_set_cell(new_row.cells[4], MONEY_TEXT.format(item.amount))
|
||||
|
||||
# Totals (locate by stable XML identity — index shifts after inserts)
|
||||
total_row = next(r for r in table.rows if r._tr is totals_tr)
|
||||
_set_cell(total_row.cells[0], "Итого:")
|
||||
_set_cell(total_row.cells[4], MONEY_TEXT.format(doc.total))
|
||||
_place_storno(document, h)
|
||||
|
||||
buf = io.BytesIO()
|
||||
d.save(buf)
|
||||
document.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
|
||||
@@ -30,8 +30,7 @@
|
||||
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||
{% endif %}
|
||||
<div class="mt-2">
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">КС-3 (Word)</a>
|
||||
{% if document.status != 'draft' %}
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/artifact" class="btn btn-outline-dark btn-sm">
|
||||
📎 Официальная форма (Word)
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,216 @@
|
||||
# Implementation Report — DOC-C8 (KS-3 Word marker renderer)
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### Что было сделано
|
||||
|
||||
Печатная форма КС-3 переведена на архитектуру DOC-C4–DOC-C7:
|
||||
шаблон отвечает за геометрию, renderer за данные; статические поля —
|
||||
именованные markers; одна динамическая таблица с естественной пагинацией
|
||||
и повторением заголовка; финальные итоги без промежуточных page subtotal.
|
||||
Из UI убрана Excel-кнопка КС-3, оставлена `КС-3 (Word)`.
|
||||
|
||||
Не изменялись: БД, модель KS3, связь KS3↔KS2, issue/cancel, платежи,
|
||||
КС-2 и его renderer, Excel renderer КС-2 (и Excel renderer КС-3 оставлен
|
||||
как есть — endpoint `/export/excel` работает для внутренних сценариев и
|
||||
тестов), artifact lifecycle (`template_type="ks3"` сохранён), бизнес-логика
|
||||
расчёта KS3.
|
||||
|
||||
---
|
||||
|
||||
## Структура официального КС-3 (`docs/templates/official/КС-3.docx`)
|
||||
|
||||
5 таблиц:
|
||||
|
||||
| Таблица | Содержимое |
|
||||
|---|---|
|
||||
| t0 | Реквизиты: Инвестор / Заказчик / Подрядчик / Стройка / ОКДП / Договор / Вид операции (ОКУД 0322001) |
|
||||
| t1 | Номер документа / Дата составления / Отчетный период + «СПРАВКА» |
|
||||
| t2 | Работы: 3-строчный заголовок, форматные строки, data-строки, «Итого» / «Сумма НДС» / «Всего с учетом НДС» |
|
||||
| t3 | Подписи «Заказчик (Генподрядчик)» |
|
||||
| t4 | Подписи «Подрядчик (Субподрядчик)» |
|
||||
|
||||
Колонки t2 (6): № по порядку | Наименование | Код | с начала проведения работ |
|
||||
с начала года | в том числе за отчетный период.
|
||||
|
||||
Рабочая копия: `app/templates_docs/ks3/ks3_ru_markers.docx`
|
||||
(оригинал `docs/templates/official/КС-3.docx` не изменялся).
|
||||
|
||||
---
|
||||
|
||||
## Markers
|
||||
|
||||
В шаблоне (в существующих ячейках бланка):
|
||||
|
||||
| Marker | Ячейка |
|
||||
|---|---|
|
||||
| `{{investor}}` `{{customer}}` `{{contractor}}` `{{construction}}` | t0 реквизиты |
|
||||
| `{{contract_number}}` | t0 «номер» |
|
||||
| `{{contract_date_day/month/year}}` | t0 «дата» (3 ячейки) |
|
||||
| `{{ks3_number}}` `{{ks3_date}}` `{{report_from}}` `{{report_to}}` | t1 строка значений |
|
||||
| `##KS3_ROW##` | t2 — якорь первой data-строки |
|
||||
| `{{total}}` | t2 «Итого» (заполняется renderer'ом) |
|
||||
| `{{customer_signer_*}}` `{{contractor_signer_*}}` | t3 / t4 |
|
||||
|
||||
Источники — существующий `KS3ExportHeader` / `KS3ExportItem` через
|
||||
`build_ks3_export_dto`. Поиск по русским подписям не используется.
|
||||
|
||||
### Неподдерживаемые официальные поля (оставлены пустыми)
|
||||
|
||||
- ОКПО, Вид деятельности по ОКДП, Вид операции — нет в БД;
|
||||
- `object` (Объект) — в официальном бланке КС-3 **нет** строки «Объект»;
|
||||
- `contract_amount` — в бланке КС-3 нет строки сметной стоимости
|
||||
(в отличие от КС-2); marker не ставится;
|
||||
- «Код» позиции — нет в DTO;
|
||||
- «с начала проведения работ» / «с начала года» — в `KS3ExportItem` есть
|
||||
единственная сумма (`amount` = сумма KS2Item включённого КС-2),
|
||||
новые расчёты не придумывались;
|
||||
- «Сумма НДС» / «Всего с учетом НДС» — НДС не поддерживается моделью.
|
||||
|
||||
### Маппинг data-строки
|
||||
|
||||
| Колонка | Источник |
|
||||
|---|---|
|
||||
| № по порядку | `KS3ExportItem.row_number` |
|
||||
| Наименование | `КС-2 №{ks2_number} от {date}` (фактические поля DTO) |
|
||||
| Код | пусто |
|
||||
| с начала проведения работ | пусто (нет в DTO) |
|
||||
| с начала года | пусто (нет в DTO) |
|
||||
| в том числе за отчетный период | `KS3ExportItem.amount` (money formatter) |
|
||||
|
||||
Суммы считает `build_ks3_export_dto` (существующая бизнес-логика),
|
||||
renderer их только отображает.
|
||||
|
||||
---
|
||||
|
||||
## Архитектура динамической таблицы
|
||||
|
||||
- Одна логическая таблица t2; никакого `t_left/t_right` и `split_at`.
|
||||
- `_set_header_repeat(t2, 3)` — `w:tblHeader` на трёх строках заголовка,
|
||||
Word повторяет их при переносе.
|
||||
- `_expand_works_table` — клонирование/удаление шаблонной строки
|
||||
(`##KS3_ROW##`), без лимитов строк.
|
||||
- Итоговый блок «Итого / Сумма НДС / Всего с учетом НДС» — в конце t2,
|
||||
ровно один раз, page subtotal не выводятся.
|
||||
- Подписи t3/t4 после итогов.
|
||||
|
||||
Money formatter — единый `format_money` (пробел как разделитель тысяч,
|
||||
запятая как десятичный, 2 знака, без валюты).
|
||||
|
||||
---
|
||||
|
||||
## UI
|
||||
|
||||
`app/templates/ks3/view.html`: убрана кнопка `📊 Excel`,
|
||||
оставлена **`КС-3 (Word)`** (`/export/word`). Кнопка официальной формы
|
||||
(artifact) сохранена. Excel-endpoint `/export/excel` физически не удалён.
|
||||
|
||||
---
|
||||
|
||||
## Changed files
|
||||
|
||||
| Файл | Изменение |
|
||||
|---|---|
|
||||
| `app/templates_docs/ks3/ks3_ru_markers.docx` | рабочий marker-шаблон (новый) |
|
||||
| `app/exporters/word/ks3_renderer.py` | полностью переписан под marker-архитектуру |
|
||||
| `app/templates/ks3/view.html` | только `КС-3 (Word)` |
|
||||
| `tests/test_doc_b4_ks3_word_renderer.py` | переписан: 28 regression под новую архитектуру |
|
||||
| `tests/test_task020_export_polish.py` | word-тест КС-3 под официальную форму |
|
||||
| `docs/implementation/DOC-C8.md` | report |
|
||||
|
||||
---
|
||||
|
||||
## Tests
|
||||
|
||||
**pytest -q:** 643 passed (0 failed)
|
||||
|
||||
**Новые/переписанные (28) в `test_doc_b4_ks3_word_renderer.py`:**
|
||||
1. Template exists (markers)
|
||||
2. Template type/version
|
||||
3. Markers есть в рабочем шаблоне
|
||||
4. Missing template raises
|
||||
5. Markers заменяются (нет `{{...}}`)
|
||||
6. Номер и даты в правильных местах
|
||||
7. Contract date разбита на день/месяц/год
|
||||
8. Header requisites (ОКУД 0322001)
|
||||
9. `build_ks3_template_fields` money format
|
||||
10. Money formatter (`31 293,36` / `18 600 000,00`)
|
||||
11. Нет точки как десятичного разделителя / валюты
|
||||
12. KS3 на один KS2
|
||||
13. KS3 на несколько KS2 (каждый ровно один раз)
|
||||
14. Суммирование = total из DTO
|
||||
15. Renderer не пересчитывает total
|
||||
16. Одна динамическая таблица, нет continuation-таблицы
|
||||
17. Нет промежуточных page subtotal
|
||||
18. Финальные итоги один раз, после последней позиции
|
||||
19. `w:tblHeader` на 3 строках заголовка
|
||||
20. Подписи после итогов (Заказчик / Подрядчик)
|
||||
21. Подписанты заполнены
|
||||
22. Cancelled → СТОРНИРОВАН
|
||||
23. Issued → без СТОРНИРОВАН
|
||||
24. Возвращает bytes, 5 таблиц
|
||||
25. Шаблон не изменяется
|
||||
26. Rerender стабилен
|
||||
27. 0 позиций — без фиктивных строк
|
||||
28. Совместим с artifact service (`template_type="ks3"`)
|
||||
|
||||
Существующие KS3 tests (`test_ks3`, `test_task017`, `test_task019`,
|
||||
`test_task022`) и KS2 tests проходят без изменений логики.
|
||||
|
||||
**git diff --check:** чисто (LF→CRLF warning — pre-existing).
|
||||
|
||||
---
|
||||
|
||||
## Визуальная проверка (UI → Word COM → PDF)
|
||||
|
||||
Реальные DOCX скачаны кнопкой **`КС-3 (Word)`** через UI (Playwright).
|
||||
Рендер: Word COM `ExportAsFixedFormat` → PDF → pypdfium2.
|
||||
|
||||
**Visual smoke: 69/69 PASS.**
|
||||
|
||||
| Сценарий | Содержимое | PDF |
|
||||
|---|---|---|
|
||||
| A: один KS2 (2 позиции внутри) | 1 строка | 1 стр. |
|
||||
| B: два KS2 | 2 строки | 1 стр. |
|
||||
| C: 25 KS2 | 25 строк, 2 системы | **2 стр.** |
|
||||
| D: cancelled | 1 строка + СТОРНИРОВАН | 1 стр. |
|
||||
|
||||
PDF сценария C (пагинация):
|
||||
|
||||
| Страница | Содержимое |
|
||||
|---|---|
|
||||
| p1 | шапка, СПРАВКА, **заголовок таблицы**, строки КС-2 №N10…N34 |
|
||||
| p2 | **повторённый заголовок таблицы**, `Итого 50 250,00`, «Сумма НДС» (пусто), «Всего с учетом НДС» (пусто), подписи |
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| UI: `КС-3 (Word)` на месте, Excel-кнопки нет | ✅ |
|
||||
| Официальная шапка / ОКУД 0322001 / СПРАВКА | ✅ |
|
||||
| Дата договора `10 01 2026` по ячейкам | ✅ |
|
||||
| Номер/даты/период в своих местах | ✅ |
|
||||
| Одна таблица, нет continuation | ✅ |
|
||||
| Повтор заголовка на следующей странице | ✅ |
|
||||
| Нет промежуточных итогов | ✅ |
|
||||
| `Итого` ровно один раз, в конце | ✅ |
|
||||
| Суммы в формате `50 250,00` | ✅ |
|
||||
| Подписи после итогов | ✅ |
|
||||
| STORNO | ✅ |
|
||||
| Нет пустых страниц / больших промежутков | ✅ |
|
||||
|
||||
---
|
||||
|
||||
## Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
1. Колонки «с начала проведения работ» и «с начала года» оставлены пустыми:
|
||||
в `KS3ExportItem` есть одна сумма (по КС-2 за период). Если бизнес-логика
|
||||
когда-нибудь начнёт считать накопительные суммы — маппинг уже есть.
|
||||
2. «Сумма НДС» / «Всего с учетом НДС» пустые (НДС не поддерживается).
|
||||
3. Excel renderer КС-3 и endpoint `/export/excel` физически оставлены
|
||||
(тесты task017/019/022 ими пользуются), из UI кнопка убрана.
|
||||
4. Работа не закоммичена (по требованию задачи).
|
||||
@@ -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())
|
||||
|
||||
@@ -192,8 +192,11 @@ def test_ks3_export_key_values(tmp_path):
|
||||
word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word")
|
||||
assert word.status_code == 200
|
||||
_, wtext = _word_text(word)
|
||||
assert "КС-3 № 3" in wtext
|
||||
assert "500.00" in wtext
|
||||
# Official form (DOC-C8): marker-template KS-3 Word
|
||||
assert "Унифицированная форма № КС-3" in wtext
|
||||
assert "0322001" in wtext
|
||||
assert "DOG-2026-7" in wtext
|
||||
assert "500,00" in wtext
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
Reference in New Issue
Block a user