Files
work-volume-tracker/app/exporters/excel/ks2_renderer.py
T
2026-09-29 17:50:58 +03:00

189 lines
6.9 KiB
Python

"""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 load_workbook
from app.exporters.common import format_date, format_period
from app.exporters.ks2_dto import KS2ExportDocument
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:
"""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
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.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
# 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
# Snapshot merged ranges so we can restore them after row insertion.
merges = [str(r) for r in ws.merged_cells.ranges]
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)))
# 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
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))
# 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)
# 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)
buf.seek(0)
return buf.read()