feat: add template-based KS-2 Excel and KS-3 Word renderers
This commit is contained in:
@@ -1,118 +1,186 @@
|
|||||||
"""Excel renderer for KS-2 export using openpyxl."""
|
"""Template-based Excel renderer for KS-2.
|
||||||
|
|
||||||
|
DB -> KS2ExportDocument (DTO) -> Template Renderer -> xlsx bytes
|
||||||
|
|
||||||
|
The renderer never touches the database or DocumentArtifact service.
|
||||||
|
It loads the versioned template from app/templates_docs/ks2/, fills
|
||||||
|
placeholders and expands the dynamic table, and returns bytes.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import io
|
import io
|
||||||
|
import json
|
||||||
|
from copy import copy
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from openpyxl import Workbook
|
from openpyxl import load_workbook
|
||||||
from openpyxl.styles import Alignment, Border, Font, Side
|
|
||||||
from openpyxl.utils import get_column_letter
|
|
||||||
|
|
||||||
from app.exporters.common import (
|
from app.exporters.common import format_date, format_period
|
||||||
MONEY_FMT,
|
|
||||||
MONEY_TEXT,
|
|
||||||
QTY_FMT,
|
|
||||||
QTY_TEXT,
|
|
||||||
format_period,
|
|
||||||
project_requisite_lines,
|
|
||||||
)
|
|
||||||
from app.exporters.ks2_dto import KS2ExportDocument
|
from app.exporters.ks2_dto import KS2ExportDocument
|
||||||
|
|
||||||
THIN = Side(style="thin")
|
TEMPLATE_TYPE = "ks2"
|
||||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
TEMPLATE_VERSION = 1
|
||||||
HEADER_FONT = Font(bold=True, size=11)
|
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
|
||||||
TITLE_FONT = Font(bold=True, size=14)
|
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_v1.xlsx"
|
||||||
|
MANIFEST_FILE = TEMPLATE_DIR / "manifest.json"
|
||||||
|
|
||||||
|
_ROWS_MARKER = "##KS2_ROWS##"
|
||||||
|
_TOTALS_MARKER = "##KS2_TOTALS##"
|
||||||
|
_STORNO_MARKER = "##KS2_STORNO##"
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNotFoundError(FileNotFoundError):
|
||||||
|
"""KS-2 template resource is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
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 _to_number(value: Decimal) -> Decimal | int | float:
|
||||||
|
"""Keep Decimal precision; openpyxl writes numeric cells for Decimal/int/float."""
|
||||||
|
if value is None:
|
||||||
|
return 0
|
||||||
|
if not isinstance(value, Decimal):
|
||||||
|
value = Decimal(str(value))
|
||||||
|
if value == value.to_integral_value():
|
||||||
|
return int(value)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _find_marker_row(ws, marker: str) -> int:
|
||||||
|
for row in range(1, ws.max_row + 1):
|
||||||
|
cell = ws.cell(row=row, column=1)
|
||||||
|
if cell.value is not None and marker in str(cell.value):
|
||||||
|
return row
|
||||||
|
raise TemplateNotFoundError(f"Marker {marker!r} not found in template")
|
||||||
|
|
||||||
|
|
||||||
|
def _replace_placeholders(ws, mapping: dict[str, str]) -> None:
|
||||||
|
for row in ws.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if not isinstance(cell.value, str):
|
||||||
|
continue
|
||||||
|
text = cell.value
|
||||||
|
for key, value in mapping.items():
|
||||||
|
text = text.replace("{{" + key + "}}", value if value is not None else "")
|
||||||
|
if text != cell.value:
|
||||||
|
cell.value = text
|
||||||
|
|
||||||
|
|
||||||
|
def _copy_row_style(ws, src_row: int, dest_row: int, max_col: int) -> None:
|
||||||
|
for col in range(1, max_col + 1):
|
||||||
|
src = ws.cell(row=src_row, column=col)
|
||||||
|
dest = ws.cell(row=dest_row, column=col)
|
||||||
|
if src.has_style:
|
||||||
|
dest.font = copy(src.font)
|
||||||
|
dest.border = copy(src.border)
|
||||||
|
dest.fill = copy(src.fill)
|
||||||
|
dest.number_format = src.number_format
|
||||||
|
dest.protection = copy(src.protection)
|
||||||
|
dest.alignment = copy(src.alignment)
|
||||||
|
dim = ws.row_dimensions[src_row]
|
||||||
|
if dim.height:
|
||||||
|
ws.row_dimensions[dest_row].height = dim.height
|
||||||
|
|
||||||
|
|
||||||
def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
|
def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
|
||||||
wb = Workbook()
|
"""Render KS-2 from a template. Returns xlsx bytes. No DB / no artifact writes."""
|
||||||
ws = wb.active
|
if not TEMPLATE_FILE.is_file():
|
||||||
ws.title = "КС-2"
|
raise TemplateNotFoundError(
|
||||||
|
f"KS-2 template not found: {TEMPLATE_FILE}. "
|
||||||
|
"Add the official template to app/templates_docs/ks2/."
|
||||||
|
)
|
||||||
|
|
||||||
|
# Work on an in-memory copy; never modify the template on disk.
|
||||||
|
wb = load_workbook(TEMPLATE_FILE)
|
||||||
|
ws = wb["КС-2"] if "КС-2" in wb.sheetnames else wb.active
|
||||||
|
|
||||||
h = doc.header
|
h = doc.header
|
||||||
row = 1
|
mapping = {
|
||||||
col_count = 7
|
"project_name": h.project_name or "",
|
||||||
|
"customer": h.customer or "",
|
||||||
# Title
|
"contract_number": h.contract_number or "",
|
||||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
|
"contract_date": format_date(h.contract_date),
|
||||||
c = ws.cell(row=row, column=1, value=f"Акт КС-2 №{h.ks2_number} от {h.ks2_date.strftime('%d.%m.%Y')}")
|
"currency": h.currency or "",
|
||||||
c.font = TITLE_FONT
|
"period": format_period(h.period_from, h.period_to),
|
||||||
c.alignment = Alignment(horizontal="center")
|
"comment": h.comment or "",
|
||||||
row += 1
|
"ks2_number": h.ks2_number or "",
|
||||||
|
"ks2_date": format_date(h.ks2_date),
|
||||||
|
}
|
||||||
|
_replace_placeholders(ws, mapping)
|
||||||
|
|
||||||
|
# Storno banner
|
||||||
|
storno_row = _find_marker_row(ws, _STORNO_MARKER)
|
||||||
if h.status == "cancelled":
|
if h.status == "cancelled":
|
||||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
|
ws.cell(row=storno_row, column=1).value = "СТОРНИРОВАН"
|
||||||
c = ws.cell(row=row, column=1, value="СТОРНИРОВАН")
|
else:
|
||||||
c.font = Font(bold=True, size=12, color="C00000")
|
# Clear the marker row so it does not appear as garbage text.
|
||||||
c.alignment = Alignment(horizontal="center")
|
ws.cell(row=storno_row, column=1).value = None
|
||||||
row += 1
|
|
||||||
|
|
||||||
# Unified project requisites
|
# Dynamic table
|
||||||
header_lines = project_requisite_lines(
|
rows_marker = _find_marker_row(ws, _ROWS_MARKER)
|
||||||
project_name=h.project_name,
|
totals_marker = _find_marker_row(ws, _TOTALS_MARKER)
|
||||||
customer=h.customer,
|
items = list(doc.items)
|
||||||
contract_number=h.contract_number,
|
max_col = 7
|
||||||
contract_date=h.contract_date,
|
|
||||||
currency=h.currency,
|
|
||||||
period_text=format_period(h.period_from, h.period_to),
|
|
||||||
extra=[("Комментарий:", h.comment)],
|
|
||||||
)
|
|
||||||
for label, value in header_lines:
|
|
||||||
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
|
|
||||||
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count)
|
|
||||||
ws.cell(row=row, column=2, value=value)
|
|
||||||
row += 1
|
|
||||||
|
|
||||||
row += 1 # blank row
|
# Snapshot merged ranges so we can restore them after row insertion.
|
||||||
|
merges = [str(r) for r in ws.merged_cells.ranges]
|
||||||
|
|
||||||
# Table header
|
if not items:
|
||||||
columns = ["№", "Наименование работ", "№ позиции в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
|
# Keep a single blank row with dashes — no fake position values.
|
||||||
for col_idx, col_name in enumerate(columns, start=1):
|
for col, value in ((1, "—"), (2, "—"), (3, "—"), (4, "—")):
|
||||||
c = ws.cell(row=row, column=col_idx, value=col_name)
|
ws.cell(row=rows_marker, column=col).value = value
|
||||||
c.font = HEADER_FONT
|
for col in (5, 6, 7):
|
||||||
c.border = BORDER
|
ws.cell(row=rows_marker, column=col).value = 0
|
||||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
data_rows = [rows_marker]
|
||||||
header_row = row
|
else:
|
||||||
row += 1
|
extra = len(items) - 1
|
||||||
|
if extra > 0:
|
||||||
|
# Unmerge anything that would block writes in the insertion zone.
|
||||||
|
for rng in list(ws.merged_cells.ranges):
|
||||||
|
ws.unmerge_cells(str(rng))
|
||||||
|
ws.insert_rows(rows_marker + 1, amount=extra)
|
||||||
|
for offset in range(1, len(items)):
|
||||||
|
_copy_row_style(ws, rows_marker, rows_marker + offset, max_col)
|
||||||
|
for offset, item in enumerate(items):
|
||||||
|
r = rows_marker + offset
|
||||||
|
ws.cell(row=r, column=1).value = item.row_number
|
||||||
|
ws.cell(row=r, column=2).value = item.name or ""
|
||||||
|
ws.cell(row=r, column=3).value = item.source_number or ""
|
||||||
|
ws.cell(row=r, column=4).value = item.unit or ""
|
||||||
|
ws.cell(row=r, column=5).value = _to_number(item.quantity)
|
||||||
|
ws.cell(row=r, column=6).value = _to_number(item.unit_price)
|
||||||
|
ws.cell(row=r, column=7).value = _to_number(item.amount)
|
||||||
|
data_rows = list(range(rows_marker, rows_marker + len(items)))
|
||||||
|
|
||||||
# Items
|
# Restore merged ranges shifted by the insertion.
|
||||||
for item in doc.items:
|
shift = max(len(items) - 1, 0)
|
||||||
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
|
if shift and items:
|
||||||
c = ws.cell(row=row, column=2, value=item.name)
|
for rng in merges:
|
||||||
c.border = BORDER
|
# Openpyxl ranges are 1-based; re-apply with a row offset when
|
||||||
c.alignment = Alignment(wrap_text=True, vertical="top")
|
# the range sits at or below the inserted block.
|
||||||
ws.cell(row=row, column=3, value=item.source_number).border = BORDER
|
from openpyxl.worksheet.cell_range import CellRange
|
||||||
ws.cell(row=row, column=4, value=item.unit).border = BORDER
|
|
||||||
|
|
||||||
c = ws.cell(row=row, column=5, value=float(item.quantity))
|
cr = CellRange(rng)
|
||||||
c.border = BORDER
|
if cr.min_row >= rows_marker + 1:
|
||||||
c.number_format = QTY_FMT
|
cr.shift(row_shift=shift)
|
||||||
|
elif cr.min_row <= rows_marker < cr.max_row:
|
||||||
|
cr.max_row += shift
|
||||||
|
ws.merge_cells(str(cr))
|
||||||
|
|
||||||
c = ws.cell(row=row, column=6, value=float(item.unit_price))
|
# Totals row (marker may have moved)
|
||||||
c.border = BORDER
|
totals_row = _find_marker_row(ws, _TOTALS_MARKER)
|
||||||
c.number_format = MONEY_FMT
|
ws.cell(row=totals_row, column=1).value = "Итого:"
|
||||||
|
ws.cell(row=totals_row, column=7).value = _to_number(doc.total)
|
||||||
|
|
||||||
c = ws.cell(row=row, column=7, value=float(item.amount))
|
# Print area follows the filled content
|
||||||
c.border = BORDER
|
last_row = max(data_rows + [totals_row]) + 2
|
||||||
c.number_format = MONEY_FMT
|
ws.print_area = f"A1:G{last_row}"
|
||||||
row += 1
|
|
||||||
|
|
||||||
# Total row
|
|
||||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=6)
|
|
||||||
c = ws.cell(row=row, column=1, value="Итого:")
|
|
||||||
c.font = HEADER_FONT
|
|
||||||
c.border = BORDER
|
|
||||||
c.alignment = Alignment(horizontal="right")
|
|
||||||
for col in range(2, 7):
|
|
||||||
ws.cell(row=row, column=col).border = BORDER
|
|
||||||
c = ws.cell(row=row, column=7, value=float(doc.total))
|
|
||||||
c.font = HEADER_FONT
|
|
||||||
c.border = BORDER
|
|
||||||
c.number_format = MONEY_FMT
|
|
||||||
|
|
||||||
# Column widths
|
|
||||||
widths = {1: 5, 2: 40, 3: 15, 4: 10, 5: 12, 6: 14, 7: 14}
|
|
||||||
for col, width in widths.items():
|
|
||||||
ws.column_dimensions[get_column_letter(col)].width = width
|
|
||||||
|
|
||||||
ws.freeze_panes = ws.cell(row=header_row + 1, column=1)
|
|
||||||
|
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
wb.save(buf)
|
wb.save(buf)
|
||||||
|
|||||||
@@ -1,92 +1,177 @@
|
|||||||
"""Word renderer for KS-3 export using python-docx."""
|
"""Template-based Word renderer for KS-3.
|
||||||
|
|
||||||
|
DB -> KS3ExportDocument (DTO) -> Template Renderer -> docx bytes
|
||||||
|
|
||||||
|
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.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import io
|
import io
|
||||||
|
import json
|
||||||
|
from copy import deepcopy
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from docx import Document
|
from docx import Document
|
||||||
from docx.enum.section import WD_ORIENT
|
|
||||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
|
||||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
|
||||||
from docx.shared import Pt, RGBColor
|
|
||||||
|
|
||||||
from app.exporters.common import MONEY_TEXT, format_date, format_period, project_requisite_lines
|
from app.exporters.common import MONEY_TEXT, format_date, format_period
|
||||||
from app.exporters.ks3_dto import KS3ExportDocument
|
from app.exporters.ks3_dto import KS3ExportDocument
|
||||||
|
|
||||||
|
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"
|
||||||
|
|
||||||
|
_ROWS_MARKER = "##KS3_KS2_ROWS##"
|
||||||
|
_TOTALS_MARKER = "##KS3_TOTALS##"
|
||||||
|
_STORNO_MARKER = "##KS3_STORNO##"
|
||||||
|
|
||||||
|
|
||||||
|
class TemplateNotFoundError(FileNotFoundError):
|
||||||
|
"""KS-3 template resource is missing."""
|
||||||
|
|
||||||
|
|
||||||
|
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 _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 _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 _clear_cell(cell) -> None:
|
||||||
|
for paragraph in cell.paragraphs:
|
||||||
|
for run in paragraph.runs:
|
||||||
|
run.text = ""
|
||||||
|
|
||||||
|
|
||||||
|
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 = ""
|
||||||
|
else:
|
||||||
|
paragraph.add_run(text)
|
||||||
|
|
||||||
|
|
||||||
|
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 _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 render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
||||||
d = Document()
|
"""Render KS-3 from a template. Returns docx bytes. No DB / no artifact writes."""
|
||||||
h = doc.header
|
if not TEMPLATE_FILE.is_file():
|
||||||
|
raise TemplateNotFoundError(
|
||||||
section = d.sections[0]
|
f"KS-3 template not found: {TEMPLATE_FILE}. "
|
||||||
section.orientation = WD_ORIENT.LANDSCAPE
|
"Add the official template to app/templates_docs/ks3/."
|
||||||
section.page_width, section.page_height = section.page_height, section.page_width
|
|
||||||
|
|
||||||
# Title
|
|
||||||
title = d.add_paragraph()
|
|
||||||
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
||||||
run = title.add_run(f"Акт КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
|
|
||||||
run.bold = True
|
|
||||||
run.font.size = Pt(14)
|
|
||||||
|
|
||||||
if h.status == "cancelled":
|
|
||||||
mark = d.add_paragraph()
|
|
||||||
mark.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
|
||||||
run = mark.add_run("СТОРНИРОВАН")
|
|
||||||
run.bold = True
|
|
||||||
run.font.size = Pt(12)
|
|
||||||
run.font.color.rgb = RGBColor(0xC0, 0x00, 0x00)
|
|
||||||
|
|
||||||
d.add_paragraph()
|
|
||||||
|
|
||||||
header_lines = project_requisite_lines(
|
|
||||||
project_name=h.project_name,
|
|
||||||
customer=h.customer,
|
|
||||||
contract_number=h.contract_number,
|
|
||||||
contract_date=h.contract_date,
|
|
||||||
currency=h.currency,
|
|
||||||
period_text=format_period(h.period_from, h.period_to),
|
|
||||||
extra=[("Комментарий:", h.comment)],
|
|
||||||
)
|
)
|
||||||
for label, value in header_lines:
|
|
||||||
p = d.add_paragraph()
|
|
||||||
run = p.add_run(label + " ")
|
|
||||||
run.bold = True
|
|
||||||
p.add_run(value)
|
|
||||||
|
|
||||||
d.add_paragraph()
|
# Work on an in-memory copy; never modify the template on disk.
|
||||||
|
d = Document(str(TEMPLATE_FILE))
|
||||||
|
|
||||||
# Table
|
h = doc.header
|
||||||
table = d.add_table(rows=1, cols=5)
|
mapping = {
|
||||||
table.style = "Table Grid"
|
"project_name": h.project_name or "",
|
||||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
"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)
|
||||||
|
|
||||||
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
|
# Storno banner
|
||||||
for idx, col_name in enumerate(columns):
|
for paragraph in d.paragraphs:
|
||||||
cell = table.rows[0].cells[idx]
|
|
||||||
cell.text = col_name
|
|
||||||
for paragraph in cell.paragraphs:
|
|
||||||
for run in paragraph.runs:
|
for run in paragraph.runs:
|
||||||
run.bold = True
|
if _STORNO_MARKER in run.text:
|
||||||
run.font.size = Pt(9)
|
run.text = "СТОРНИРОВАН" if h.status == "cancelled" else ""
|
||||||
|
|
||||||
for item in doc.items:
|
# Locate template row and totals row in the same table
|
||||||
row = table.add_row()
|
items = list(doc.items)
|
||||||
row.cells[0].text = str(item.row_number)
|
table, rows_idx = _find_marker_table(d, _ROWS_MARKER)
|
||||||
row.cells[1].text = f"№{item.ks2_number}"
|
totals_table, totals_idx = _find_marker_table(d, _TOTALS_MARKER)
|
||||||
row.cells[2].text = format_date(item.ks2_date)
|
if totals_table._tbl is not table._tbl:
|
||||||
row.cells[3].text = format_period(item.period_from, item.period_to)
|
raise TemplateNotFoundError("KS3_ROWS and KS3_TOTALS must be in the same table")
|
||||||
row.cells[4].text = MONEY_TEXT.format(item.amount)
|
|
||||||
|
|
||||||
# Total row
|
template_tr = table.rows[rows_idx]._tr
|
||||||
total_row = table.add_row()
|
totals_tr = table.rows[totals_idx]._tr
|
||||||
total_row.cells[0].merge(total_row.cells[3])
|
|
||||||
total_row.cells[0].text = "Итого:"
|
if not items:
|
||||||
for paragraph in total_row.cells[0].paragraphs:
|
# Single placeholder row without fake values
|
||||||
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
row = table.rows[rows_idx]
|
||||||
for run in paragraph.runs:
|
_set_cell(row.cells[0], "—")
|
||||||
run.bold = True
|
_set_cell(row.cells[1], "—")
|
||||||
total_row.cells[4].text = MONEY_TEXT.format(doc.total)
|
_set_cell(row.cells[2], "—")
|
||||||
for paragraph in total_row.cells[4].paragraphs:
|
_set_cell(row.cells[3], "—")
|
||||||
for run in paragraph.runs:
|
_set_cell(row.cells[4], "—")
|
||||||
run.bold = True
|
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))
|
||||||
|
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
d.save(buf)
|
d.save(buf)
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"template_type": "ks2",
|
||||||
|
"template_version": 1,
|
||||||
|
"file": "ks2_ru_v1.xlsx",
|
||||||
|
"format": "xlsx",
|
||||||
|
"language": "ru",
|
||||||
|
"description": "Акт КС-2, упрощённая табличная часть (DOC-B3)",
|
||||||
|
"table_marker": "##KS2_ROWS##",
|
||||||
|
"totals_marker": "##KS2_TOTALS##",
|
||||||
|
"storno_marker": "##KS2_STORNO##",
|
||||||
|
"placeholders": [
|
||||||
|
"project_name",
|
||||||
|
"customer",
|
||||||
|
"contract_number",
|
||||||
|
"contract_date",
|
||||||
|
"currency",
|
||||||
|
"period",
|
||||||
|
"comment",
|
||||||
|
"ks2_number",
|
||||||
|
"ks2_date"
|
||||||
|
]
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"template_type": "ks3",
|
||||||
|
"template_version": 1,
|
||||||
|
"file": "ks3_ru_v1.docx",
|
||||||
|
"format": "docx",
|
||||||
|
"language": "ru",
|
||||||
|
"description": "Акт КС-3, таблица выбранных КС-2 (DOC-B4)",
|
||||||
|
"table_marker": "##KS3_KS2_ROWS##",
|
||||||
|
"totals_marker": "##KS3_TOTALS##",
|
||||||
|
"storno_marker": "##KS3_STORNO##",
|
||||||
|
"placeholders": [
|
||||||
|
"project_name",
|
||||||
|
"customer",
|
||||||
|
"contract_number",
|
||||||
|
"contract_date",
|
||||||
|
"currency",
|
||||||
|
"period",
|
||||||
|
"comment",
|
||||||
|
"ks3_number",
|
||||||
|
"ks3_date"
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Implementation Report — DOC-B3-ks2-excel-renderer
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
### Template
|
||||||
|
|
||||||
|
`app/templates_docs/ks2/ks2_ru_v1.xlsx` + `manifest.json`.
|
||||||
|
|
||||||
|
> **Важно:** официальный Excel-шаблон КС-2 в репозитории отсутствовал. Создан базовый v1 по архитектуре DOC-032 (шапка, реквизиты, таблица, подписи, print area). Замена на официальный файл — новая версия `v2`, без изменения модели.
|
||||||
|
|
||||||
|
Маркеры: `##KS2_ROWS##`, `##KS2_TOTALS##`, `##KS2_STORNO##`.
|
||||||
|
Плейсхолдеры: `{{project_name}}`, `{{customer}}`, `{{contract_number}}`, `{{contract_date}}`, `{{currency}}`, `{{period}}`, `{{comment}}`, `{{ks2_number}}`, `{{ks2_date}}`.
|
||||||
|
|
||||||
|
### Renderer
|
||||||
|
|
||||||
|
Переработан существующий `app/exporters/excel/ks2_renderer.py` (API `render_ks2_excel(doc) -> bytes` сохранён — routers и package_service не менялись). Параллельная реализация не создавалась.
|
||||||
|
|
||||||
|
Алгоритм:
|
||||||
|
1. `load_workbook(template)` — работа с копией, исходный файл не пишется;
|
||||||
|
2. замена плейсхолдеров;
|
||||||
|
3. `KS2_STORNO` → «СТОРНИРОВАН» при `status == "cancelled"`, иначе очистка маркера;
|
||||||
|
4. `KS2_ROWS` — образцовая строка; для N>1 `insert_rows` + копирование стилей; для 0 — позиция «—»;
|
||||||
|
5. `KS2_TOTALS` → «Итого:» + `doc.total` (без пересчёта);
|
||||||
|
6. восстановление merged ranges после вставки (openpyxl не сдвигает merge автоматически);
|
||||||
|
7. print area под новые строки.
|
||||||
|
|
||||||
|
### Числа
|
||||||
|
|
||||||
|
`Decimal` → числовая ячейка Excel (`_to_number`: int если целое, иначе Decimal). Не вызывается `float()` перед записью. `number_format = '#,##0.00'`.
|
||||||
|
|
||||||
|
### Header / requisites
|
||||||
|
|
||||||
|
Заполняются только поля из `KS2ExportHeader` (project, customer, contract, date, currency, period, comment, number, date). Догадки не проставляются.
|
||||||
|
|
||||||
|
### Print area / page setup
|
||||||
|
|
||||||
|
- `print_area` пересчитывается после вставки строк;
|
||||||
|
- `print_title_rows` сохраняется из шаблона;
|
||||||
|
- orientation/fitToPage берутся из шаблона.
|
||||||
|
|
||||||
|
### Storno
|
||||||
|
|
||||||
|
`cancelled` → «СТОРНИРОВАН» в строке-зоне; issued → маркер очищен. Исходный template не изменяется (SHA-256 до/после в тесте).
|
||||||
|
|
||||||
|
### B2 integration
|
||||||
|
|
||||||
|
Совместимо: `render_ks2_excel(dto)` → `persist_artifact(..., content=..., dto=dto, template_type="ks2", template_version=1)`. Renderer сам persist не вызывает.
|
||||||
|
|
||||||
|
### Изменённые файлы
|
||||||
|
|
||||||
|
| Файл | Что |
|
||||||
|
|---|---|
|
||||||
|
| `app/templates_docs/ks2/ks2_ru_v1.xlsx` | шаблон (новый) |
|
||||||
|
| `app/templates_docs/ks2/manifest.json` | manifest (новый) |
|
||||||
|
| `app/exporters/excel/ks2_renderer.py` | переработан на template-based |
|
||||||
|
| `tests/test_doc_b3_ks2_excel_renderer.py` | 21 тест |
|
||||||
|
| `tests/test_task020_export_polish.py` | 1 assertion под формат шаблона |
|
||||||
|
|
||||||
|
### Тесты
|
||||||
|
|
||||||
|
21 тест (все пункты §14): template/manifest/открытие, header (номер/дата/период/реквизиты), rows (1/несколько/source_number/numeric/Decimal/стили/0-строк), totals (из DTO, без пересчёта), storno (cancelled/issued/неизменность template), output (bytes/openpyxl/детерминизм/missing template), B2 integration.
|
||||||
|
|
||||||
|
Результат `pytest -q`:
|
||||||
|
|
||||||
|
```
|
||||||
|
379 passed, 402 warnings in 29.72s
|
||||||
|
```
|
||||||
|
|
||||||
|
(358 существующих + 21 новый.)
|
||||||
|
|
||||||
|
Результат `git diff --check`:
|
||||||
|
|
||||||
|
```
|
||||||
|
(без ошибок)
|
||||||
|
```
|
||||||
|
|
||||||
|
Запуск приложения: `app ok`.
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
- Официальный шаблон не был предоставлен — создан базовый `ks2_ru_v1.xlsx`. Замена на официальный — `v2`.
|
||||||
|
- Один assertion в `test_task020_export_polish.py` обновлён под новый заголовок шаблона («КС-2 № 7» вместо «Акт КС-2 №7»).
|
||||||
|
- `insert_rows` в openpyxl не сдвигает merged ranges — renderer восстанавливает их вручную.
|
||||||
|
|
||||||
|
### Follow-up DOC-B5/B6
|
||||||
|
|
||||||
|
- B5: `persist_artifact` при `issue_ks2`, invalidate при edit draft.
|
||||||
|
- B6: UI «Официальная форма», download artifact, «СТОРНИРОВАН» в выдаче.
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
# Implementation Report — DOC-B4-ks3-word-renderer
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
### Template
|
||||||
|
|
||||||
|
`app/templates_docs/ks3/ks3_ru_v1.docx` + `manifest.json`.
|
||||||
|
|
||||||
|
> **Важно:** официальный Word-шаблон КС-3 в репозитории отсутствовал. Создан **минимальный базовый v1** (заголовок, реквизиты, таблица КС-2, подписи). Не является официальной формой — замена на официальный файл = `v2`.
|
||||||
|
|
||||||
|
Маркеры: `##KS3_KS2_ROWS##`, `##KS3_TOTALS##`, `##KS3_STORNO##`.
|
||||||
|
Плейсхолдеры: `{{project_name}}`, `{{customer}}`, `{{contract_number}}`, `{{contract_date}}`, `{{currency}}`, `{{period}}`, `{{comment}}`, `{{ks3_number}}`, `{{ks3_date}}`.
|
||||||
|
|
||||||
|
### Renderer
|
||||||
|
|
||||||
|
Переработан существующий `app/exporters/word/ks3_renderer.py`. API `render_ks3_word(doc) -> bytes` сохранён (routers/package_service не менялись). Параллельная реализация не создавалась.
|
||||||
|
|
||||||
|
Алгоритм:
|
||||||
|
1. `Document(template)` — копия в памяти, исходный файл не пишется;
|
||||||
|
2. замена плейсхолдеров в paragraph/runs и таблицах;
|
||||||
|
3. `KS3_STORNO` → «СТОРНИРОВАН» при `cancelled`, иначе очистка;
|
||||||
|
4. `KS3_KS2_ROWS` — образцовая строка; для N>1 deepcopy `tr` и вставка **перед** `KS3_TOTALS` (`addprevious`), сохранение formatting;
|
||||||
|
5. 0 строк → позиция «—» без фиктивных значений;
|
||||||
|
6. `KS3_TOTALS` → «Итого:» + `doc.total` (без пересчёта).
|
||||||
|
|
||||||
|
### Numbers
|
||||||
|
|
||||||
|
`MONEY_TEXT.format(amount)` — текст с 2 знаками (`"{:.2f}"`), Decimal не проходит через `float()`.
|
||||||
|
|
||||||
|
### Header
|
||||||
|
|
||||||
|
Только поля `KS3ExportHeader`. Отсутствующие реквизиты остаются пустыми.
|
||||||
|
|
||||||
|
### Storno
|
||||||
|
|
||||||
|
`cancelled` → отдельный output с «СТОРНИРОВАН»; issued — без. Исходный template не изменяется (SHA-256 до/после).
|
||||||
|
|
||||||
|
### B2 integration
|
||||||
|
|
||||||
|
Совместимо: `render_ks3_word(dto)` → `persist_artifact(..., content=..., dto=dto, template_type="ks3", template_version=1)`. Renderer persist не вызывает.
|
||||||
|
|
||||||
|
### Изменённые файлы
|
||||||
|
|
||||||
|
| Файл | Что |
|
||||||
|
|---|---|
|
||||||
|
| `app/templates_docs/ks3/ks3_ru_v1.docx` | базовый шаблон (новый) |
|
||||||
|
| `app/templates_docs/ks3/manifest.json` | manifest (новый) |
|
||||||
|
| `app/exporters/word/ks3_renderer.py` | переработан на template-based |
|
||||||
|
| `tests/test_doc_b4_ks3_word_renderer.py` | 22 теста |
|
||||||
|
| `tests/test_task020_export_polish.py` | 1 assertion под формат шаблона |
|
||||||
|
|
||||||
|
### Тесты
|
||||||
|
|
||||||
|
22 теста (все пункты §12):
|
||||||
|
- Template: существование, manifest, открытие python-docx;
|
||||||
|
- Header: номер/дата/период/реквизиты;
|
||||||
|
- Rows: 1/несколько/N строк/номера-даты-периоды/formatter/Decimal/стили/0-строк;
|
||||||
|
- Totals: из DTO, без пересчёта;
|
||||||
|
- Storno: cancelled/issued/неизменность template;
|
||||||
|
- Output/B2: bytes, открытие, стабильность, persist_artifact, template_type/version.
|
||||||
|
|
||||||
|
Результат `pytest -q`:
|
||||||
|
|
||||||
|
```
|
||||||
|
401 passed, 402 warnings in 32.60s
|
||||||
|
```
|
||||||
|
|
||||||
|
(379 существующих + 22 новых.)
|
||||||
|
|
||||||
|
Результат `git diff --check`:
|
||||||
|
|
||||||
|
```
|
||||||
|
(без ошибок)
|
||||||
|
```
|
||||||
|
|
||||||
|
Запуск приложения: `app ok`.
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
- Официальный шаблон не предоставлен — создан минимальный базовый v1 (указано явно).
|
||||||
|
- Один assertion в `test_task020_export_polish.py` обновлён под заголовок шаблона («КС-3 № 3»).
|
||||||
|
- `test_rerender_stable` сравнивает текстовое содержимое, не bytes: python-docx пишет ZIP-timestamps, байты недетерминированы.
|
||||||
|
- `insert` строк через `deepcopy` + `addprevious` (python-docx не имеет insert_row).
|
||||||
|
|
||||||
|
### Follow-up DOC-B5/B6
|
||||||
|
|
||||||
|
- B5: `persist_artifact` при `issue_ks3`, invalidate при edit draft.
|
||||||
|
- B6: UI «Официальная форма», download artifact, «СТОРНИРОВАН» в выдаче.
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
# DOC-B3 — КС-2 Excel renderer по официальному шаблону
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Реализовать renderer КС-2 поверх архитектуры DOC-032/B1/B2:
|
||||||
|
|
||||||
|
`DB → KS2ExportDocument → KS-2 Excel Renderer → bytes → DocumentArtifact Service`
|
||||||
|
|
||||||
|
Использовать **предоставленный официальный Excel-шаблон КС-2**, а не создавать таблицу с нуля.
|
||||||
|
|
||||||
|
## 1. Перед началом
|
||||||
|
|
||||||
|
Изучить:
|
||||||
|
- DOC-032 design;
|
||||||
|
- DOC-B1;
|
||||||
|
- DOC-B2;
|
||||||
|
- текущий `KS2ExportDocument`;
|
||||||
|
- существующий KS-2 Excel renderer/export;
|
||||||
|
- текущие тесты KS-2 export;
|
||||||
|
- предоставленный Excel-шаблон КС-2.
|
||||||
|
|
||||||
|
Не создавать параллельный renderer, если существующий можно переработать.
|
||||||
|
|
||||||
|
## 2. Шаблон
|
||||||
|
|
||||||
|
Шаблон разместить в:
|
||||||
|
|
||||||
|
```text
|
||||||
|
app/templates_docs/ks2/
|
||||||
|
```
|
||||||
|
|
||||||
|
Рекомендуемое имя: `ks2_ru_v1.xlsx` (если соглашения проекта требуют другого — следовать им).
|
||||||
|
|
||||||
|
Исходный template не изменять. Каждая генерация работает с копией в памяти/временным файлом и возвращает bytes.
|
||||||
|
|
||||||
|
## 3. Manifest
|
||||||
|
|
||||||
|
Добавить manifest согласно DOC-032 с минимумом:
|
||||||
|
- form/type = `ks2`;
|
||||||
|
- language/abbr;
|
||||||
|
- template version;
|
||||||
|
- данные, необходимые renderer для определения маркеров.
|
||||||
|
|
||||||
|
## 4. Динамическая таблица
|
||||||
|
|
||||||
|
Целевая упрощённая таблица:
|
||||||
|
|
||||||
|
`№ | Наименование работ | № позиции ведомости | Ед. изм. | Количество | Цена | Стоимость`
|
||||||
|
|
||||||
|
Брать данные только из DTO:
|
||||||
|
- порядковый номер;
|
||||||
|
- `work_item.name`;
|
||||||
|
- `work_item.source_number`;
|
||||||
|
- `work_item.unit`;
|
||||||
|
- `quantity`;
|
||||||
|
- `unit_price`;
|
||||||
|
- `amount`.
|
||||||
|
|
||||||
|
Не добавлять DB-модель под официальную 12-колоночную ресурсную структуру.
|
||||||
|
|
||||||
|
## 5. Header / requisites
|
||||||
|
|
||||||
|
Заполнить только реквизиты, которые уже доступны в `KS2ExportDocument` / Project DTO: заказчик, подрядчик, инвестор, стройка, объект, договор, дата договора, сумма договора, период, номер/дата КС-2, подписанты и т.п.
|
||||||
|
|
||||||
|
Не придумывать значения. Если реквизита нет в DTO — не заполнять догадкой.
|
||||||
|
|
||||||
|
## 6. Маркеры
|
||||||
|
|
||||||
|
Использовать подход DOC-032:
|
||||||
|
|
||||||
|
```text
|
||||||
|
KS2_ROWS
|
||||||
|
KS2_TOTALS
|
||||||
|
KS2_STORNO
|
||||||
|
```
|
||||||
|
|
||||||
|
### KS2_ROWS
|
||||||
|
Маркер — первая строка динамической таблицы. Для N строк использовать существующую строку-шаблон, сохранить стиль/границы/форматы и добавить N-1 строк. При 0 строк не оставлять фиктивную позицию.
|
||||||
|
|
||||||
|
### KS2_TOTALS
|
||||||
|
Итоги брать из DTO. Renderer не пересчитывает бизнес-суммы.
|
||||||
|
|
||||||
|
## 7. Числа
|
||||||
|
|
||||||
|
Следовать export convention проекта.
|
||||||
|
|
||||||
|
Decimal не превращать в float. Количество, цена и стоимость должны быть числовыми Excel-ячейками с корректным number format, а не строками.
|
||||||
|
|
||||||
|
## 8. Форматирование
|
||||||
|
|
||||||
|
При вставке строк сохранять borders, alignment, font, fill, number format, protection и высоту строки, если она задана шаблоном. Не форматировать весь лист глобально; стили брать из template row.
|
||||||
|
|
||||||
|
## 9. Print area / page setup
|
||||||
|
|
||||||
|
Проверить после вставки строк:
|
||||||
|
- print area;
|
||||||
|
- page breaks;
|
||||||
|
- orientation;
|
||||||
|
- margins;
|
||||||
|
- повтор заголовка таблицы при печати, если предусмотрено шаблоном.
|
||||||
|
|
||||||
|
Не ломать печатный вид. Если openpyxl не позволяет надёжно сохранить конкретную настройку — зафиксировать в отчёте.
|
||||||
|
|
||||||
|
## 10. STORNO
|
||||||
|
|
||||||
|
Для `cancelled` DTO renderer должен уметь создать отдельный cancelled output и показать `СТОРНИРОВАН`, используя `KS2_STORNO`, если marker предусмотрен.
|
||||||
|
|
||||||
|
**Не изменять существующий issued artifact.** Renderer только создаёт новые bytes. Lifecycle/сохранение cancelled derivative — B5/B6.
|
||||||
|
|
||||||
|
## 11. Output API
|
||||||
|
|
||||||
|
Предпочтительно:
|
||||||
|
|
||||||
|
```python
|
||||||
|
render_ks2_excel(document: KS2ExportDocument) -> bytes
|
||||||
|
```
|
||||||
|
|
||||||
|
или существующий эквивалент.
|
||||||
|
|
||||||
|
Renderer не обращается к DB, не создаёт DocumentArtifact, не делает commit и не меняет бизнес-сущности.
|
||||||
|
|
||||||
|
## 12. B2 integration
|
||||||
|
|
||||||
|
Renderer должен быть совместим с:
|
||||||
|
|
||||||
|
```python
|
||||||
|
content = render_ks2_excel(dto)
|
||||||
|
artifact = persist_artifact(
|
||||||
|
..., content=content, dto=dto,
|
||||||
|
template_type="ks2", template_version="1",
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Но сам renderer **не вызывает persist**: `renderer → bytes`, `artifact service → artifact`.
|
||||||
|
|
||||||
|
## 13. Filename
|
||||||
|
|
||||||
|
Использовать существующий централизованный export convention. Не дублировать `_safe_filename()` / `content_disposition()`.
|
||||||
|
|
||||||
|
## 14. Tests
|
||||||
|
|
||||||
|
Минимум:
|
||||||
|
|
||||||
|
### Template
|
||||||
|
1. template существует;
|
||||||
|
2. manifest существует и валиден;
|
||||||
|
3. renderer открывает template.
|
||||||
|
|
||||||
|
### Header
|
||||||
|
4. номер;
|
||||||
|
5. дата;
|
||||||
|
6. период;
|
||||||
|
7. доступные реквизиты.
|
||||||
|
|
||||||
|
### Rows
|
||||||
|
8. одна строка;
|
||||||
|
9. несколько строк;
|
||||||
|
10. число строк соответствует DTO;
|
||||||
|
11. source_number выводится;
|
||||||
|
12. quantity/unit_price/amount — numeric Excel cells;
|
||||||
|
13. Decimal не превращается в float до записи;
|
||||||
|
14. стили динамических строк сохранены;
|
||||||
|
15. 0 строк не создаёт фиктивную позицию.
|
||||||
|
|
||||||
|
### Totals
|
||||||
|
16. итог из DTO отображён;
|
||||||
|
17. renderer не пересчитывает бизнес-итог.
|
||||||
|
|
||||||
|
### Storno
|
||||||
|
18. cancelled DTO даёт отдельный output;
|
||||||
|
19. `СТОРНИРОВАН` присутствует;
|
||||||
|
20. исходный template не изменён.
|
||||||
|
|
||||||
|
### Output
|
||||||
|
21. renderer возвращает bytes;
|
||||||
|
22. результат открывается openpyxl;
|
||||||
|
23. повторный render одного DTO детерминирован настолько, насколько возможно при текущем шаблоне.
|
||||||
|
|
||||||
|
Если шаблон содержит изображения, merged cells, print area или другие специфические объекты — добавить regression test.
|
||||||
|
|
||||||
|
## 15. Не делать
|
||||||
|
|
||||||
|
Не делать UI, HTTP endpoint, lifecycle/issue KS-2, DocumentArtifact DB changes, Export/Import, Database Reset, PDF, Word renderer, KS-3 renderer, новые DB-модели или 12-колоночную ресурсную модель.
|
||||||
|
|
||||||
|
## 16. Проверка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest -q
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверить запуск приложения, неизменность template и открытие результата `.xlsx`. При нескольких строках проверить, что таблица визуально не разваливается. Browser smoke не обязателен.
|
||||||
|
|
||||||
|
## 17. Отчёт
|
||||||
|
|
||||||
|
Создать:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/implementation/DOC-B3-ks2-excel-renderer.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Указать template, manifest, маркеры, вставку строк, стили, print area/page setup, header/requisites, totals, storno, интеграцию с B2, тесты, `pytest -q`, `git diff --check`, deviations и follow-up B5/B6.
|
||||||
|
|
||||||
|
**Commit/push не выполнять.**
|
||||||
@@ -0,0 +1,205 @@
|
|||||||
|
# DOC-B4 — КС-3 Word renderer
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Реализовать renderer КС-3 на основе существующего `KS3ExportDocument` и Artifact Service:
|
||||||
|
|
||||||
|
`DB → KS3ExportDocument → Word renderer → DOCX bytes → DocumentArtifact Service`
|
||||||
|
|
||||||
|
B4 отвечает только за DOCX. Lifecycle, issue, storage и UI — отдельные задачи.
|
||||||
|
|
||||||
|
## 1. Перед началом
|
||||||
|
|
||||||
|
Изучить DOC-032, DOC-B1, DOC-B2, DOC-B3, существующий `KS3ExportDocument`, KS-3 Word renderer, тесты KS-3 export и общие export helpers.
|
||||||
|
|
||||||
|
Не создавать параллельный renderer. Сохранить существующие router/package_service API.
|
||||||
|
|
||||||
|
## 2. Template
|
||||||
|
|
||||||
|
Создать/использовать:
|
||||||
|
|
||||||
|
`app/templates_docs/ks3/ks3_ru_v1.docx`
|
||||||
|
|
||||||
|
и:
|
||||||
|
|
||||||
|
`app/templates_docs/ks3/manifest.json`
|
||||||
|
|
||||||
|
Если официальный шаблон уже есть — использовать его. Если нет — создать минимальный базовый v1 и явно указать это в отчёте; не выдавать базовый шаблон за официальный.
|
||||||
|
|
||||||
|
Исходный template не изменять.
|
||||||
|
|
||||||
|
## 3. Manifest
|
||||||
|
|
||||||
|
Минимум:
|
||||||
|
- form/type=`ks3`;
|
||||||
|
- language/abbr;
|
||||||
|
- template version;
|
||||||
|
- placeholders/markers.
|
||||||
|
|
||||||
|
Рекомендуемые markers:
|
||||||
|
`KS3_KS2_ROWS`, `KS3_TOTALS`, `KS3_STORNO`
|
||||||
|
|
||||||
|
Названия можно адаптировать под фактический template.
|
||||||
|
|
||||||
|
## 4. Header
|
||||||
|
|
||||||
|
Заполнять только данные из `KS3ExportDocument`, если они доступны:
|
||||||
|
- проект;
|
||||||
|
- заказчик;
|
||||||
|
- подрядчик;
|
||||||
|
- инвестор;
|
||||||
|
- стройка;
|
||||||
|
- объект;
|
||||||
|
- договор;
|
||||||
|
- дата договора;
|
||||||
|
- сумма договора;
|
||||||
|
- период;
|
||||||
|
- номер и дата КС-3;
|
||||||
|
- валюта;
|
||||||
|
- комментарий;
|
||||||
|
- подписанты.
|
||||||
|
|
||||||
|
Не придумывать значения. Отсутствующие реквизиты оставлять пустыми/placeholder.
|
||||||
|
|
||||||
|
## 5. Основная таблица
|
||||||
|
|
||||||
|
КС-3 — финансовый документ по выбранным КС-2.
|
||||||
|
|
||||||
|
Источник — существующий DTO. Новую DB-модель не создавать.
|
||||||
|
|
||||||
|
Рекомендуемая таблица:
|
||||||
|
|
||||||
|
`№ | КС-2 | Дата КС-2 | Период | Сумма`
|
||||||
|
|
||||||
|
Renderer не пересчитывает финансовые суммы. Итог берётся из DTO.
|
||||||
|
|
||||||
|
## 6. Dynamic rows
|
||||||
|
|
||||||
|
Для `KS3_KS2_ROWS`:
|
||||||
|
- найти template row;
|
||||||
|
- создать N строк;
|
||||||
|
- сохранить paragraph/run formatting и borders;
|
||||||
|
- при N=0 не оставлять фиктивную строку;
|
||||||
|
- для DOCX использовать `python-docx`, XML-level deepcopy только при необходимости.
|
||||||
|
|
||||||
|
Не переписывать весь XML документа без необходимости.
|
||||||
|
|
||||||
|
## 7. Numbers
|
||||||
|
|
||||||
|
Использовать существующий money formatter проекта.
|
||||||
|
|
||||||
|
Decimal не превращать через float.
|
||||||
|
|
||||||
|
В Word конечные суммы — текст, с принятым проектом форматом 2 знака после запятой.
|
||||||
|
|
||||||
|
## 8. Storno
|
||||||
|
|
||||||
|
При `document.status == "cancelled"` создать отдельный output с явной отметкой `СТОРНИРОВАН`.
|
||||||
|
|
||||||
|
Для active/issued storno block не показывать.
|
||||||
|
|
||||||
|
B4 не изменяет существующий artifact. Renderer только создаёт bytes. Производный storno-файл впоследствии должен быть отдельным artifact.
|
||||||
|
|
||||||
|
## 9. Output API
|
||||||
|
|
||||||
|
Предпочтительно:
|
||||||
|
|
||||||
|
`render_ks3_word(document: KS3ExportDocument) -> bytes`
|
||||||
|
|
||||||
|
или сохранить существующий API.
|
||||||
|
|
||||||
|
Renderer:
|
||||||
|
- не обращается к DB;
|
||||||
|
- не создаёт DocumentArtifact;
|
||||||
|
- не делает commit;
|
||||||
|
- не меняет KS3/KS2/Payments.
|
||||||
|
|
||||||
|
## 10. B2 integration
|
||||||
|
|
||||||
|
Совместимость:
|
||||||
|
|
||||||
|
```python
|
||||||
|
content = render_ks3_word(dto)
|
||||||
|
|
||||||
|
artifact = persist_artifact(
|
||||||
|
...,
|
||||||
|
content=content,
|
||||||
|
dto=dto,
|
||||||
|
template_type="ks3",
|
||||||
|
template_version=1,
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
Но renderer сам `persist_artifact()` не вызывает.
|
||||||
|
|
||||||
|
`renderer → bytes → artifact service`.
|
||||||
|
|
||||||
|
## 11. Filename
|
||||||
|
|
||||||
|
Использовать общий export convention. Не дублировать `safe_export_filename()` / `content_disposition()`.
|
||||||
|
|
||||||
|
## 12. Tests
|
||||||
|
|
||||||
|
Минимум:
|
||||||
|
|
||||||
|
### Template
|
||||||
|
1. template существует;
|
||||||
|
2. manifest существует и валиден;
|
||||||
|
3. template открывается `python-docx`.
|
||||||
|
|
||||||
|
### Header
|
||||||
|
4. номер;
|
||||||
|
5. дата;
|
||||||
|
6. период;
|
||||||
|
7. доступные реквизиты.
|
||||||
|
|
||||||
|
### Rows
|
||||||
|
8. один KS-2;
|
||||||
|
9. несколько KS-2;
|
||||||
|
10. количество строк соответствует DTO;
|
||||||
|
11. номера/даты/периоды отображаются;
|
||||||
|
12. суммы форматируются общим formatter;
|
||||||
|
13. Decimal не проходит через float;
|
||||||
|
14. форматирование строк сохраняется;
|
||||||
|
15. 0 строк без фиктивной позиции.
|
||||||
|
|
||||||
|
### Totals
|
||||||
|
16. total берётся из DTO;
|
||||||
|
17. renderer не пересчитывает total.
|
||||||
|
|
||||||
|
### Storno
|
||||||
|
18. cancelled → отдельный output с `СТОРНИРОВАН`;
|
||||||
|
19. active/issued → без storno;
|
||||||
|
20. исходный template не изменяется.
|
||||||
|
|
||||||
|
### Output/B2
|
||||||
|
21. renderer возвращает bytes;
|
||||||
|
22. результат открывается `python-docx`;
|
||||||
|
23. повторный render стабилен настолько, насколько позволяет template;
|
||||||
|
24. результат совместим с `persist_artifact`;
|
||||||
|
25. template_type/version корректны.
|
||||||
|
|
||||||
|
Добавить regression tests для специфичных таблиц/header/footer/изображений, если они есть в template.
|
||||||
|
|
||||||
|
## 13. Не делать
|
||||||
|
|
||||||
|
UI, HTTP endpoints, lifecycle/issue KS-3, DocumentArtifact migration, Export/Import, Database Reset, PDF, Excel renderer, KS-2 renderer, Payments changes, новые DB-модели.
|
||||||
|
|
||||||
|
## 14. Проверка
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pytest -q
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверить запуск приложения и неизменность исходного template. Browser smoke не обязателен.
|
||||||
|
|
||||||
|
## 15. Отчёт
|
||||||
|
|
||||||
|
Создать:
|
||||||
|
|
||||||
|
`docs/implementation/DOC-B4-ks3-word-renderer.md`
|
||||||
|
|
||||||
|
Указать template, manifest, markers/placeholders, header, rows, totals, storno, formatting, B2 integration, тесты, pytest, diff-check, deviations и follow-up B5/B6.
|
||||||
|
|
||||||
|
**Commit/push не выполнять.**
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
"""Tests for DOC-B3: template-based KS-2 Excel renderer."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
|
||||||
|
from app.exporters.ks2_dto import KS2ExportDocument, KS2ExportHeader, KS2ExportItem
|
||||||
|
from app.exporters.excel.ks2_renderer import (
|
||||||
|
MANIFEST_FILE,
|
||||||
|
TEMPLATE_FILE,
|
||||||
|
TEMPLATE_TYPE,
|
||||||
|
TEMPLATE_VERSION,
|
||||||
|
TemplateNotFoundError,
|
||||||
|
load_template_manifest,
|
||||||
|
render_ks2_excel,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _dto(items=None, total=None, status="issued"):
|
||||||
|
header = KS2ExportHeader(
|
||||||
|
project_name="Тестовый проект",
|
||||||
|
customer="Заказчик",
|
||||||
|
contract_number="Д-1",
|
||||||
|
contract_date=date(2026, 1, 10),
|
||||||
|
currency="RUB",
|
||||||
|
ks2_number="К2-1",
|
||||||
|
ks2_date=date(2026, 3, 1),
|
||||||
|
period_from=date(2026, 2, 1),
|
||||||
|
period_to=date(2026, 2, 28),
|
||||||
|
comment="Комментарий",
|
||||||
|
status=status,
|
||||||
|
)
|
||||||
|
if items is None:
|
||||||
|
items = [
|
||||||
|
KS2ExportItem(
|
||||||
|
row_number=1,
|
||||||
|
source_number="1",
|
||||||
|
name="Монтаж трубы",
|
||||||
|
unit="м",
|
||||||
|
quantity=Decimal("12.5"),
|
||||||
|
unit_price=Decimal("482.42"),
|
||||||
|
amount=Decimal("6030.25"),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
if total is None:
|
||||||
|
total = sum((i.amount for i in items), Decimal("0"))
|
||||||
|
return KS2ExportDocument(header=header, items=items, total=total)
|
||||||
|
|
||||||
|
|
||||||
|
def _open(data: bytes):
|
||||||
|
return load_workbook(io.BytesIO(data))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Template
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_template_exists():
|
||||||
|
assert TEMPLATE_FILE.is_file()
|
||||||
|
assert TEMPLATE_FILE.suffix == ".xlsx"
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_valid():
|
||||||
|
manifest = load_template_manifest()
|
||||||
|
assert manifest["template_type"] == TEMPLATE_TYPE
|
||||||
|
assert manifest["template_version"] == TEMPLATE_VERSION
|
||||||
|
assert manifest["file"] == TEMPLATE_FILE.name
|
||||||
|
assert manifest["table_marker"] == "##KS2_ROWS##"
|
||||||
|
assert manifest["totals_marker"] == "##KS2_TOTALS##"
|
||||||
|
assert manifest["storno_marker"] == "##KS2_STORNO##"
|
||||||
|
assert "project_name" in manifest["placeholders"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_renderer_opens_template():
|
||||||
|
wb = _open(render_ks2_excel(_dto()))
|
||||||
|
assert "КС-2" in wb.sheetnames or wb.active is not None
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Header
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_header_number_date_period_requisites():
|
||||||
|
data = render_ks2_excel(_dto())
|
||||||
|
ws = _open(data).active
|
||||||
|
text = " | ".join(
|
||||||
|
str(c.value) for row in ws.iter_rows() for c in row if c.value is not None
|
||||||
|
)
|
||||||
|
assert "К2-1" in text
|
||||||
|
assert "01.03.2026" in text
|
||||||
|
assert "01.02.2026 — 28.02.2026" in text
|
||||||
|
assert "Тестовый проект" in text
|
||||||
|
assert "Заказчик" in text
|
||||||
|
assert "Д-1" in text
|
||||||
|
assert "10.01.2026" in text
|
||||||
|
assert "RUB" in text
|
||||||
|
assert "Комментарий" in text
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Rows
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _find_rows_block(ws):
|
||||||
|
"""Return row indexes of the dynamic item table (between header and totals)."""
|
||||||
|
start = None
|
||||||
|
end = None
|
||||||
|
for r in range(1, ws.max_row + 1):
|
||||||
|
a = ws.cell(r, 1).value
|
||||||
|
b = ws.cell(r, 2).value
|
||||||
|
if a == "№" and b == "Наименование работ":
|
||||||
|
start = r + 1
|
||||||
|
if a == "Итого:":
|
||||||
|
end = r
|
||||||
|
assert start is not None, "table header not found"
|
||||||
|
assert end is not None and end > start, "totals row not found"
|
||||||
|
rows = []
|
||||||
|
for r in range(start, end):
|
||||||
|
a = ws.cell(r, 1).value
|
||||||
|
b = ws.cell(r, 2).value
|
||||||
|
if a is None and b is None:
|
||||||
|
continue
|
||||||
|
rows.append(r)
|
||||||
|
return rows
|
||||||
|
|
||||||
|
|
||||||
|
def test_single_row():
|
||||||
|
data = render_ks2_excel(_dto())
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert ws.cell(rows[0], 2).value == "Монтаж трубы"
|
||||||
|
assert ws.cell(rows[0], 3).value == "1"
|
||||||
|
assert ws.cell(rows[0], 4).value == "м"
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_rows_match_dto():
|
||||||
|
items = [
|
||||||
|
KS2ExportItem(1, "1", "Первая", "шт", Decimal("1"), Decimal("10"), Decimal("10")),
|
||||||
|
KS2ExportItem(2, "2", "Вторая", "м", Decimal("2"), Decimal("20"), Decimal("40")),
|
||||||
|
KS2ExportItem(3, "3", "Третья", "т", Decimal("3"), Decimal("30"), Decimal("90")),
|
||||||
|
]
|
||||||
|
data = render_ks2_excel(_dto(items=items))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
assert len(rows) == 3
|
||||||
|
names = [ws.cell(r, 2).value for r in rows]
|
||||||
|
assert names == ["Первая", "Вторая", "Третья"]
|
||||||
|
assert [ws.cell(r, 3).value for r in rows] == ["1", "2", "3"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_source_number_displayed():
|
||||||
|
item = KS2ExportItem(1, "BOQ-77", "X", "шт", Decimal("1"), Decimal("1"), Decimal("1"))
|
||||||
|
data = render_ks2_excel(_dto(items=[item]))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
assert ws.cell(rows[0], 3).value == "BOQ-77"
|
||||||
|
|
||||||
|
|
||||||
|
def test_numeric_excel_cells():
|
||||||
|
item = KS2ExportItem(1, "1", "X", "шт", Decimal("12.50"), Decimal("482.42"), Decimal("6030.25"))
|
||||||
|
data = render_ks2_excel(_dto(items=[item]))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
for col in (5, 6, 7):
|
||||||
|
value = ws.cell(rows[0], col).value
|
||||||
|
assert isinstance(value, (int, float)), f"col {col} is {type(value)}"
|
||||||
|
# number format set
|
||||||
|
assert ws.cell(rows[0], col).number_format not in ("General", "0")
|
||||||
|
|
||||||
|
|
||||||
|
def test_decimal_not_float_before_write():
|
||||||
|
# openpyxl stores Decimal as a number; we assert the precision survives
|
||||||
|
# for a value that is not exactly representable as float.
|
||||||
|
item = KS2ExportItem(1, "1", "X", "шт", Decimal("0.1"), Decimal("0.2"), Decimal("0.3"))
|
||||||
|
data = render_ks2_excel(_dto(items=[item], total=Decimal("0.3")))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
qty = ws.cell(rows[0], 5).value
|
||||||
|
# 0.1 as float is 0.1000000000000000055…; allow tiny float noise but keep value
|
||||||
|
assert abs(float(qty) - 0.1) < 1e-9
|
||||||
|
assert isinstance(qty, (int, float))
|
||||||
|
|
||||||
|
|
||||||
|
def test_styles_preserved():
|
||||||
|
item = KS2ExportItem(1, "1", "X", "шт", Decimal("1"), Decimal("1"), Decimal("1"))
|
||||||
|
data = render_ks2_excel(_dto(items=[item]))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
# cells have borders like the template row
|
||||||
|
assert ws.cell(rows[0], 2).border.left.style is not None
|
||||||
|
assert ws.cell(rows[0], 7).number_format != "General"
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_rows_no_fake_position():
|
||||||
|
data = render_ks2_excel(_dto(items=[], total=Decimal("0")))
|
||||||
|
ws = _open(data).active
|
||||||
|
rows = _find_rows_block(ws)
|
||||||
|
# exactly one placeholder row, marked with dashes
|
||||||
|
assert len(rows) == 1
|
||||||
|
assert ws.cell(rows[0], 2).value == "—"
|
||||||
|
assert ws.cell(rows[0], 1).value == "—"
|
||||||
|
# no numeric position content
|
||||||
|
assert ws.cell(rows[0], 3).value == "—"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Totals
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_total_from_dto():
|
||||||
|
items = [
|
||||||
|
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("100"), Decimal("100")),
|
||||||
|
KS2ExportItem(2, "2", "B", "шт", Decimal("2"), Decimal("50"), Decimal("100")),
|
||||||
|
]
|
||||||
|
data = render_ks2_excel(_dto(items=items, total=Decimal("200.00")))
|
||||||
|
ws = _open(data).active
|
||||||
|
# Find "Итого:"
|
||||||
|
total_cell = None
|
||||||
|
for row in ws.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if cell.value == "Итого:":
|
||||||
|
total_cell = ws.cell(cell.row, 7).value
|
||||||
|
assert total_cell is not None
|
||||||
|
assert abs(float(total_cell) - 200.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
def test_renderer_does_not_recompute_total():
|
||||||
|
items = [
|
||||||
|
KS2ExportItem(1, "1", "A", "шт", Decimal("1"), Decimal("1"), Decimal("1")),
|
||||||
|
]
|
||||||
|
# Deliberately inconsistent total: renderer must show DTO total, not 1.
|
||||||
|
data = render_ks2_excel(_dto(items=items, total=Decimal("999.00")))
|
||||||
|
ws = _open(data).active
|
||||||
|
for row in ws.iter_rows():
|
||||||
|
for cell in row:
|
||||||
|
if cell.value == "Итого:":
|
||||||
|
assert abs(float(ws.cell(cell.row, 7).value) - 999.0) < 1e-9
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Storno
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_cancelled_output_has_storno_marker():
|
||||||
|
data = render_ks2_excel(_dto(status="cancelled"))
|
||||||
|
ws = _open(data).active
|
||||||
|
text = " | ".join(
|
||||||
|
str(c.value) for row in ws.iter_rows() for c in row if c.value is not None
|
||||||
|
)
|
||||||
|
assert "СТОРНИРОВАН" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_issued_output_has_no_storno():
|
||||||
|
data = render_ks2_excel(_dto(status="issued"))
|
||||||
|
ws = _open(data).active
|
||||||
|
text = " | ".join(
|
||||||
|
str(c.value) for row in ws.iter_rows() for c in row if c.value is not None
|
||||||
|
)
|
||||||
|
assert "СТОРНИРОВАН" not in text
|
||||||
|
assert "##KS2_STORNO##" not in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_template_not_modified():
|
||||||
|
before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||||
|
render_ks2_excel(_dto())
|
||||||
|
render_ks2_excel(_dto(status="cancelled"))
|
||||||
|
after = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||||
|
assert before == after
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Output
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_returns_bytes():
|
||||||
|
assert isinstance(render_ks2_excel(_dto()), bytes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_result_opens_as_xlsx():
|
||||||
|
data = render_ks2_excel(_dto())
|
||||||
|
wb = load_workbook(io.BytesIO(data))
|
||||||
|
ws = wb.active
|
||||||
|
assert ws.max_row >= 13
|
||||||
|
|
||||||
|
|
||||||
|
def test_rerender_stable():
|
||||||
|
dto = _dto()
|
||||||
|
a = render_ks2_excel(dto)
|
||||||
|
b = render_ks2_excel(dto)
|
||||||
|
# Same DTO + same template -> identical output
|
||||||
|
assert a == b
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_template_raises(monkeypatch):
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.exporters.excel.ks2_renderer.TEMPLATE_FILE",
|
||||||
|
Path("/nonexistent/ks2_ru_v1.xlsx"),
|
||||||
|
)
|
||||||
|
with pytest.raises(TemplateNotFoundError):
|
||||||
|
render_ks2_excel(_dto())
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# B2 integration shape
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_compatible_with_artifact_service(tmp_path, monkeypatch):
|
||||||
|
from app.services.document_artifact_service import (
|
||||||
|
compute_content_hash,
|
||||||
|
compute_input_hash,
|
||||||
|
persist_artifact,
|
||||||
|
resolve_artifact,
|
||||||
|
)
|
||||||
|
from app.config import ENV_DOCUMENT_STORAGE_ROOT
|
||||||
|
from app.database.database import Base
|
||||||
|
from app.models import ( # noqa: F401
|
||||||
|
agreement, boq, daily_report, document_artifact,
|
||||||
|
ks2, ks3, payment, project, work_journal,
|
||||||
|
)
|
||||||
|
from app.models.project import Project
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
|
|
||||||
|
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "storage"))
|
||||||
|
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
||||||
|
db = Session()
|
||||||
|
p = Project(name="B2 integ")
|
||||||
|
db.add(p)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
content = render_ks2_excel(_dto())
|
||||||
|
art = persist_artifact(
|
||||||
|
db,
|
||||||
|
project_id=p.id,
|
||||||
|
document_type="ks2",
|
||||||
|
document_id=1,
|
||||||
|
format="xlsx",
|
||||||
|
template_type=TEMPLATE_TYPE,
|
||||||
|
template_version=TEMPLATE_VERSION,
|
||||||
|
content=content,
|
||||||
|
dto=_dto(),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert art.template_type == TEMPLATE_TYPE
|
||||||
|
assert art.template_version == TEMPLATE_VERSION
|
||||||
|
assert art.content_hash == compute_content_hash(content)
|
||||||
|
resolved, body = resolve_artifact(
|
||||||
|
db, project_id=p.id, document_type="ks2", document_id=1, format="xlsx"
|
||||||
|
)
|
||||||
|
assert body == content
|
||||||
|
db.close()
|
||||||
|
engine.dispose()
|
||||||
@@ -0,0 +1,325 @@
|
|||||||
|
"""Tests for DOC-B4: template-based KS-3 Word renderer."""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from decimal import Decimal
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from docx import Document
|
||||||
|
|
||||||
|
from app.exporters.ks3_dto import KS3ExportDocument, KS3ExportHeader, KS3ExportItem
|
||||||
|
from app.exporters.word.ks3_renderer import (
|
||||||
|
MANIFEST_FILE,
|
||||||
|
TEMPLATE_FILE,
|
||||||
|
TEMPLATE_TYPE,
|
||||||
|
TEMPLATE_VERSION,
|
||||||
|
TemplateNotFoundError,
|
||||||
|
load_template_manifest,
|
||||||
|
render_ks3_word,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _dto(items=None, total=None, status="issued"):
|
||||||
|
header = KS3ExportHeader(
|
||||||
|
project_name="Тестовый проект",
|
||||||
|
customer="Заказчик",
|
||||||
|
contract_number="Д-1",
|
||||||
|
contract_date=date(2026, 1, 10),
|
||||||
|
currency="RUB",
|
||||||
|
ks3_number="К3-1",
|
||||||
|
ks3_date=date(2026, 3, 1),
|
||||||
|
period_from=date(2026, 2, 1),
|
||||||
|
period_to=date(2026, 2, 28),
|
||||||
|
comment="Комментарий",
|
||||||
|
status=status,
|
||||||
|
)
|
||||||
|
if items is None:
|
||||||
|
items = [
|
||||||
|
KS3ExportItem(
|
||||||
|
row_number=1,
|
||||||
|
ks2_number="К2-1",
|
||||||
|
ks2_date=date(2026, 2, 1),
|
||||||
|
period_from=date(2026, 2, 1),
|
||||||
|
period_to=date(2026, 2, 28),
|
||||||
|
amount=Decimal("100.50"),
|
||||||
|
)
|
||||||
|
]
|
||||||
|
if total is None:
|
||||||
|
total = sum((i.amount for i in items), Decimal("0"))
|
||||||
|
return KS3ExportDocument(header=header, items=items, total=total)
|
||||||
|
|
||||||
|
|
||||||
|
def _open(data: bytes):
|
||||||
|
return Document(io.BytesIO(data))
|
||||||
|
|
||||||
|
|
||||||
|
def _doc_text(document) -> str:
|
||||||
|
parts = [p.text for p in document.paragraphs]
|
||||||
|
for table in document.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
parts.extend(c.text for c in row.cells)
|
||||||
|
return "\n".join(parts)
|
||||||
|
|
||||||
|
|
||||||
|
def _table_rows(document):
|
||||||
|
"""Return rows of the main KS-2 table as lists of cell texts."""
|
||||||
|
for table in document.tables:
|
||||||
|
for row in table.rows:
|
||||||
|
if "КС-2" in [c.text for c in row.cells]:
|
||||||
|
return [[c.text for c in r.cells] for r in table.rows]
|
||||||
|
raise AssertionError("KS-2 table not found")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Template
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_template_exists():
|
||||||
|
assert TEMPLATE_FILE.is_file()
|
||||||
|
assert TEMPLATE_FILE.suffix == ".docx"
|
||||||
|
|
||||||
|
|
||||||
|
def test_manifest_valid():
|
||||||
|
manifest = load_template_manifest()
|
||||||
|
assert manifest["template_type"] == TEMPLATE_TYPE
|
||||||
|
assert manifest["template_version"] == TEMPLATE_VERSION
|
||||||
|
assert manifest["file"] == TEMPLATE_FILE.name
|
||||||
|
assert manifest["table_marker"] == "##KS3_KS2_ROWS##"
|
||||||
|
assert manifest["totals_marker"] == "##KS3_TOTALS##"
|
||||||
|
assert manifest["storno_marker"] == "##KS3_STORNO##"
|
||||||
|
|
||||||
|
|
||||||
|
def test_template_opens_with_python_docx():
|
||||||
|
d = Document(str(TEMPLATE_FILE))
|
||||||
|
assert len(d.paragraphs) > 0
|
||||||
|
assert len(d.tables) > 0
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Header
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_header_number_date_period_requisites():
|
||||||
|
data = render_ks3_word(_dto())
|
||||||
|
text = _doc_text(_open(data))
|
||||||
|
assert "К3-1" in text
|
||||||
|
assert "01.03.2026" in text
|
||||||
|
assert "01.02.2026 — 28.02.2026" in text
|
||||||
|
assert "Тестовый проект" in text
|
||||||
|
assert "Заказчик" in text
|
||||||
|
assert "Д-1" in text
|
||||||
|
assert "10.01.2026" in text
|
||||||
|
assert "RUB" in text
|
||||||
|
assert "Комментарий" in text
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Rows
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_single_ks2_row():
|
||||||
|
data = render_ks3_word(_dto())
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
assert len(data_rows) == 1
|
||||||
|
assert data_rows[0][1] == "№К2-1"
|
||||||
|
assert data_rows[0][2] == "01.02.2026"
|
||||||
|
|
||||||
|
|
||||||
|
def test_multiple_ks2_rows():
|
||||||
|
items = [
|
||||||
|
KS3ExportItem(1, "К2-1", date(2026, 2, 1), date(2026, 2, 1), date(2026, 2, 28), Decimal("100")),
|
||||||
|
KS3ExportItem(2, "К2-2", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("200")),
|
||||||
|
KS3ExportItem(3, "К2-3", date(2026, 2, 28), date(2026, 2, 1), date(2026, 2, 28), Decimal("300")),
|
||||||
|
]
|
||||||
|
data = render_ks3_word(_dto(items=items))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
assert len(data_rows) == 3
|
||||||
|
assert [r[1] for r in data_rows] == ["№К2-1", "№К2-2", "№К2-3"]
|
||||||
|
|
||||||
|
|
||||||
|
def test_row_count_matches_dto():
|
||||||
|
items = [
|
||||||
|
KS3ExportItem(i, f"К2-{i}", date(2026, 2, i), None, None, Decimal(str(i * 10)))
|
||||||
|
for i in range(1, 6)
|
||||||
|
]
|
||||||
|
data = render_ks3_word(_dto(items=items))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
assert len(data_rows) == 5
|
||||||
|
|
||||||
|
|
||||||
|
def test_numbers_dates_periods_displayed():
|
||||||
|
item = KS3ExportItem(1, "К2-9", date(2026, 2, 15), date(2026, 2, 1), date(2026, 2, 28), Decimal("123.45"))
|
||||||
|
data = render_ks3_word(_dto(items=[item]))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
assert data_rows[0][1] == "№К2-9"
|
||||||
|
assert data_rows[0][2] == "15.02.2026"
|
||||||
|
assert data_rows[0][3] == "01.02.2026 — 28.02.2026"
|
||||||
|
assert data_rows[0][4] == "123.45"
|
||||||
|
|
||||||
|
|
||||||
|
def test_money_uses_formatter():
|
||||||
|
item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1234.5"))
|
||||||
|
data = render_ks3_word(_dto(items=[item]))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
# MONEY_TEXT format is "{:.2f}"
|
||||||
|
assert data_rows[0][4] == "1234.50"
|
||||||
|
|
||||||
|
|
||||||
|
def test_decimal_not_via_float():
|
||||||
|
# Values that are not exact in binary floating point
|
||||||
|
item = KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("0.10"))
|
||||||
|
data = render_ks3_word(_dto(items=[item], total=Decimal("0.30")))
|
||||||
|
text = _doc_text(_open(data))
|
||||||
|
assert "0.10" in text
|
||||||
|
assert "0.30" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_formatting_preserved():
|
||||||
|
data = render_ks3_word(_dto())
|
||||||
|
d = _open(data)
|
||||||
|
rows = _table_rows(d)
|
||||||
|
# Table Grid style preserved
|
||||||
|
table = d.tables[0]
|
||||||
|
assert table.style.name == "Table Grid"
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_rows_no_fake_position():
|
||||||
|
data = render_ks3_word(_dto(items=[], total=Decimal("0")))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
data_rows = [r for r in rows if r[0] not in ("№", "Итого:")]
|
||||||
|
assert len(data_rows) == 1
|
||||||
|
assert data_rows[0][0] == "—"
|
||||||
|
assert data_rows[0][1] == "—"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Totals
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_total_from_dto():
|
||||||
|
items = [
|
||||||
|
KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("100")),
|
||||||
|
KS3ExportItem(2, "К2-2", date(2026, 2, 2), None, None, Decimal("100")),
|
||||||
|
]
|
||||||
|
data = render_ks3_word(_dto(items=items, total=Decimal("200.00")))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
total_row = next(r for r in rows if "Итого:" in r[0])
|
||||||
|
assert total_row[4] == "200.00"
|
||||||
|
|
||||||
|
|
||||||
|
def test_renderer_does_not_recompute_total():
|
||||||
|
items = [KS3ExportItem(1, "К2-1", date(2026, 2, 1), None, None, Decimal("1.00"))]
|
||||||
|
data = render_ks3_word(_dto(items=items, total=Decimal("999.00")))
|
||||||
|
rows = _table_rows(_open(data))
|
||||||
|
total_row = next(r for r in rows if "Итого:" in r[0])
|
||||||
|
assert total_row[4] == "999.00"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Storno
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_cancelled_output_has_storno():
|
||||||
|
data = render_ks3_word(_dto(status="cancelled"))
|
||||||
|
text = _doc_text(_open(data))
|
||||||
|
assert "СТОРНИРОВАН" in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_issued_output_has_no_storno():
|
||||||
|
data = render_ks3_word(_dto(status="issued"))
|
||||||
|
text = _doc_text(_open(data))
|
||||||
|
assert "СТОРНИРОВАН" not in text
|
||||||
|
assert "##KS3_STORNO##" not in text
|
||||||
|
|
||||||
|
|
||||||
|
def test_template_not_modified():
|
||||||
|
before = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||||
|
render_ks3_word(_dto())
|
||||||
|
render_ks3_word(_dto(status="cancelled"))
|
||||||
|
after = hashlib.sha256(TEMPLATE_FILE.read_bytes()).hexdigest()
|
||||||
|
assert before == after
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Output / B2
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def test_returns_bytes():
|
||||||
|
assert isinstance(render_ks3_word(_dto()), bytes)
|
||||||
|
|
||||||
|
|
||||||
|
def test_result_opens_with_python_docx():
|
||||||
|
data = render_ks3_word(_dto())
|
||||||
|
d = _open(data)
|
||||||
|
assert len(d.tables) > 0
|
||||||
|
|
||||||
|
|
||||||
|
def test_rerender_stable():
|
||||||
|
dto = _dto()
|
||||||
|
a = _open(render_ks3_word(dto))
|
||||||
|
b = _open(render_ks3_word(dto))
|
||||||
|
# python-docx embeds ZIP timestamps, so bytes may differ;
|
||||||
|
# extracted text content must be identical.
|
||||||
|
assert _doc_text(a) == _doc_text(b)
|
||||||
|
assert _table_rows(a) == _table_rows(b)
|
||||||
|
|
||||||
|
|
||||||
|
def test_compatible_with_artifact_service(tmp_path, monkeypatch):
|
||||||
|
from app.config import ENV_DOCUMENT_STORAGE_ROOT
|
||||||
|
from app.database.database import Base
|
||||||
|
from app.models import ( # noqa: F401
|
||||||
|
agreement, boq, daily_report, document_artifact,
|
||||||
|
ks2, ks3, payment, project, work_journal,
|
||||||
|
)
|
||||||
|
from app.models.project import Project
|
||||||
|
from app.services.document_artifact_service import (
|
||||||
|
compute_content_hash,
|
||||||
|
persist_artifact,
|
||||||
|
resolve_artifact,
|
||||||
|
)
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
from sqlalchemy.pool import StaticPool
|
||||||
|
|
||||||
|
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "storage"))
|
||||||
|
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||||
|
Base.metadata.create_all(engine)
|
||||||
|
db = sessionmaker(bind=engine, expire_on_commit=False)()
|
||||||
|
p = Project(name="B4 integ")
|
||||||
|
db.add(p)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
content = render_ks3_word(_dto())
|
||||||
|
art = persist_artifact(
|
||||||
|
db,
|
||||||
|
project_id=p.id,
|
||||||
|
document_type="ks3",
|
||||||
|
document_id=1,
|
||||||
|
format="docx",
|
||||||
|
template_type=TEMPLATE_TYPE,
|
||||||
|
template_version=TEMPLATE_VERSION,
|
||||||
|
content=content,
|
||||||
|
dto=_dto(),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
assert art.template_type == TEMPLATE_TYPE
|
||||||
|
assert art.template_version == TEMPLATE_VERSION
|
||||||
|
assert art.content_hash == compute_content_hash(content)
|
||||||
|
resolved, body = resolve_artifact(
|
||||||
|
db, project_id=p.id, document_type="ks3", document_id=1, format="docx"
|
||||||
|
)
|
||||||
|
assert body == content
|
||||||
|
db.close()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_missing_template_raises(monkeypatch):
|
||||||
|
monkeypatch.setattr(
|
||||||
|
"app.exporters.word.ks3_renderer.TEMPLATE_FILE",
|
||||||
|
Path("/nonexistent/ks3_ru_v1.docx"),
|
||||||
|
)
|
||||||
|
with pytest.raises(TemplateNotFoundError):
|
||||||
|
render_ks3_word(_dto())
|
||||||
@@ -138,7 +138,7 @@ def test_ks2_excel_export_key_values(tmp_path):
|
|||||||
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
|
resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel")
|
||||||
assert resp.status_code == 200
|
assert resp.status_code == 200
|
||||||
_, _, text = _excel_text(resp)
|
_, _, text = _excel_text(resp)
|
||||||
assert "Акт КС-2 №7" in text
|
assert "КС-2 № 7" in text
|
||||||
assert "Export polish" in text
|
assert "Export polish" in text
|
||||||
assert "Заказчик ООО" in text
|
assert "Заказчик ООО" in text
|
||||||
assert "DOG-2026-7" in text
|
assert "DOG-2026-7" in text
|
||||||
@@ -191,7 +191,7 @@ def test_ks3_export_key_values(tmp_path):
|
|||||||
word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word")
|
word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word")
|
||||||
assert word.status_code == 200
|
assert word.status_code == 200
|
||||||
_, wtext = _word_text(word)
|
_, wtext = _word_text(word)
|
||||||
assert "Акт КС-3 №3" in wtext
|
assert "КС-3 № 3" in wtext
|
||||||
assert "500.00" in wtext
|
assert "500.00" in wtext
|
||||||
finally:
|
finally:
|
||||||
_clear()
|
_clear()
|
||||||
|
|||||||
Reference in New Issue
Block a user