feat: add template-based KS-2 Excel and KS-3 Word renderers

This commit is contained in:
Арсентьев Александр
2026-09-29 17:50:58 +03:00
parent cddde114fe
commit e66bce0d25
12 changed files with 1643 additions and 176 deletions
+164 -96
View File
@@ -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 json
from copy import copy
from decimal import Decimal
from pathlib import Path
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, Side
from openpyxl.utils import get_column_letter
from openpyxl import load_workbook
from app.exporters.common import (
MONEY_FMT,
MONEY_TEXT,
QTY_FMT,
QTY_TEXT,
format_period,
project_requisite_lines,
)
from app.exporters.common import format_date, format_period
from app.exporters.ks2_dto import KS2ExportDocument
THIN = Side(style="thin")
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
HEADER_FONT = Font(bold=True, size=11)
TITLE_FONT = Font(bold=True, size=14)
TEMPLATE_TYPE = "ks2"
TEMPLATE_VERSION = 1
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
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:
wb = Workbook()
ws = wb.active
ws.title = "КС-2"
"""Render KS-2 from a template. Returns xlsx bytes. No DB / no artifact writes."""
if not TEMPLATE_FILE.is_file():
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
row = 1
col_count = 7
# Title
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
c = ws.cell(row=row, column=1, value=f"Акт КС-2 №{h.ks2_number} от {h.ks2_date.strftime('%d.%m.%Y')}")
c.font = TITLE_FONT
c.alignment = Alignment(horizontal="center")
row += 1
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 "",
"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":
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count)
c = ws.cell(row=row, column=1, value="СТОРНИРОВАН")
c.font = Font(bold=True, size=12, color="C00000")
c.alignment = Alignment(horizontal="center")
row += 1
ws.cell(row=storno_row, column=1).value = "СТОРНИРОВАН"
else:
# Clear the marker row so it does not appear as garbage text.
ws.cell(row=storno_row, column=1).value = None
# Unified project requisites
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:
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
# Dynamic table
rows_marker = _find_marker_row(ws, _ROWS_MARKER)
totals_marker = _find_marker_row(ws, _TOTALS_MARKER)
items = list(doc.items)
max_col = 7
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
columns = ["№", "Наименование работ", "№ позиции в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
for col_idx, col_name in enumerate(columns, start=1):
c = ws.cell(row=row, column=col_idx, value=col_name)
c.font = HEADER_FONT
c.border = BORDER
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
header_row = row
row += 1
if not items:
# Keep a single blank row with dashes — no fake position values.
for col, value in ((1, "—"), (2, "—"), (3, "—"), (4, "—")):
ws.cell(row=rows_marker, column=col).value = value
for col in (5, 6, 7):
ws.cell(row=rows_marker, column=col).value = 0
data_rows = [rows_marker]
else:
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
for item in doc.items:
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
c = ws.cell(row=row, column=2, value=item.name)
c.border = BORDER
c.alignment = Alignment(wrap_text=True, vertical="top")
ws.cell(row=row, column=3, value=item.source_number).border = BORDER
ws.cell(row=row, column=4, value=item.unit).border = BORDER
# Restore merged ranges shifted by the insertion.
shift = max(len(items) - 1, 0)
if shift and items:
for rng in merges:
# Openpyxl ranges are 1-based; re-apply with a row offset when
# the range sits at or below the inserted block.
from openpyxl.worksheet.cell_range import CellRange
c = ws.cell(row=row, column=5, value=float(item.quantity))
c.border = BORDER
c.number_format = QTY_FMT
cr = CellRange(rng)
if cr.min_row >= rows_marker + 1:
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))
c.border = BORDER
c.number_format = MONEY_FMT
# Totals row (marker may have moved)
totals_row = _find_marker_row(ws, _TOTALS_MARKER)
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))
c.border = BORDER
c.number_format = MONEY_FMT
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)
# Print area follows the filled content
last_row = max(data_rows + [totals_row]) + 2
ws.print_area = f"A1:G{last_row}"
buf = io.BytesIO()
wb.save(buf)