feat: official KS-2 Excel/Word forms with template markers and single-table flow

Replace the simplified KS-2 exports with the official unified form:

- Excel: official blank as working template, merge-safe row insertion,
  compact layout, header/signer polish, 0.00 money format
- Word: official blank via named template markers (DOC-C4), one dynamic
  works table with repeating header rows, separate closing totals block
  (Итого / Всего по акту), system group rows merged across 8 columns
- Word money formatter (space thousands, comma decimals) and split
  contract date day/month/year boxes
- Issue persists both xlsx and docx artifacts; UI keeps Excel and adds
  Word download
- Daily reports: multi-system item selection in the form

Regression tests for renderers, artifacts and layout; docs/tasks +
docs/implementation for the DOC-C* series.
This commit is contained in:
Арсентьев Александр
2026-10-03 19:48:29 +03:00
parent 79c7d4f335
commit bd64bb6307
49 changed files with 6917 additions and 353 deletions
+497 -89
View File
@@ -1,10 +1,20 @@
"""Template-based Excel renderer for KS-2.
"""Template-based Excel renderer for KS-2 (official form v2).
DB -> KS2ExportDocument (DTO) -> Template Renderer -> xlsx bytes
DB -> KS2ExportDocument (DTO) -> Official Template v2 -> 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.
Column mapping (7 data columns in the template):
A = row_number (№ пп)
B = source_number (№ поз. Ведомости)
C = name (Наименование работ и затрат)
E = unit (Ед. изм.)
G = quantity (Количество)
I = unit_price (Цена за единицу)
K = amount (Стоимость)
Merge policy:
- Header merges (rows above the group marker) are never unmerged.
- Data-area merges are recreated per output row (group = A:M, item = C:D..K:M).
- Merges below the data area are shifted by the inserted row count.
"""
from __future__ import annotations
@@ -15,23 +25,43 @@ from decimal import Decimal
from pathlib import Path
from openpyxl import load_workbook
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
from openpyxl.worksheet.cell_range import CellRange
from app.exporters.common import format_date, format_period
from app.exporters.common import format_date
from app.exporters.ks2_dto import KS2ExportDocument
TEMPLATE_TYPE = "ks2"
TEMPLATE_VERSION = 1
TEMPLATE_VERSION = 2
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_v1.xlsx"
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_v2.xlsx"
MANIFEST_FILE = TEMPLATE_DIR / "manifest.json"
_ROWS_MARKER = "##KS2_ROWS##"
_GROUP_MARKER = "##KS2_GROUP##"
_TOTALS_MARKER = "##KS2_TOTALS##"
_STORNO_MARKER = "##KS2_STORNO##"
_COL_NUM = 1
_COL_SOURCE = 2
_COL_NAME = 3
_COL_UNIT = 5
_COL_QTY = 7
_COL_PRICE = 9
_COL_AMOUNT = 11
MAX_COL = 13
# Excel numeric format for money/qty: invariant "0.00" renders as 0,00 in ru locale.
_NUM_FMT = "0.00"
# Per-item column pairs from the official template (C:D, E:F, G:H, I:J, K:M)
_ITEM_MERGES = ((3, 4), (5, 6), (7, 8), (9, 10), (11, 13))
# Group divider spans the full table width
_GROUP_MERGE = (1, 13)
class TemplateNotFoundError(FileNotFoundError):
"""KS-2 template resource is missing."""
pass
def load_template_manifest() -> dict:
@@ -41,15 +71,15 @@ def load_template_manifest() -> dict:
return json.load(handle)
def _to_number(value: Decimal) -> Decimal | int | float:
"""Keep Decimal precision; openpyxl writes numeric cells for Decimal/int/float."""
def _to_excel_number(value) -> int | float:
"""Convert Decimal/int/float/None to an Excel numeric (int or 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
return float(value)
def _find_marker_row(ws, marker: str) -> int:
@@ -72,115 +102,493 @@ def _replace_placeholders(ws, mapping: dict[str, str]) -> None:
cell.value = text
def _copy_row_style(ws, src_row: int, dest_row: int, max_col: int) -> None:
def _capture_row_style(ws, src_row: int, max_col: int) -> list[dict]:
captured = []
for col in range(1, max_col + 1):
src = ws.cell(row=src_row, column=col)
captured.append({
"font": copy(src.font) if src.has_style else None,
"border": copy(src.border) if src.has_style else None,
"fill": copy(src.fill) if src.has_style else None,
"number_format": src.number_format,
"protection": copy(src.protection) if src.has_style else None,
"alignment": copy(src.alignment) if src.has_style else None,
})
return captured
def _apply_row_style(ws, captured: list[dict], dest_row: int, max_col: int) -> None:
for col in range(1, max_col + 1):
if col - 1 >= len(captured):
break
st = captured[col - 1]
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
if st["font"] is not None:
dest.font = copy(st["font"])
if st["border"] is not None:
dest.border = copy(st["border"])
if st["fill"] is not None:
dest.fill = copy(st["fill"])
dest.number_format = st["number_format"]
if st["protection"] is not None:
dest.protection = copy(st["protection"])
if st["alignment"] is not None:
dest.alignment = copy(st["alignment"])
def _row_is_empty(ws, row: int, max_col: int = MAX_COL) -> bool:
for col in range(1, max_col + 1):
val = ws.cell(row=row, column=col).value
if val is not None and str(val).strip() != "":
return False
return True
def _remap_row_after_delete(row: int, deleted: int) -> int | None:
"""Map row index after deleting `deleted` (None = that row is gone)."""
if row < deleted:
return row
if row == deleted:
return None
return row - 1
def _snapshot_row_heights(ws) -> dict[int, float]:
heights: dict[int, float] = {}
for r in range(1, ws.max_row + 1):
dim = ws.row_dimensions[r]
if dim.height is not None:
heights[r] = float(dim.height)
return heights
def _apply_row_heights(ws, heights: dict[int, float]) -> None:
for r in range(1, ws.max_row + 1):
if r in heights:
ws.row_dimensions[r].height = heights[r]
else:
# drop stale dimension left behind by insert/delete
if r in ws.row_dimensions:
ws.row_dimensions[r].height = None
def _shift_heights_after_insert(heights: dict[int, float], at: int, amount: int) -> dict[int, float]:
"""openpyxl insert_rows does not move row_dimensions — remap manually."""
out: dict[int, float] = {}
for r, h in heights.items():
out[r + amount if r >= at else r] = h
return out
def _delete_rows_with_merges(ws, rows_to_delete: list[int]) -> None:
"""Delete rows bottom-up, remapping merges AND row heights.
Header merges (entirely above the first deleted row) are left untouched —
they must never be unmerged or recreated.
"""
targets = sorted({r for r in rows_to_delete if r >= 1}, reverse=True)
if not targets:
return
first = min(targets)
heights = _snapshot_row_heights(ws)
merges: list[list[int]] = []
for rng in list(ws.merged_cells.ranges):
cr = CellRange(str(rng))
if cr.max_row < first:
continue # header / earlier merges: do not touch
merges.append([cr.min_row, cr.min_col, cr.max_row, cr.max_col])
ws.unmerge_cells(str(rng))
for deleted in targets:
ws.delete_rows(deleted)
new_heights: dict[int, float] = {}
for r, h in heights.items():
nr = _remap_row_after_delete(r, deleted)
if nr is not None:
new_heights[nr] = h
heights = new_heights
kept: list[list[int]] = []
for min_r, min_c, max_r, max_c in merges:
new_min = _remap_row_after_delete(min_r, deleted)
new_max = _remap_row_after_delete(max_r, deleted)
if new_min is None and new_max is None:
continue
if new_min is None:
new_min = new_max
if new_max is None:
new_max = new_min
kept.append([new_min, min_c, new_max, max_c])
merges = kept
_apply_row_heights(ws, heights)
for min_r, min_c, max_r, max_c in merges:
if min_r < 1 or max_r < min_r:
continue
try:
ws.merge_cells(
start_row=min_r, start_column=min_c,
end_row=max_r, end_column=max_c,
)
except Exception:
pass
def _set_num(cell, value) -> None:
"""Write a numeric Excel value with 0.00 format (no currency)."""
cell.value = _to_excel_number(value)
cell.number_format = _NUM_FMT
# Signature block: values sit on the row above the labels row.
# Column E is the position/value column in the signature block.
_SIG_COL_POS = 5
_SIG_COL_NAME = 10 # column J (name / расшифровка)
def _write_into_merge_top_left(ws, row: int, col: int, value: str) -> None:
"""Write to the top-left cell of a merge covering (row, col) if any; else the cell."""
target_row, target_col = row, col
for rng in ws.merged_cells.ranges:
cr = CellRange(str(rng))
if cr.min_row <= row <= cr.max_row and cr.min_col <= col <= cr.max_col:
target_row, target_col = cr.min_row, cr.min_col
break
ws.cell(row=target_row, column=target_col).value = value
def _clear_signature_placeholders(ws) -> None:
"""Remove leftover {{...}} signer markers so they never render as text."""
for row in ws.iter_rows():
for cell in row:
if isinstance(cell.value, str) and "{{" in cell.value and "signer" in cell.value:
cell.value = None
def _place_signatures(ws, h) -> None:
"""Place signer names/positions on the value row (above the signature line).
Template quirk: ks2_ru_v2 has {{customer_signer_position}} on the label row
(next to «(подпись)») and leaves the intended value-row merge empty.
Renderer must write values strictly into the form's value-row cells and
restore the «(должность)» label below the line — without touching header
merges and without editing the template file.
"""
_clear_signature_placeholders(ws)
pairs = (
("Сдал", h.contractor_signer_position or "", h.contractor_signer_name or ""),
("Принял", h.customer_signer_position or "", h.customer_signer_name or ""),
)
for row in range(1, ws.max_row + 1):
c3 = ws.cell(row=row, column=3).value
if c3 is None:
continue
text = str(c3).strip()
for label, position, name in pairs:
if text != label:
continue
# Value row is the «Сдал»/«Принял» row itself: position in E:I, name in J:K.
_write_into_merge_top_left(ws, row, _SIG_COL_POS, position)
_write_into_merge_top_left(ws, row, _SIG_COL_NAME, name)
# Label row below the signature line must show «(должность)» under the position.
label_row = row + 1
if label_row <= ws.max_row:
cell = ws.cell(row=label_row, column=_SIG_COL_POS)
val = "" if cell.value is None else str(cell.value).strip()
if "(должность)" not in val:
cell.value = "(должность)"
def _polish_header_doc_block(ws) -> None:
"""Polish «Номер документа / Дата составления / Отчётный период» block.
Values are already written into the template-designated cells (G22..J22)
by placeholder substitution. Only alignment is adjusted — merged cells
are never created, destroyed or re-created here.
Labels use shrink-to-fit so «Дата составления» does not break mid-word
in the narrow template column.
"""
for row in range(1, min(ws.max_row, 28) + 1):
val = ws.cell(row=row, column=7).value # column G
if val is not None and "Номер документа" in str(val):
label_row = row
value_row = row + 2 # labels occupy 2 rows (G20:G21 / H20:H21); values on next
for col in range(7, 11): # G..J
label = ws.cell(row=label_row, column=col)
if label.value is not None:
text = str(label.value).replace("\n", " ")
label.value = text
words = text.split()
longest = max((len(w) for w in words), default=0)
if longest >= 10:
# Narrow column: Excel would split the word mid-syllable.
# shrink_to_fit keeps one clean line without touching the template.
label.alignment = Alignment(
horizontal="center", vertical="center",
wrap_text=False, shrink_to_fit=True,
)
else:
label.alignment = Alignment(
horizontal="center", vertical="center",
wrap_text=True, shrink_to_fit=False,
)
# «с» / «по» sub-labels sit on the second label row
sub = ws.cell(row=label_row + 1, column=col)
if sub.value is not None:
sub.alignment = Alignment(horizontal="center", vertical="center")
cell = ws.cell(row=value_row, column=col)
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=False)
return
def _apply_table_alignment(ws, row: int, *, numeric_cols: tuple[int, ...]) -> None:
"""Neat cell padding: text = vcenter+wrap+small left indent; numbers = vcenter, no indent."""
for col in range(1, MAX_COL + 1):
cell = ws.cell(row=row, column=col)
if col in numeric_cols:
# numbers: vertical center, no indent (centered so they don't stick to borders)
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=False, indent=0)
else:
cell.alignment = Alignment(horizontal="left", vertical="center", wrap_text=True, indent=1)
def _apply_storno(ws, storno_row: int, cancelled: bool) -> None:
"""Fill ##KS2_STORNO## without breaking existing merges.
For cancelled: full-width merge A:M + bold red centered label.
The merge is only created when the row is not already inside another merge,
so surrounding template merges stay intact.
"""
if cancelled:
already = False
for rng in ws.merged_cells.ranges:
cr = CellRange(str(rng))
if cr.min_row <= storno_row <= cr.max_row and cr.max_col >= MAX_COL:
already = True
storno_merge = str(rng)
break
if not already:
# Row must be free of other merges; if occupied, write into the
# top-left of the existing range instead of destroying it.
occupied = None
for rng in ws.merged_cells.ranges:
cr = CellRange(str(rng))
if cr.min_row <= storno_row <= cr.max_row:
occupied = cr
break
if occupied is not None:
ws.cell(row=occupied.min_row, column=occupied.min_col).value = "СТОРНИРОВАН"
ws.cell(row=occupied.min_row, column=occupied.min_col).font = Font(
name="Arial", size=12, bold=True, color="FF0000"
)
return
ws.merge_cells(
start_row=storno_row, start_column=1,
end_row=storno_row, end_column=MAX_COL,
)
cell = ws.cell(row=storno_row, column=1)
cell.value = "СТОРНИРОВАН"
cell.font = Font(name="Arial", size=12, bold=True, color="FF0000")
cell.alignment = Alignment(horizontal="center", vertical="center")
dim = ws.row_dimensions[storno_row]
if not dim.height or dim.height < 18:
dim.height = 18
else:
# Clear marker only; leave merges untouched.
cell = ws.cell(row=storno_row, column=1)
cell.value = None
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/."
)
raise TemplateNotFoundError(f"KS-2 template not found: {TEMPLATE_FILE}.")
# 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
# --- Header placeholders (never unmerge this area) ---
h = doc.header
mapping = {
"project_name": h.project_name or "",
"customer": h.customer or "",
"customer": h.customer or h.customer_name or "",
"contractor_name": h.contractor_name or "",
"object_name": h.object_name 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),
"period_from": format_date(h.period_from),
"period_to": format_date(h.period_to),
"project_name": h.project_name or "",
}
# Signer fields are placed by _place_signatures into the correct value-row
# cells (the template has {{customer_signer_position}} on the wrong row).
_replace_placeholders(ws, mapping)
_polish_header_doc_block(ws)
# Storno banner
# --- STORNO (header zone; must not destroy merges) ---
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
_apply_storno(ws, storno_row, h.status == "cancelled")
# Dynamic table
# --- Locate template rows ---
group_marker = _find_marker_row(ws, _GROUP_MARKER)
rows_marker = _find_marker_row(ws, _ROWS_MARKER)
totals_marker = _find_marker_row(ws, _TOTALS_MARKER)
items = list(doc.items)
max_col = 7
sequence: list[tuple[str, object]] = []
for item in items:
gh = getattr(item, "group_header", None)
if gh:
sequence.append(("group", gh))
sequence.append(("item", item))
if not sequence:
sequence = [("item", None)]
# Snapshot merged ranges so we can restore them after row insertion.
merges = [str(r) for r in ws.merged_cells.ranges]
total_rows = len(sequence)
# Template data block occupies group_marker..rows_marker (2 rows)
template_data_rows = rows_marker - group_marker + 1
extra = total_rows - template_data_rows
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)))
# --- Capture styles for group/item rows before any insert ---
group_styles = _capture_row_style(ws, group_marker, MAX_COL)
item_styles = _capture_row_style(ws, rows_marker, MAX_COL)
group_height = ws.row_dimensions[group_marker].height
item_height = ws.row_dimensions[rows_marker].height
# 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
# --- Snapshot merges at/after data area; leave header merges alone ---
shifting_merges: list[tuple[int, int, int, int]] = []
for rng in list(ws.merged_cells.ranges):
cr = CellRange(str(rng))
if cr.min_row >= group_marker:
shifting_merges.append((cr.min_row, cr.min_col, cr.max_row, cr.max_col))
ws.unmerge_cells(str(rng))
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))
row_heights = _snapshot_row_heights(ws)
# Totals row (marker may have moved)
# --- Insert extra data rows just below the group template row ---
if extra > 0:
ws.insert_rows(rows_marker + 1, amount=extra)
row_heights = _shift_heights_after_insert(row_heights, rows_marker + 1, extra)
_apply_row_heights(ws, row_heights)
# --- Fill data area ---
data_start = group_marker
for idx, (kind, payload) in enumerate(sequence):
r = data_start + idx
if kind == "group":
_apply_row_style(ws, group_styles, r, MAX_COL)
ws.cell(row=r, column=1).value = str(payload)
for col in range(2, MAX_COL + 1):
ws.cell(row=r, column=col).value = None
ws.merge_cells(
start_row=r, start_column=_GROUP_MERGE[0],
end_row=r, end_column=_GROUP_MERGE[1],
)
# group divider text: neat padding like table text
ws.cell(row=r, column=1).alignment = Alignment(
horizontal="left", vertical="center", wrap_text=True, indent=1,
)
if group_height:
ws.row_dimensions[r].height = group_height
else:
_apply_row_style(ws, item_styles, r, MAX_COL)
if payload is None:
for col in (_COL_NUM, _COL_SOURCE, _COL_NAME, _COL_UNIT):
ws.cell(row=r, column=col).value = "—"
for col in (_COL_QTY, _COL_PRICE, _COL_AMOUNT):
_set_num(ws.cell(row=r, column=col), 0)
else:
item = payload
ws.cell(row=r, column=_COL_NUM).value = item.row_number
ws.cell(row=r, column=_COL_SOURCE).value = item.source_number or ""
ws.cell(row=r, column=_COL_NAME).value = item.name or ""
ws.cell(row=r, column=_COL_UNIT).value = item.unit or ""
_set_num(ws.cell(row=r, column=_COL_QTY), item.quantity)
_set_num(ws.cell(row=r, column=_COL_PRICE), item.unit_price)
_set_num(ws.cell(row=r, column=_COL_AMOUNT), item.amount)
for c1, c2 in _ITEM_MERGES:
ws.merge_cells(start_row=r, start_column=c1, end_row=r, end_column=c2)
# neat padding: text vcenter+wrap+left indent; numbers vcenter, no indent
_apply_table_alignment(ws, r, numeric_cols=(_COL_NUM, _COL_QTY, _COL_PRICE, _COL_AMOUNT))
if item_height:
ws.row_dimensions[r].height = item_height
data_end = data_start + total_rows - 1
shift = max(extra, 0)
# --- Restore merges that lived at/after the original data area ---
orig_lo, orig_hi = group_marker, rows_marker
for (min_r, min_c, max_r, max_c) in shifting_merges:
# Recreated per data row — skip originals inside the template data block
if orig_lo <= min_r and max_r <= orig_hi:
continue
if min_r > orig_hi:
new_min, new_max = min_r + shift, max_r + shift
elif max_r < orig_lo:
new_min, new_max = min_r, max_r
else:
# Spans across the data block — skip (template has none of these)
continue
if new_min <= new_max:
try:
ws.merge_cells(
start_row=new_min, start_column=min_c,
end_row=new_max, end_column=max_c,
)
except Exception:
pass
# --- Totals ---
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)
ws.cell(row=totals_row, column=1).value = None
# Print area follows the filled content
last_row = max(data_rows + [totals_row]) + 2
ws.print_area = f"A1:G{last_row}"
vsyo_row = None
for row in range(totals_row, ws.max_row + 1):
val = ws.cell(row=row, column=1).value
if val and "ВСЕГО" in str(val):
vsyo_row = row
_set_num(ws.cell(row=row, column=_COL_AMOUNT), doc.total)
# Do not stretch the totals row with reserved template height
ws.row_dimensions[row].height = 22.5
break
# --- Compact layout: drop unused data slots and empty reserved rows ---
# 1) leftover template data rows between last item and the ВСЕГО block
delete_rows: list[int] = []
block_end = vsyo_row if vsyo_row is not None else totals_row
for r in range(data_end + 1, block_end):
# Clear leftover markers/placeholders from the template data slot
for col in range(1, MAX_COL + 1):
ws.cell(row=r, column=col).value = None
if _row_is_empty(ws, r):
delete_rows.append(r)
# 2) empty spacer rows between ВСЕГО and the signature block ("Сдал")
sdal_row = None
for r in range(block_end + 1, ws.max_row + 1):
val = ws.cell(row=r, column=3).value # "Сдал" lives in col C
if val is not None and "Сдал" in str(val):
sdal_row = r
break
if sdal_row is not None:
for r in range(block_end + 1, sdal_row):
if _row_is_empty(ws, r):
delete_rows.append(r)
if delete_rows:
_delete_rows_with_merges(ws, delete_rows)
# --- Signatures: values on the value row (above the line), labels below ---
_place_signatures(ws, h)
# --- Print: one page wide, repeat table header on page breaks ---
ws.print_area = f"A1:M{ws.max_row}"
ws.print_title_rows = f"{group_marker - 2}:{group_marker - 1}" # 27:28
buf = io.BytesIO()
wb.save(buf)