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 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)
|
||||
|
||||
@@ -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 json
|
||||
from copy import deepcopy
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
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
|
||||
|
||||
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:
|
||||
d = Document()
|
||||
"""Render KS-3 from a template. Returns docx bytes. No DB / no artifact writes."""
|
||||
if not TEMPLATE_FILE.is_file():
|
||||
raise TemplateNotFoundError(
|
||||
f"KS-3 template not found: {TEMPLATE_FILE}. "
|
||||
"Add the official template to app/templates_docs/ks3/."
|
||||
)
|
||||
|
||||
# Work on an in-memory copy; never modify the template on disk.
|
||||
d = Document(str(TEMPLATE_FILE))
|
||||
|
||||
h = doc.header
|
||||
mapping = {
|
||||
"project_name": h.project_name or "",
|
||||
"customer": h.customer or "",
|
||||
"contract_number": h.contract_number or "",
|
||||
"contract_date": format_date(h.contract_date),
|
||||
"currency": h.currency or "",
|
||||
"period": format_period(h.period_from, h.period_to),
|
||||
"comment": h.comment or "",
|
||||
"ks3_number": h.ks3_number or "",
|
||||
"ks3_date": format_date(h.ks3_date),
|
||||
}
|
||||
_replace_in_paragraphs(d, mapping)
|
||||
|
||||
section = d.sections[0]
|
||||
section.orientation = WD_ORIENT.LANDSCAPE
|
||||
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()
|
||||
|
||||
# Table
|
||||
table = d.add_table(rows=1, cols=5)
|
||||
table.style = "Table Grid"
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
|
||||
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
|
||||
for idx, col_name in enumerate(columns):
|
||||
cell = table.rows[0].cells[idx]
|
||||
cell.text = col_name
|
||||
for paragraph in cell.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
run.font.size = Pt(9)
|
||||
|
||||
for item in doc.items:
|
||||
row = table.add_row()
|
||||
row.cells[0].text = str(item.row_number)
|
||||
row.cells[1].text = f"№{item.ks2_number}"
|
||||
row.cells[2].text = format_date(item.ks2_date)
|
||||
row.cells[3].text = format_period(item.period_from, item.period_to)
|
||||
row.cells[4].text = MONEY_TEXT.format(item.amount)
|
||||
|
||||
# Total row
|
||||
total_row = table.add_row()
|
||||
total_row.cells[0].merge(total_row.cells[3])
|
||||
total_row.cells[0].text = "Итого:"
|
||||
for paragraph in total_row.cells[0].paragraphs:
|
||||
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
||||
# Storno banner
|
||||
for paragraph in d.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
total_row.cells[4].text = MONEY_TEXT.format(doc.total)
|
||||
for paragraph in total_row.cells[4].paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
if _STORNO_MARKER in run.text:
|
||||
run.text = "СТОРНИРОВАН" if h.status == "cancelled" else ""
|
||||
|
||||
# Locate template row and totals row in the same table
|
||||
items = list(doc.items)
|
||||
table, rows_idx = _find_marker_table(d, _ROWS_MARKER)
|
||||
totals_table, totals_idx = _find_marker_table(d, _TOTALS_MARKER)
|
||||
if totals_table._tbl is not table._tbl:
|
||||
raise TemplateNotFoundError("KS3_ROWS and KS3_TOTALS must be in the same table")
|
||||
|
||||
template_tr = table.rows[rows_idx]._tr
|
||||
totals_tr = table.rows[totals_idx]._tr
|
||||
|
||||
if not items:
|
||||
# Single placeholder row without fake values
|
||||
row = table.rows[rows_idx]
|
||||
_set_cell(row.cells[0], "—")
|
||||
_set_cell(row.cells[1], "—")
|
||||
_set_cell(row.cells[2], "—")
|
||||
_set_cell(row.cells[3], "—")
|
||||
_set_cell(row.cells[4], "—")
|
||||
else:
|
||||
# First item fills the template row
|
||||
row = table.rows[rows_idx]
|
||||
item = items[0]
|
||||
_set_cell(row.cells[0], str(item.row_number))
|
||||
_set_cell(row.cells[1], f"№{item.ks2_number}")
|
||||
_set_cell(row.cells[2], format_date(item.ks2_date))
|
||||
_set_cell(row.cells[3], format_period(item.period_from, item.period_to))
|
||||
_set_cell(row.cells[4], MONEY_TEXT.format(item.amount))
|
||||
# Insert additional items BEFORE the totals row
|
||||
for item in items[1:]:
|
||||
new_tr = _insert_row_before(table, totals_tr, template_tr)
|
||||
# Re-read the new row from the table object
|
||||
new_row = next(r for r in table.rows if r._tr is new_tr)
|
||||
_set_cell(new_row.cells[0], str(item.row_number))
|
||||
_set_cell(new_row.cells[1], f"№{item.ks2_number}")
|
||||
_set_cell(new_row.cells[2], format_date(item.ks2_date))
|
||||
_set_cell(new_row.cells[3], format_period(item.period_from, item.period_to))
|
||||
_set_cell(new_row.cells[4], MONEY_TEXT.format(item.amount))
|
||||
|
||||
# Totals (locate by stable XML identity — index shifts after inserts)
|
||||
total_row = next(r for r in table.rows if r._tr is totals_tr)
|
||||
_set_cell(total_row.cells[0], "Итого:")
|
||||
_set_cell(total_row.cells[4], MONEY_TEXT.format(doc.total))
|
||||
|
||||
buf = io.BytesIO()
|
||||
d.save(buf)
|
||||
|
||||
Reference in New Issue
Block a user