Files
work-volume-tracker/app/exporters/word/ks3_renderer.py
T
Арсентьев Александр 9992a435b2 feat: enforce KS-2/KS-3 stornation integrity
2026-09-27 18:12:19 +03:00

95 lines
3.0 KiB
Python

"""Word renderer for KS-3 export using python-docx."""
import io
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 app.exporters.common import MONEY_TEXT, format_date, format_period, project_requisite_lines
from app.exporters.ks3_dto import KS3ExportDocument
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
d = Document()
h = doc.header
section = d.sections[0]
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width, section.page_height = section.page_height, section.page_width
# 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)
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=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 = format_date(item.ks2_date)
row.cells[3].text = format_period(item.period_from, item.period_to)
row.cells[4].text = MONEY_TEXT.format(item.amount)
# 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 = MONEY_TEXT.format(doc.total)
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()