"""Template-based Excel renderer for KS-2 (official form v2). DB -> KS2ExportDocument (DTO) -> Official Template v2 -> xlsx 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 import io import json from copy import copy 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 from app.exporters.ks2_dto import KS2ExportDocument TEMPLATE_TYPE = "ks2" TEMPLATE_VERSION = 2 TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2" 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): pass 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_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 float(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 _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 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: if not TEMPLATE_FILE.is_file(): raise TemplateNotFoundError(f"KS-2 template not found: {TEMPLATE_FILE}.") 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 = { "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), "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 (header zone; must not destroy merges) --- storno_row = _find_marker_row(ws, _STORNO_MARKER) _apply_storno(ws, storno_row, h.status == "cancelled") # --- 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) 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)] 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 # --- 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 # --- 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)) row_heights = _snapshot_row_heights(ws) # --- 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 = None 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) buf.seek(0) return buf.read()