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)
+19
View File
@@ -13,6 +13,8 @@ class KS2ExportItem:
quantity: Decimal
unit_price: Decimal
amount: Decimal
group_header: str | None = None
group_code: str | None = None
@dataclass(frozen=True)
@@ -55,10 +57,25 @@ def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
project = ks2_document.project
items = []
total = D("0")
current_group = None
for idx, line in enumerate(ks2_document.items, start=1):
wi = line.work_item
amount = D(str(line.amount or 0))
total += amount
# Determine group header from System → Section hierarchy
group_header = None
group_code = None
if wi is not None:
system_name = wi.system.name if wi.system else None
system_code = wi.system.code if wi.system else None
section_name = wi.section.name if wi.section else None
if system_name and system_name != current_group:
group_header = system_name
group_code = system_code
current_group = system_name
elif section_name and system_name is None and section_name != current_group:
group_header = section_name
current_group = section_name
items.append(KS2ExportItem(
row_number=idx,
source_number=wi.source_number or "",
@@ -67,6 +84,8 @@ def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
quantity=D(str(line.quantity or 0)),
unit_price=D(str(line.unit_price or 0)),
amount=amount,
group_header=group_header,
group_code=group_code,
))
header = KS2ExportHeader(
+467 -78
View File
@@ -1,96 +1,485 @@
"""Word renderer for KS-2 export using python-docx."""
"""Official-form KS-2 Word renderer.
KS2ExportDocument -> official DOCX template -> generated DOCX
Working template: app/templates_docs/ks2/ks2_ru_markers.docx
(copied from docs/templates/official/КС-2.docx via ks2_ru_v2.docx;
the original is never modified).
Static header fields (DOC-C4) are named template markers `{{name}}`:
the template owns the layout, Python only supplies data
(build_ks2_template_fields + fill_template_markers). The dynamic works
table is still filled by the code below.
Template layout (python-docx tables):
t0 requisites (Инвестор/Заказчик/Подрядчик/Стройка/Объект/ОКДП/Договор)
t1 Номер документа / Дата составления / Отчетный период + АКТ
t2 Сметная (договорная) стоимость
t3 one dynamic works table (3-row header + system/item rows);
header rows repeat on page breaks via w:tblHeader
t4 closing totals block only («Итого» + «Всего по акту») after the items
t5 «Сдал» signatures
t6 «Принял» signatures
Data columns (8): № по порядку | № поз. по смете | Наименование |
Номер ед. расценки (always empty) | Ед. изм. | Количество | Цена | Стоимость.
"""
from __future__ import annotations
import io
from copy import deepcopy
from datetime import date
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 docx.oxml.ns import qn
from docx.shared import RGBColor
from app.exporters.common import MONEY_TEXT, QTY_TEXT, format_period, project_requisite_lines
from app.exporters.ks2_dto import KS2ExportDocument
from app.exporters.word.template_markers import fill_template_markers
TEMPLATE_TYPE = "ks2_word"
TEMPLATE_VERSION = 1
TEMPLATE_DIR = Path(__file__).resolve().parents[2] / "templates_docs" / "ks2"
TEMPLATE_FILE = TEMPLATE_DIR / "ks2_ru_markers.docx"
class TemplateNotFoundError(FileNotFoundError):
pass
# Column indices inside the 8-column data tables.
_COL_NUM = 0
_COL_SOURCE = 1
_COL_NAME = 2
_COL_RATE = 3 # always empty
_COL_UNIT = 4
_COL_QTY = 5
_COL_PRICE = 6
_COL_AMOUNT = 7
_DATA_COLS = 8
# ---------------------------------------------------------------------------
# Formatters (Word-only; Excel keeps its own numeric formats)
# ---------------------------------------------------------------------------
def format_money(value) -> str:
"""Money: thousands = space, decimal = comma, exactly 2 digits, no currency.
Examples: 31 293,36 / 18 600 000,00 / 1 005,00
"""
if value is None or value == "":
return ""
d = Decimal(str(value)).quantize(Decimal("0.01"))
sign = "-" if d < 0 else ""
d = abs(d)
int_part, frac = f"{d:.2f}".split(".")
groups = []
while len(int_part) > 3:
groups.append(int_part[-3:])
int_part = int_part[:-3]
groups.append(int_part)
int_part = " ".join(reversed(groups))
return f"{sign}{int_part},{frac}"
def format_qty(value) -> str:
"""Quantity: ordinary number with comma decimal and exactly 2 digits (17,00)."""
if value is None or value == "":
return ""
d = Decimal(str(value)).quantize(Decimal("0.01"))
return f"{d:.2f}".replace(".", ",")
def _tr(tbl, row_idx):
return tbl.rows[row_idx]._tr
def _tcs(tbl, row_idx):
"""Raw w:tc elements of a row (merged cells appear once)."""
return _tr(tbl, row_idx).findall(qn("w:tc"))
def _set_tc_text(tc, text: str, *, bold: bool = False, size_pt: float | None = None,
color: RGBColor | None = None, align=None, no_wrap: bool = False) -> None:
"""Replace all runs of a w:tc with a single run carrying `text`.
Newlines become real OOXML line breaks (w:br).
"""
for p in tc.findall(qn("w:p")):
tc.remove(p)
p = tc.makeelement(qn("w:p"), {})
tc.append(p)
pPr = p.makeelement(qn("w:pPr"), {})
p.append(pPr)
if align is not None:
jc = pPr.makeelement(qn("w:jc"), {qn("w:val"): align})
pPr.append(jc)
if no_wrap:
tcPr = tc.find(qn("w:tcPr"))
if tcPr is None:
tcPr = tc.makeelement(qn("w:tcPr"), {})
tc.insert(0, tcPr)
if tcPr.find(qn("w:noWrap")) is None:
tcPr.append(tcPr.makeelement(qn("w:noWrap"), {}))
run = p.makeelement(qn("w:r"), {})
p.append(run)
rPr = run.makeelement(qn("w:rPr"), {})
run.append(rPr)
if bold:
rPr.append(rPr.makeelement(qn("w:b"), {}))
if size_pt is not None:
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): str(int(size_pt * 2))}))
if color is not None:
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): str(color)}))
parts = text.split("\n")
for i, part in enumerate(parts):
if i > 0:
run.append(run.makeelement(qn("w:br"), {}))
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
t.text = part
run.append(t)
def _find_row_by_text(tbl, needle: str, tc_index: int = 0) -> int | None:
for ri in range(len(tbl.rows)):
tcs = _tcs(tbl, ri)
if tc_index < len(tcs):
texts = [t.text or "" for t in tcs[tc_index].iter(qn("w:t"))]
if needle in "".join(texts):
return ri
return None
def _split_date(value: date | None) -> tuple[str, str, str]:
"""Return (day, month, year) as zero-padded strings; empty when no date."""
if value is None:
return "", "", ""
return f"{value.day:02d}", f"{value.month:02d}", str(value.year)
def _fmt_date(value: date | None) -> str:
if value is None:
return ""
return f"{value.day:02d}.{value.month:02d}.{value.year}"
def build_ks2_template_fields(doc: KS2ExportDocument) -> dict[str, str]:
"""Named marker values for the static KS-2 header (DOC-C4).
Values only — layout stays in the template (ks2_ru_markers.docx).
"""
h = doc.header
day, month, year = _split_date(h.contract_date)
raw_amount = (h.contract_amount or "").strip()
if raw_amount:
try:
amount = format_money(Decimal(raw_amount))
except Exception:
amount = raw_amount
else:
amount = ""
return {
"ks2_number": h.ks2_number or "",
"ks2_date": _fmt_date(h.ks2_date),
"contract_number": h.contract_number or "",
"contract_date_day": day,
"contract_date_month": month,
"contract_date_year": year,
"report_from": _fmt_date(h.period_from),
"report_to": _fmt_date(h.period_to),
"investor": h.investor_name or "",
"customer": h.customer or h.customer_name or "",
"contractor": h.contractor_name or "",
"construction": h.construction_name or "",
"object": h.object_name or "",
"contract_amount": amount,
"contractor_signer_name": h.contractor_signer_name or "",
"contractor_signer_position": h.contractor_signer_position or "",
"customer_signer_name": h.customer_signer_name or "",
"customer_signer_position": h.customer_signer_position or "",
}
def _data_row_index(tbl) -> int | None:
"""First empty data row (after the 3-row header block, before «Итого»)."""
total_ri = _find_row_by_text(tbl, "Итого", 0)
if total_ri is None:
return None
for ri in range(3, total_ri):
tcs = _tcs(tbl, ri)
if len(tcs) == 8:
texts = [t.text or "" for t in tcs[0].iter(qn("w:t"))]
if not "".join(texts).strip():
return ri
return None
def _totals_row_index(tbl) -> int | None:
return _find_row_by_text(tbl, "Итого", 0)
def _grand_total_row_index(tbl) -> int | None:
return _find_row_by_text(tbl, "Всего по акту", 0)
def _delete_row(tbl, row_idx: int) -> None:
tr = _tr(tbl, row_idx)
tr.getparent().remove(tr)
def _clone_row_before(tbl, template_tr, before_tr):
new_tr = deepcopy(template_tr)
before_tr.addprevious(new_tr)
return new_tr
def _fill_data_row_tr(tr, item) -> None:
tcs = tr.findall(qn("w:tc"))
if len(tcs) < 8:
return
_set_tc_text(tcs[_COL_NUM], str(item.row_number), size_pt=9, align="center")
_set_tc_text(tcs[_COL_SOURCE], item.source_number or "", size_pt=9, align="center")
_set_tc_text(tcs[_COL_NAME], item.name or "", size_pt=9)
_set_tc_text(tcs[_COL_RATE], "", size_pt=9) # always empty
_set_tc_text(tcs[_COL_UNIT], item.unit or "", size_pt=9, align="center")
_set_tc_text(tcs[_COL_QTY], format_qty(item.quantity), size_pt=9, align="right")
_set_tc_text(tcs[_COL_PRICE], format_money(item.unit_price), size_pt=9, align="right")
_set_tc_text(tcs[_COL_AMOUNT], format_money(item.amount), size_pt=9, align="right")
def _merge_tr_cells(tr) -> object:
"""Merge every w:tc of a row into a single cell spanning all columns."""
tcs = tr.findall(qn("w:tc"))
if len(tcs) <= 1:
return tcs[0] if tcs else None
first = tcs[0]
tcPr = first.find(qn("w:tcPr"))
if tcPr is None:
tcPr = first.makeelement(qn("w:tcPr"), {})
first.insert(0, tcPr)
for gs in tcPr.findall(qn("w:gridSpan")):
tcPr.remove(gs)
gs = tcPr.makeelement(qn("w:gridSpan"), {qn("w:val"): str(len(tcs))})
tcPr.append(gs)
for tc in tcs[1:]:
tr.remove(tc)
return first
def _fill_group_row_tr(tr, title: str) -> None:
"""System/section divider: one merged cell across all 8 columns, bold title.
No row number — text never lands in the № column.
"""
tc = _merge_tr_cells(tr)
if tc is None:
return
_set_tc_text(tc, title, bold=True, size_pt=9, align="left")
def _group_title(code: str | None, name: str) -> str:
code = (code or "").strip()
name = name or ""
return f"{code} — {name}" if code else name
def _fill_totals(tbl, total) -> None:
ri = _totals_row_index(tbl)
if ri is None:
return
tcs = _tcs(tbl, ri)
# [5]'Итого' [1]'' [1]'Х' [1]'' → amount in the last tc
if tcs:
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
def _fill_grand_total(tbl, total) -> None:
ri = _grand_total_row_index(tbl)
if ri is None:
return
tcs = _tcs(tbl, ri)
if tcs:
_set_tc_text(tcs[-1], format_money(total), bold=True, size_pt=9, align="right")
def _delete_intermediate_totals(tbl) -> None:
"""Remove the intermediate «Итого» row (page subtotal) from a data table.
Only the final «Итого» / «Всего по акту» at the very end of the document
may show money totals (DOC-C6).
"""
ri = _totals_row_index(tbl)
if ri is not None:
_delete_row(tbl, ri)
def _set_header_repeat(tbl, n_header_rows: int) -> None:
"""Mark the first rows as a repeating Word header (w:tblHeader).
Word then repeats them automatically when the single works table
flows onto the next page (DOC-C7).
"""
for ri in range(min(n_header_rows, len(tbl.rows))):
tr = _tr(tbl, ri)
trPr = tr.find(qn("w:trPr"))
if trPr is None:
trPr = tr.makeelement(qn("w:trPr"), {})
tr.insert(0, trPr)
if trPr.find(qn("w:tblHeader")) is None:
trPr.append(trPr.makeelement(qn("w:tblHeader"), {}))
def _to_totals_block(tbl, total) -> None:
"""Turn a second data table into a standalone totals block (DOC-C7).
Keeps only the «Итого» and «Всего по акту» rows (already formatted like
the works table) and drops the copied header/data rows — this is not a
continuation table, just the closing money block after the last item.
"""
keep: set[int] = set()
ri_itogo = _totals_row_index(tbl)
ri_vsyo = _grand_total_row_index(tbl)
if ri_itogo is not None:
keep.add(ri_itogo)
if ri_vsyo is not None:
keep.add(ri_vsyo)
# delete every row except the totals rows (bottom-up so indices stay valid)
for ri in range(len(tbl.rows) - 1, -1, -1):
if ri not in keep:
_delete_row(tbl, ri)
_fill_totals(tbl, total)
_fill_grand_total(tbl, total)
def _place_storno(doc, h) -> None:
"""Bold red СТОРНИРОВАН as a body paragraph right before the АКТ title table.
Does not touch any table structure.
"""
if h.status != "cancelled":
return
body = doc.element.body
for child in body:
if child.tag != qn("w:tbl"):
continue
texts = [t.text or "" for t in child.iter(qn("w:t"))]
if any("О ПРИЕМКЕ" in t for t in texts):
p = body.makeelement(qn("w:p"), {})
child.addprevious(p)
pPr = p.makeelement(qn("w:pPr"), {})
p.append(pPr)
pPr.append(pPr.makeelement(qn("w:jc"), {qn("w:val"): "center"}))
run = p.makeelement(qn("w:r"), {})
p.append(run)
rPr = run.makeelement(qn("w:rPr"), {})
run.append(rPr)
rPr.append(rPr.makeelement(qn("w:b"), {}))
rPr.append(rPr.makeelement(qn("w:color"), {qn("w:val"): "FF0000"}))
rPr.append(rPr.makeelement(qn("w:sz"), {qn("w:val"): "28"}))
t = run.makeelement(qn("w:t"), {qn("xml:space"): "preserve"})
t.text = "СТОРНИРОВАН"
run.append(t)
break
def _expand_data_table(tbl, items, group_headers=None):
"""Fill data rows of a table; clone/delete template rows as needed.
`group_headers` maps id(item) -> (code, name) or a plain string.
Returns the number of item rows written.
"""
first_data = _data_row_index(tbl)
total_ri = _totals_row_index(tbl)
if first_data is None or total_ri is None:
return 0
# Build the sequence: optional group header rows + item rows.
sequence = []
for item in items:
gh = group_headers.get(id(item)) if group_headers else None
if gh:
sequence.append(("group", gh))
sequence.append(("item", item))
if not sequence:
sequence = []
template_tr = _tr(tbl, first_data)
# current number of data slots
slots = total_ri - first_data
needed = len(sequence)
# Delete unused slots (bottom-up).
for ri in range(total_ri - 1, first_data + needed - 1, -1):
if ri >= first_data:
_delete_row(tbl, ri)
# Insert extra clones before the totals row.
totals_tr = _tr(tbl, _totals_row_index(tbl))
for _ in range(max(0, needed - slots)):
_clone_row_before(tbl, template_tr, totals_tr)
# Fill.
data_start = _data_row_index(tbl)
for idx, (kind, payload) in enumerate(sequence):
tr = _tr(tbl, data_start + idx)
if kind == "group":
if isinstance(payload, tuple):
title = _group_title(payload[0], payload[1])
else:
title = str(payload)
_fill_group_row_tr(tr, title)
else:
_fill_data_row_tr(tr, payload)
return sum(1 for k, _ in sequence if k == "item")
def render_ks2_word(doc: KS2ExportDocument) -> bytes:
d = Document()
if not TEMPLATE_FILE.is_file():
raise TemplateNotFoundError(f"KS-2 Word template not found: {TEMPLATE_FILE}")
document = Document(str(TEMPLATE_FILE))
h = doc.header
section = d.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
tables = document.tables
if len(tables) < 7:
raise TemplateNotFoundError(
f"KS-2 Word template must contain 7 tables, found {len(tables)}"
)
# Title
title = d.add_paragraph()
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = title.add_run(f"Акт КС-2 №{h.ks2_number} от {h.ks2_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=7)
table.style = "Table Grid"
table.alignment = WD_TABLE_ALIGNMENT.CENTER
columns = ["№", "Наименование работ", "№ поз. в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
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)
# Static header fields: named template markers own the layout (DOC-C4).
fields = build_ks2_template_fields(doc)
fill_template_markers(document, fields)
# Group headers keyed by item identity (from DTO): (code, name).
group_headers: dict[int, tuple] = {}
for item in doc.items:
row = table.add_row()
row.cells[0].text = str(item.row_number)
row.cells[1].text = item.name
row.cells[2].text = item.source_number
row.cells[3].text = item.unit
row.cells[4].text = QTY_TEXT.format(item.quantity)
row.cells[5].text = MONEY_TEXT.format(item.unit_price)
row.cells[6].text = MONEY_TEXT.format(item.amount)
gh = getattr(item, "group_header", None)
if gh:
group_headers[id(item)] = (
getattr(item, "group_code", None) or "",
gh,
)
# Total row
total_row = table.add_row()
total_row.cells[0].merge(total_row.cells[5])
total_row.cells[0].text = "Итого:"
for paragraph in total_row.cells[0].paragraphs:
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
for run in paragraph.runs:
run.bold = True
total_row.cells[6].text = MONEY_TEXT.format(doc.total)
for paragraph in total_row.cells[6].paragraphs:
for run in paragraph.runs:
run.bold = True
items = list(doc.items)
# DOC-C7: one dynamic works table for every item and system row. Word
# flows it across pages on its own; the header repeats via w:tblHeader.
# No t3/t4 split, no per-page row limits.
_expand_data_table(tables[3], items, group_headers)
_set_header_repeat(tables[3], 3)
# The «Итого» template row of the works table is a page-subtotal slot —
# money totals live only in the separate closing block (DOC-C6).
_delete_intermediate_totals(tables[3])
# t4 used to be a second data table (page 2). It is now only the closing
# totals block: «Итого» + «Всего по акту» after the last position.
_to_totals_block(tables[4], doc.total)
_place_storno(document, h)
buf = io.BytesIO()
d.save(buf)
document.save(buf)
buf.seek(0)
return buf.read()
+70
View File
@@ -0,0 +1,70 @@
"""Named text markers for official-form DOCX templates (DOC-C4 prototype).
A working template carries named markers like ``{{ks2_number}}`` directly in
the cells where the renderer used to write static values. The template owns the
layout (geometry, merges, run formatting); Python owns the data.
``fill_template_markers(document, fields)`` replaces every ``{{name}}`` with
``fields[name]``. Only ``w:t`` text nodes are touched, so runs, line breaks and
cell geometry stay exactly as the template defines them.
Prototype limits (by design, see docs/tasks/DOC-C4-ks2-template-markers.md):
- a marker must sit inside a single run/w:t (true for ks2_ru_markers.docx);
- no VBA, no search by Russian labels, no cell coordinate math;
- a marker without a value in `fields` becomes an empty string — a missing
optional field never breaks the export.
"""
from __future__ import annotations
import re
from docx.oxml.ns import qn
MARKER_RE = re.compile(r"\{\{([a-z0-9_]+)\}\}")
# Named fields of the static KS-2 header (the marker contract of the template).
REQUIRED_KS2_MARKERS = (
"ks2_number",
"ks2_date",
"contract_number",
"contract_date_day",
"contract_date_month",
"contract_date_year",
"report_from",
"report_to",
"investor",
"customer",
"contractor",
"construction",
"object",
"contract_amount",
"contractor_signer_name",
"contractor_signer_position",
"customer_signer_name",
"customer_signer_position",
)
def fill_template_markers(document, fields) -> int:
"""Replace ``{{name}}`` markers in the document body with `fields` values.
`document` is a python-docx Document. `fields` maps marker name -> str.
Markers missing from `fields` are replaced with "" (never raises).
Returns the number of replacements made.
"""
fields = fields or {}
replaced = 0
def _sub(match):
nonlocal replaced
replaced += 1
return str(fields.get(match.group(1), ""))
for t in document.element.iter(qn("w:t")):
text = t.text
if not text or "{{" not in text:
continue
new_text = MARKER_RE.sub(_sub, text)
if new_text != text:
t.text = new_text
return replaced
+21 -12
View File
@@ -49,7 +49,8 @@ def _report_or_404(db: Session, project_id: int, report_id: int):
return report
def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_report_id=None):
def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_report_id=None,
all_systems: bool = False):
totals = db.query(
DailyReportItem.work_item_id.label("work_item_id"),
func.sum(DailyReportItem.completed_quantity).label("completed"),
@@ -64,7 +65,7 @@ def _report_rows(db: Session, project_id: int, system_id: int | None, exclude_re
rows = []
for planned in plan["items"]:
item = planned.item
if item.system_id == system_id:
if all_systems or item.system_id == system_id:
rows.append({"item": item, "planned_quantity": planned.quantity,
"accumulated": totals.get(item.id, Decimal("0"))})
rows.sort(key=lambda row: (row["item"].section_id or 0, row["item"].id))
@@ -98,11 +99,13 @@ def _render_form(request, db, project_obj, system_id=None, report=None, errors=N
selected_system = next((row for row in systems if row.id == selected_id), None)
if selected_system is None:
raise HTTPException(status_code=400, detail="System does not belong to this project effective plan")
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None)
rows = _report_rows(db, project_obj.id, selected_id, report.id if report else None,
all_systems=True)
current = {line.work_item_id: line.completed_quantity for line in report.items} if report else {}
for row in rows:
row["current_quantity"] = current.get(row["item"].id)
row["over_plan"] = row["accumulated"] + Decimal(str(row["current_quantity"] or 0)) > row["planned_quantity"]
row["in_selection"] = row["item"].system_id == selected_id
return request.app.templates.TemplateResponse("projects/daily_report_form.html", {
"request": request, "project": project_obj, "systems": systems,
"has_unclassified_items": bool(unclassified), "unclassified_selected": unclassified_selected,
@@ -171,7 +174,7 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
rows = _report_rows(db, project_id, report.system_id, report.id)
rows = _report_rows(db, project_id, report.system_id, report.id, all_systems=True)
lines = {line.work_item_id: line for line in report.items}
displayed = []
warnings = []
@@ -193,20 +196,22 @@ async def view_daily_report(request: Request, project_id: int, report_id: int,
row["closed_quantity"] = info.closed_quantity if info else Decimal("0")
row["available_quantity"] = info.available_quantity if info else row["current_quantity"]
can_del, del_reason = can_delete_report(db, report)
system_names = sorted({row["item"].system.name for row in displayed if row["item"].system})
return request.app.templates.TemplateResponse("projects/daily_report_view.html", {
"request": request, "project": project_obj, "report": report,
"rows": displayed, "warnings": warnings,
"rows": displayed, "warnings": warnings, "system_names": system_names,
"can_delete_report": can_del, "delete_blocked_reason": del_reason,
})
@router.get("/{project_id}/daily-reports/{report_id}/edit")
async def edit_daily_report(request: Request, project_id: int, report_id: int,
db: Session = Depends(get_db)):
system_id: str = None, db: Session = Depends(get_db)):
project_obj = _project_or_404(db, project_id)
report = _report_or_404(db, project_id, report_id)
return _render_form(request, db, project_obj,
report.system_id if report.system_id is not None else "unclassified", report)
selection = system_id if system_id not in (None, "") else (
report.system_id if report.system_id is not None else "unclassified")
return _render_form(request, db, project_obj, selection, report)
@router.post("/{project_id}/daily-reports/{report_id}/edit")
@@ -259,10 +264,14 @@ def _quantities_from_form(form):
def _validate_work_items(db, project_id, system_id, quantities):
effective_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]
if row.item.system_id == system_id}
if effective_ids.intersection(quantities) != set(quantities):
raise HTTPException(status_code=400, detail="One or more work items are not part of the selected system effective plan")
"""Quantities must reference effective-plan items of the project.
Items may come from several systems at once: one Daily Report can hold
positions of multiple systems, so only project membership is enforced.
"""
effective_ids = {row.item.id for row in build_effective_plan(db, project_id)["items"]}
if not set(quantities).issubset(effective_ids):
raise HTTPException(status_code=400, detail="One or more work items are not part of the project effective plan")
def _ks2_closed_item_ids(db, report_id):
+21 -1
View File
@@ -167,6 +167,7 @@ def save_draft(db: Session, project_id: int, number: str, document_date: date, c
def issue_ks2(db: Session, project_id: int, ks2_id: int):
"""Revalidate current balances, attribute quantity to DR lines oldest-first, and issue atomically."""
artifact = None
word_artifact = None
try:
document = db.query(KS2).filter(KS2.id == ks2_id, KS2.project_id == project_id).with_for_update().first()
if document is None:
@@ -217,12 +218,17 @@ def issue_ks2(db: Session, project_id: int, ks2_id: int):
)
document.status = "issued"
# Generate and persist the official artifact inside this transaction.
# Generate and persist the official artifacts inside this transaction.
from app.exporters.excel.ks2_renderer import (
TEMPLATE_TYPE as KS2_TEMPLATE_TYPE,
TEMPLATE_VERSION as KS2_TEMPLATE_VERSION,
render_ks2_excel,
)
from app.exporters.word.ks2_renderer import (
TEMPLATE_TYPE as KS2_WORD_TEMPLATE_TYPE,
TEMPLATE_VERSION as KS2_WORD_TEMPLATE_VERSION,
render_ks2_word,
)
from app.exporters.ks2_dto import build_ks2_export_dto
from app.services.document_artifact_service import persist_artifact, remove_artifact_file
@@ -239,6 +245,18 @@ def issue_ks2(db: Session, project_id: int, ks2_id: int):
content=content,
dto=dto,
)
word_content = render_ks2_word(dto)
word_artifact = persist_artifact(
db,
project_id=project_id,
document_type="KS2",
document_id=document.id,
format="docx",
template_type=KS2_WORD_TEMPLATE_TYPE,
template_version=KS2_WORD_TEMPLATE_VERSION,
content=word_content,
dto=dto,
)
db.commit()
db.refresh(document)
@@ -247,6 +265,8 @@ def issue_ks2(db: Session, project_id: int, ks2_id: int):
db.rollback()
if artifact is not None:
remove_artifact_file(artifact)
if word_artifact is not None:
remove_artifact_file(word_artifact)
raise
+3 -8
View File
@@ -30,14 +30,9 @@
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
{% endif %}
<div class="mt-2">
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
{% if document.status != 'draft' %}
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/artifact" class="btn btn-outline-dark btn-sm">
📎 Официальная форма (Excel)
{% if document.status == 'cancelled' %}<span class="badge bg-danger ms-1">СТОРНИРОВАН</span>{% endif %}
</a>
{% endif %}
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">КС-2 (Excel)</a>
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">КС-2 (Word)</a>
{% if document.status == 'cancelled' %}<span class="badge bg-danger ms-1">СТОРНИРОВАН</span>{% endif %}
</div>
</div>
</div>
+27 -8
View File
@@ -18,7 +18,7 @@
{% for system in systems %}<option value="{{ system.id }}" {% if selected_system and selected_system.id == system.id %}selected{% endif %}>{{ system.name }}</option>{% endfor %}
{% if has_unclassified_items %}<option value="unclassified" {% if unclassified_selected %}selected{% endif %}>&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;</option>{% endif %}
</select><button class="btn btn-outline-primary" type="submit">Показать позиции</button></div>
{% if report %}<div class="form-text">При смене системы сначала нажмите «Показать позиции»; несохранённые изменения формы будут сброшены.</div>{% endif %}
<div class="form-text">Выберите систему и нажмите «Показать позиции». Позиции разных систем можно добавлять в один отчёт — уже введённые количества сохраняются.</div>
</form>
{% if selected_system or unclassified_selected %}
@@ -31,7 +31,7 @@
</div>
</div>
<div class="card">
<div class="card-header"><strong>{{ selected_system.name if selected_system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}</strong> — укажите фактическое количество хотя бы для одной позиции</div>
<div class="card-header"><strong><span id="current-system-name">{{ selected_system.name if selected_system else '&#1055;&#1088;&#1086;&#1077;&#1082;&#1090;&#1085;&#1099;&#1077; &#1087;&#1086;&#1079;&#1080;&#1094;&#1080;&#1080; &#1073;&#1077;&#1079; &#1089;&#1080;&#1089;&#1090;&#1077;&#1084;&#1099;' }}</span></strong> — укажите фактическое количество хотя бы для одной позиции</div>
<div class="p-3 border-bottom">
<label class="form-label" for="position-search">Поиск позиций</label>
<input id="position-search" class="form-control" type="search" autocomplete="off" placeholder="Номер, наименование, модель или производитель">
@@ -41,12 +41,12 @@
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">Накоплено до отчёта</th><th style="width: 180px">Выполнено за дату</th></tr></thead>
<tbody>
{% for row in rows %}
<tr class="position-row {% if row.over_plan %}table-warning{% endif %}" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}">
<td>{{ row.item.section.name if row.item.section else '—' }}</td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td>
<tr class="position-row {% if row.over_plan %}table-warning{% endif %}" data-number="{{ row.item.source_number or '' }}" data-name="{{ row.item.name or '' }}" data-model="{{ row.item.model or '' }}" data-manufacturer="{{ row.item.manufacturer or '' }}" data-system="{{ row.item.system_id if row.item.system_id is not none else 'unclassified' }}" {% if not row.in_selection and row.current_quantity is none %}hidden{% endif %}>
<td>{{ row.item.section.name if row.item.section else '—' }}<div class="small text-muted">{{ row.item.system.name if row.item.system else 'Без системы' }}</div></td><td>{{ row.item.source_number or '' }}</td><td>{{ row.item.name }}</td><td>{{ row.item.unit or '' }}</td>
<td class="text-end">{{ row.planned_quantity if row.planned_quantity is not none else '—' }}</td><td class="text-end">{{ row.accumulated }}</td>
<td><input class="form-control form-control-sm" type="number" min="0" step="0.0001" name="quantity_{{ row.item.id }}" value="{{ row.current_quantity if row.current_quantity is not none else '' }}" aria-label="Выполнено: {{ row.item.name }}"></td>
</tr>
{% else %}<tr><td colspan="7" class="text-center text-muted py-4">В этой системе нет рабочих позиций ведомости.</td></tr>{% endfor %}
{% else %}<tr><td colspan="7" class="text-center text-muted py-4">В ведомости нет рабочих позиций.</td></tr>{% endfor %}
</tbody>
</table></div>
<div class="card-footer d-flex justify-content-between"><a class="btn btn-outline-secondary" href="/projects/{{ project.id }}/daily-reports">Отмена</a><button class="btn btn-primary" type="submit">{{ 'Сохранить изменения' if report else 'Создать отчёт' }}</button></div>
@@ -58,18 +58,37 @@
if (!search) return;
const rows = [...document.querySelectorAll('.position-row')];
const empty = document.getElementById('position-search-empty');
const picker = document.getElementById('system-picker');
const pickerForm = picker ? picker.form : null;
const hiddenSystem = document.querySelector('form[method="post"] input[name="system_id"]');
const systemName = document.getElementById('current-system-name');
const normalize = value => (value || '').toLocaleLowerCase('ru-RU').trim();
search.addEventListener('input', () => {
const applyFilters = () => {
const selected = picker ? picker.value : '';
const query = normalize(search.value);
let visible = 0;
for (const row of rows) {
const filled = [...row.querySelectorAll('input')].some(input => input.value.trim() !== '');
const inSystem = !selected || row.dataset.system === selected || filled;
const haystack = normalize(['number', 'name', 'model', 'manufacturer']
.map(key => row.dataset[key]).join(' '));
row.hidden = !haystack.includes(query);
row.hidden = !(inSystem && haystack.includes(query));
if (!row.hidden) visible++;
}
empty.hidden = visible !== 0;
});
};
if (pickerForm && picker) {
pickerForm.addEventListener('submit', event => {
event.preventDefault();
if (hiddenSystem) hiddenSystem.value = picker.value;
if (systemName && picker.selectedOptions.length) {
systemName.textContent = picker.selectedOptions[0].textContent;
}
applyFilters();
});
}
search.addEventListener('input', applyFilters);
applyFilters();
})();
</script>
{% endif %}
@@ -11,7 +11,7 @@
<div class="d-flex justify-content-between align-items-start mb-4 gap-3 flex-wrap">
<div>
<h1>Daily Report</h1>
<div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ report.system.name if report.system else 'Проектные позиции без системы' }}</div>
<div class="text-muted">{{ report.report_date.strftime('%d.%m.%Y') }} · {{ system_names|join(', ') if system_names else 'Проектные позиции без системы' }}</div>
{% if report.notes %}<p class="mt-2">{{ report.notes }}</p>{% endif %}
</div>
<div class="d-flex gap-2">
@@ -35,7 +35,7 @@
<thead><tr><th>Раздел</th><th>№</th><th>Рабочая позиция</th><th>Ед.</th><th class="text-end">План</th><th class="text-end">В этом отчёте</th><th class="text-end">Закрыто КС-2</th><th class="text-end">Доступно</th></tr></thead>
<tbody>{% for row in rows %}
<tr class="{% if row.over_plan %}table-warning{% endif %}">
<td>{{ row.item.section.name if row.item.section else '—' }}</td>
<td>{{ row.item.section.name if row.item.section else '—' }}<div class="small text-muted">{{ row.item.system.name if row.item.system else 'Без системы' }}</div></td>
<td>{{ row.item.source_number or '' }}</td>
<td>{{ row.item.name }}</td>
<td>{{ row.item.unit or '' }}</td>
Binary file not shown.
Binary file not shown.
Binary file not shown.
+21 -8
View File
@@ -1,22 +1,35 @@
{
"template_type": "ks2",
"template_version": 1,
"file": "ks2_ru_v1.xlsx",
"template_version": 2,
"file": "ks2_ru_v2.xlsx",
"format": "xlsx",
"language": "ru",
"description": "Акт КС-2, упрощённая табличная часть (DOC-B3)",
"description": "Акт КС-2, официальная унифицированная форма № КС-2 (DOC-C2)",
"table_marker": "##KS2_ROWS##",
"group_marker": "##KS2_GROUP##",
"totals_marker": "##KS2_TOTALS##",
"storno_marker": "##KS2_STORNO##",
"placeholders": [
"project_name",
"customer",
"contractor_name",
"object_name",
"contract_number",
"contract_date",
"currency",
"period",
"comment",
"ks2_number",
"ks2_date"
"ks2_date",
"period_from",
"period_to",
"contractor_signer_position",
"contractor_signer_name",
"customer_signer_position",
"customer_signer_name"
],
"row_placeholders": [
"source_number",
"name",
"unit",
"quantity",
"unit_price",
"amount"
]
}