feat: add KS-3/payments, tech debt fixes, UI polish, and KS-2 Excel/Word export

Tasks 008-016: KS-6a journal, KS-3 documents, payments with allocations,
tech debt cleanup, financial privacy, document tree, storno mechanism,
row-click UI, BOQ collapse/sticky header, and KS-2 export to Excel/Word
via shared DTO architecture.
This commit is contained in:
Арсентьев Александр
2026-09-27 13:38:45 +03:00
parent 6c608a8779
commit 9cfb341774
57 changed files with 7163 additions and 50 deletions
View File
View File
+106
View File
@@ -0,0 +1,106 @@
"""Excel renderer for KS-2 export using openpyxl."""
import io
from decimal import Decimal
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, Side
from openpyxl.utils import get_column_letter
from app.exporters.ks2_dto import KS2ExportDocument
THIN = Side(style="thin")
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
HEADER_FONT = Font(bold=True, size=11)
TITLE_FONT = Font(bold=True, size=14)
MONEY_FMT = '#,##0.00'
QTY_FMT = '#,##0.0000'
def render_ks2_excel(doc: KS2ExportDocument) -> bytes:
wb = Workbook()
ws = wb.active
ws.title = "КС-2"
h = doc.header
row = 1
# Title
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=7)
c = ws.cell(row=row, column=1, value=f"Акт КС-2 №{h.ks2_number} от {h.ks2_date.strftime('%d.%m.%Y')}")
c.font = TITLE_FONT
c.alignment = Alignment(horizontal="center")
row += 1
# Header block
header_lines = [
("Проект:", h.project_name),
("Заказчик:", h.customer),
("Договор:", h.contract_number),
]
if h.period_from and h.period_to:
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
if h.comment:
header_lines.append(("Комментарий:", h.comment))
for label, value in header_lines:
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=7)
ws.cell(row=row, column=2, value=value)
row += 1
row += 1 # blank row
# Table header
columns = ["№", "Наименование работ", "№ позиции в ведомости", "Ед. изм.", "Количество", "Цена за ед.", "Стоимость"]
for col_idx, col_name in enumerate(columns, start=1):
c = ws.cell(row=row, column=col_idx, value=col_name)
c.font = HEADER_FONT
c.border = BORDER
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
header_row = row
row += 1
# Items
for item in doc.items:
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
c = ws.cell(row=row, column=2, value=item.name)
c.border = BORDER
c.alignment = Alignment(wrap_text=True, vertical="top")
ws.cell(row=row, column=3, value=item.source_number).border = BORDER
ws.cell(row=row, column=4, value=item.unit).border = BORDER
c = ws.cell(row=row, column=5, value=float(item.quantity))
c.border = BORDER
c.number_format = QTY_FMT
c = ws.cell(row=row, column=6, value=float(item.unit_price))
c.border = BORDER
c.number_format = MONEY_FMT
c = ws.cell(row=row, column=7, value=float(item.amount))
c.border = BORDER
c.number_format = MONEY_FMT
row += 1
# Total row
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=6)
c = ws.cell(row=row, column=1, value="Итого:")
c.font = HEADER_FONT
c.border = BORDER
c.alignment = Alignment(horizontal="right")
for col in range(2, 7):
ws.cell(row=row, column=col).border = BORDER
c = ws.cell(row=row, column=7, value=float(doc.total))
c.font = HEADER_FONT
c.border = BORDER
c.number_format = MONEY_FMT
# Column widths
widths = {1: 5, 2: 40, 3: 15, 4: 10, 5: 12, 6: 14, 7: 14}
for col, width in widths.items():
ws.column_dimensions[get_column_letter(col)].width = width
buf = io.BytesIO()
wb.save(buf)
buf.seek(0)
return buf.read()
+68
View File
@@ -0,0 +1,68 @@
"""Shared document DTOs for export renderers. One source of truth for Excel and Word."""
from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
@dataclass(frozen=True)
class KS2ExportItem:
row_number: int
source_number: str
name: str
unit: str
quantity: Decimal
unit_price: Decimal
amount: Decimal
@dataclass(frozen=True)
class KS2ExportHeader:
project_name: str
customer: str
contract_number: str
ks2_number: str
ks2_date: date
period_from: date | None
period_to: date | None
comment: str
@dataclass(frozen=True)
class KS2ExportDocument:
header: KS2ExportHeader
items: list[KS2ExportItem]
total: Decimal
def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument:
"""Build the export DTO from a KS2 document. Read-only: does not modify any data."""
from decimal import Decimal as D
project = ks2_document.project
items = []
total = D("0")
for idx, line in enumerate(ks2_document.items, start=1):
wi = line.work_item
amount = D(str(line.amount or 0))
total += amount
items.append(KS2ExportItem(
row_number=idx,
source_number=wi.source_number or "",
name=wi.name or "",
unit=wi.unit or "",
quantity=D(str(line.quantity or 0)),
unit_price=D(str(line.unit_price or 0)),
amount=amount,
))
header = KS2ExportHeader(
project_name=project.name if project else "",
customer=project.customer if project and project.customer else "",
contract_number=project.contract_number if project and project.contract_number else "",
ks2_number=ks2_document.number,
ks2_date=ks2_document.date,
period_from=ks2_document.reporting_period_from,
period_to=ks2_document.reporting_period_to,
comment=ks2_document.comment or "",
)
return KS2ExportDocument(header=header, items=items, total=total)
View File
+84
View File
@@ -0,0 +1,84 @@
"""Word renderer for KS-2 export using python-docx."""
import io
from docx import Document
from docx.shared import Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from app.exporters.ks2_dto import KS2ExportDocument
def render_ks2_word(doc: KS2ExportDocument) -> bytes:
d = Document()
h = doc.header
# 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)
d.add_paragraph()
# Header block
header_lines = [
("Проект:", h.project_name),
("Заказчик:", h.customer),
("Договор:", h.contract_number),
]
if h.period_from and h.period_to:
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
if h.comment:
header_lines.append(("Комментарий:", 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)
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 = f"{item.quantity:.4f}"
row.cells[5].text = f"{item.unit_price:.2f}"
row.cells[6].text = f"{item.amount:.2f}"
# 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 = f"{doc.total:.2f}"
for paragraph in total_row.cells[6].paragraphs:
for run in paragraph.runs:
run.bold = True
buf = io.BytesIO()
d.save(buf)
buf.seek(0)
return buf.read()