feat: add KS-3 Excel/Word export

This commit is contained in:
Арсентьев Александр
2026-09-27 14:36:42 +03:00
parent 34fb98e69c
commit 6e365ac434
8 changed files with 699 additions and 6 deletions
+100
View File
@@ -0,0 +1,100 @@
"""Excel renderer for KS-3 export using openpyxl."""
import io
from openpyxl import Workbook
from openpyxl.styles import Alignment, Border, Font, Side
from openpyxl.utils import get_column_letter
from app.exporters.ks3_dto import KS3ExportDocument
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'
def render_ks3_excel(doc: KS3ExportDocument) -> bytes:
wb = Workbook()
ws = wb.active
ws.title = "КС-3"
h = doc.header
row = 1
# Title
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=5)
c = ws.cell(row=row, column=1, value=f"КС-3 №{h.ks3_number} от {h.ks3_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=5)
ws.cell(row=row, column=2, value=value)
row += 1
row += 1 # blank row
# Table header
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
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)
row += 1
# Items
for item in doc.items:
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
ws.cell(row=row, column=2, value=f"№{item.ks2_number}").border = BORDER
c = ws.cell(row=row, column=3, value=item.ks2_date.strftime('%d.%m.%Y') if item.ks2_date else "")
c.border = BORDER
period_text = ""
if item.period_from and item.period_to:
period_text = f"{item.period_from.strftime('%d.%m.%Y')} — {item.period_to.strftime('%d.%m.%Y')}"
c = ws.cell(row=row, column=4, value=period_text)
c.border = BORDER
c = ws.cell(row=row, column=5, 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=4)
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, 5):
ws.cell(row=row, column=col).border = BORDER
c = ws.cell(row=row, column=5, value=float(doc.total))
c.font = HEADER_FONT
c.border = BORDER
c.number_format = MONEY_FMT
# Column widths
widths = {1: 5, 2: 12, 3: 14, 4: 24, 5: 16}
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 @@
"""KS-3 export DTO. One source of truth for Excel and Word renderers."""
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
@dataclass(frozen=True)
class KS3ExportItem:
row_number: int
ks2_number: str
ks2_date: date | None
period_from: date | None
period_to: date | None
amount: Decimal
@dataclass(frozen=True)
class KS3ExportHeader:
project_name: str
customer: str
contract_number: str
ks3_number: str
ks3_date: date
period_from: date | None
period_to: date | None
comment: str
@dataclass(frozen=True)
class KS3ExportDocument:
header: KS3ExportHeader
items: list[KS3ExportItem]
total: Decimal
def build_ks3_export_dto(db, ks3_document) -> KS3ExportDocument:
"""Build the export DTO from a KS3 document. Read-only: does not modify any data."""
from decimal import Decimal as D
project = ks3_document.project
items = []
total = D("0")
for idx, link in enumerate(ks3_document.links, start=1):
ks2 = link.ks2
if ks2 is None:
continue
amount = sum((D(str(line.amount or 0)) for line in ks2.items), D("0"))
total += amount
items.append(KS3ExportItem(
row_number=idx,
ks2_number=ks2.number,
ks2_date=ks2.date,
period_from=ks2.reporting_period_from,
period_to=ks2.reporting_period_to,
amount=amount,
))
header = KS3ExportHeader(
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 "",
ks3_number=ks3_document.number,
ks3_date=ks3_document.date,
period_from=ks3_document.reporting_period_from,
period_to=ks3_document.reporting_period_to,
comment=ks3_document.comment or "",
)
return KS3ExportDocument(header=header, items=items, total=total)
+85
View File
@@ -0,0 +1,85 @@
"""Word renderer for KS-3 export using python-docx."""
import io
from docx import Document
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT
from app.exporters.ks3_dto import KS3ExportDocument
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
d = Document()
h = doc.header
# Title
title = d.add_paragraph()
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = title.add_run(f"КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
run.bold = True
run.font.size = Pt(14)
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=5)
table.style = "Table Grid"
table.alignment = WD_TABLE_ALIGNMENT.CENTER
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
for idx, col_name in enumerate(columns):
cell = table.rows[0].cells[idx]
cell.text = col_name
for paragraph in cell.paragraphs:
for run in paragraph.runs:
run.bold = True
run.font.size = Pt(9)
for item in doc.items:
row = table.add_row()
row.cells[0].text = str(item.row_number)
row.cells[1].text = f"№{item.ks2_number}"
row.cells[2].text = item.ks2_date.strftime('%d.%m.%Y') if item.ks2_date else ""
period_text = ""
if item.period_from and item.period_to:
period_text = f"{item.period_from.strftime('%d.%m.%Y')} — {item.period_to.strftime('%d.%m.%Y')}"
row.cells[3].text = period_text
row.cells[4].text = f"{item.amount:.2f}"
# Total row
total_row = table.add_row()
total_row.cells[0].merge(total_row.cells[3])
total_row.cells[0].text = "Итого:"
for paragraph in total_row.cells[0].paragraphs:
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
for run in paragraph.runs:
run.bold = True
total_row.cells[4].text = f"{doc.total:.2f}"
for paragraph in total_row.cells[4].paragraphs:
for run in paragraph.runs:
run.bold = True
buf = io.BytesIO()
d.save(buf)
buf.seek(0)
return buf.read()