feat: add KS-6a Excel/Word export

This commit is contained in:
Арсентьев Александр
2026-09-27 14:32:36 +03:00
parent 9cfb341774
commit 34fb98e69c
9 changed files with 1281 additions and 30 deletions
+23
View File
@@ -0,0 +1,23 @@
"""Export layer: shared DTOs, helpers, and format-specific renderers."""
import re
from urllib.parse import quote
def _clean_export_name(raw: str) -> str:
return re.sub(r'[<>:"/\\|?*]', "_", raw)
def safe_export_filename(prefix: str, number: str, dt, extension: str) -> str:
raw = f"{prefix} №{number} от {dt.strftime('%d.%m.%Y')}"
return f"{_clean_export_name(raw)}.{extension}"
def safe_export_filename_period(prefix: str, date_from, date_to, extension: str, suffix: str = "") -> str:
raw = f"{prefix}_{date_from.strftime('%d.%m.%Y')}-{date_to.strftime('%d.%m.%Y')}"
if suffix:
raw = f"{raw}_{suffix}"
return f"{_clean_export_name(raw)}.{extension}"
def content_disposition(filename: str) -> str:
return f"attachment; filename*=UTF-8''{quote(filename)}"
+107
View File
@@ -0,0 +1,107 @@
"""Excel renderer for KS-6a 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.ks6a_dto import KS6aExportDocument
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)
QTY_FMT = '#,##0.00'
def render_ks6a_excel(doc: KS6aExportDocument) -> bytes:
wb = Workbook()
ws = wb.active
ws.title = "КС-6а"
h = doc.header
row = 1
# Title
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=8)
c = ws.cell(row=row, column=1, value="КС-6а — Журнал учёта выполненных работ")
c.font = TITLE_FONT
c.alignment = Alignment(horizontal="center")
row += 1
# Header block
header_lines = [
("Проект:", h.project_name),
("Заказчик:", h.customer),
]
if h.contractor:
header_lines.append(("Подрядчик:", h.contractor))
header_lines.append(("Договор:", h.contract_number))
header_lines.append((
"Период:",
f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}",
))
if h.system_name:
header_lines.append(("Система:", h.system_name))
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=8)
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 — one row per DailyReportItem
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.report_date.strftime("%d.%m.%Y"))
c.border = BORDER
c = ws.cell(row=row, column=3, value=item.system_name)
c.border = BORDER
c.alignment = Alignment(wrap_text=True, vertical="top")
c = ws.cell(row=row, column=4, value=item.section_name)
c.border = BORDER
c.alignment = Alignment(wrap_text=True, vertical="top")
ws.cell(row=row, column=5, value=item.source_number).border = BORDER
c = ws.cell(row=row, column=6, value=item.name)
c.border = BORDER
c.alignment = Alignment(wrap_text=True, vertical="top")
ws.cell(row=row, column=7, value=item.unit).border = BORDER
c = ws.cell(row=row, column=8, value=float(item.quantity))
c.border = BORDER
c.number_format = QTY_FMT
row += 1
# Column widths
widths = {1: 5, 2: 12, 3: 16, 4: 16, 5: 12, 6: 40, 7: 10, 8: 12}
for col, width in widths.items():
ws.column_dimensions[get_column_letter(col)].width = width
# Freeze table header
ws.freeze_panes = ws.cell(row=header_row + 1, column=1)
buf = io.BytesIO()
wb.save(buf)
buf.seek(0)
return buf.read()
+97
View File
@@ -0,0 +1,97 @@
"""KS-6a export DTO. One source of truth for Excel and Word renderers.
KS-6a is a reporting view of actual completed work from Daily Reports.
One row = one DailyReportItem. No financial data (price/amount/plan/KS-2 balance).
"""
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
@dataclass(frozen=True)
class KS6aExportItem:
row_number: int
report_date: date
system_name: str
section_name: str
source_number: str
name: str
unit: str
quantity: Decimal
@dataclass(frozen=True)
class KS6aExportHeader:
project_name: str
customer: str
contractor: str
contract_number: str
period_from: date
period_to: date
system_name: str
@dataclass(frozen=True)
class KS6aExportDocument:
header: KS6aExportHeader
items: list[KS6aExportItem]
def fetch_ks6a_rows(db, project_id: int, date_from: date, date_to: date, system_id: int | None = None):
"""One KS-6a row = one DailyReportItem. No aggregation across Daily Reports."""
from sqlalchemy.orm import joinedload
from app.models.boq import WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
query = db.query(DailyReportItem).join(
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
).join(
WorkItem, WorkItem.id == DailyReportItem.work_item_id
).options(
joinedload(DailyReportItem.work_item),
joinedload(DailyReportItem.report),
).filter(
DailyReport.project_id == project_id,
DailyReport.report_date >= date_from,
DailyReport.report_date <= date_to,
)
if system_id is not None:
query = query.filter(WorkItem.system_id == system_id)
return query.order_by(
DailyReport.report_date,
DailyReport.id,
DailyReportItem.id,
).all()
def build_ks6a_export_dto(project, rows, date_from: date, date_to: date, system_name: str = "") -> KS6aExportDocument:
"""Build the export DTO from KS-6a reporting rows. Read-only: does not modify any data."""
from decimal import Decimal as D
items = []
for idx, row in enumerate(rows, start=1):
wi = row.work_item
items.append(KS6aExportItem(
row_number=idx,
report_date=row.report.report_date,
system_name=wi.system.name if wi.system else "",
section_name=wi.section.name if wi.section else "",
source_number=wi.source_number or "",
name=wi.name or "",
unit=wi.unit or "",
quantity=D(str(row.completed_quantity or 0)),
))
header = KS6aExportHeader(
project_name=project.name if project else "",
customer=project.customer if project and project.customer else "",
contractor="",
contract_number=project.contract_number if project and project.contract_number else "",
period_from=date_from,
period_to=date_to,
system_name=system_name or "",
)
return KS6aExportDocument(header=header, items=items)
+85
View File
@@ -0,0 +1,85 @@
"""Word renderer for KS-6a 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
from app.exporters.ks6a_dto import KS6aExportDocument
def render_ks6a_word(doc: KS6aExportDocument) -> bytes:
d = Document()
h = doc.header
# Landscape page for the wide table
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("КС-6а — Журнал учёта выполненных работ")
run.bold = True
run.font.size = Pt(14)
d.add_paragraph()
# Header block
header_lines = [
("Проект:", h.project_name),
("Заказчик:", h.customer),
]
if h.contractor:
header_lines.append(("Подрядчик:", h.contractor))
header_lines.append(("Договор:", h.contract_number))
header_lines.append((
"Период:",
f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}",
))
if h.system_name:
header_lines.append(("Система:", h.system_name))
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 — one row per DailyReportItem
table = d.add_table(rows=1, cols=8)
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.report_date.strftime("%d.%m.%Y")
row.cells[2].text = item.system_name
row.cells[3].text = item.section_name
row.cells[4].text = item.source_number
row.cells[5].text = item.name
row.cells[6].text = item.unit
row.cells[7].text = f"{item.quantity:.2f}"
buf = io.BytesIO()
d.save(buf)
buf.seek(0)
return buf.read()
+91 -24
View File
@@ -3,12 +3,12 @@ from decimal import Decimal
from pathlib import Path
from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.responses import Response
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
from sqlalchemy.orm import Session
from app.database.database import get_db
from app.models.boq import System, WorkItem
from app.models.daily_report import DailyReport, DailyReportItem
from app.models.boq import System
from app.models.project import Project
@@ -62,33 +62,16 @@ async def ks6a_journal(
error = "Дата окончания не может быть раньше даты начала"
if parsed_from and parsed_to and not error:
query = db.query(DailyReportItem).join(
DailyReport, DailyReport.id == DailyReportItem.daily_report_id
).join(
WorkItem, WorkItem.id == DailyReportItem.work_item_id
).options(
joinedload(DailyReportItem.work_item),
joinedload(DailyReportItem.report),
).filter(
DailyReport.project_id == project_id,
DailyReport.report_date >= parsed_from,
DailyReport.report_date <= parsed_to,
)
sid = None
if system_id and system_id != "all":
try:
sid = int(system_id)
except (ValueError, TypeError):
error = "Некорректный идентификатор системы"
else:
query = query.filter(WorkItem.system_id == sid)
if not error:
rows = query.order_by(
DailyReport.report_date,
DailyReport.id,
DailyReportItem.id,
).all()
from app.exporters.ks6a_dto import fetch_ks6a_rows
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
total_count = len(rows)
return templates.TemplateResponse(name="ks6a/journal.html", context={
@@ -101,4 +84,88 @@ async def ks6a_journal(
"date_to": date_to,
"system_id": system_id,
"error": error,
})
})
def _export_filters(db, project_id: int, date_from: str, date_to: str, system_id: str):
if not date_from or not date_to:
raise HTTPException(status_code=400, detail="Необходимо указать период (date_from и date_to)")
try:
parsed_from = date.fromisoformat(date_from)
parsed_to = date.fromisoformat(date_to)
except ValueError:
raise HTTPException(status_code=400, detail="Неверный формат даты")
if parsed_to < parsed_from:
raise HTTPException(status_code=400, detail="Дата окончания не может быть раньше даты начала")
sid = None
system_name = ""
if system_id and system_id != "all":
try:
sid = int(system_id)
except (ValueError, TypeError):
raise HTTPException(status_code=400, detail="Некорректный идентификатор системы")
system = db.query(System).filter(
System.id == sid, System.project_id == project_id
).first()
if system is None:
raise HTTPException(status_code=400, detail="Система не найдена")
system_name = system.name
return parsed_from, parsed_to, sid, system_name
def _export_filename(date_from, date_to, system_name: str, extension: str) -> str:
from app.exporters import safe_export_filename_period
return safe_export_filename_period("КС-6а", date_from, date_to, extension, suffix=system_name)
def _content_disposition(filename: str) -> str:
from app.exporters import content_disposition
return content_disposition(filename)
@router.get("/{project_id}/ks6a/export/excel")
async def ks6a_export_excel(
project_id: int,
date_from: str = "",
date_to: str = "",
system_id: str = "",
db: Session = Depends(get_db),
):
project = _project(db, project_id)
parsed_from, parsed_to, sid, system_name = _export_filters(db, project_id, date_from, date_to, system_id)
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
from app.exporters.excel.ks6a_renderer import render_ks6a_excel
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
dto = build_ks6a_export_dto(project, rows, parsed_from, parsed_to, system_name)
data = render_ks6a_excel(dto)
filename = _export_filename(parsed_from, parsed_to, system_name, "xlsx")
return Response(
content=data,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
headers={"Content-Disposition": _content_disposition(filename)},
)
@router.get("/{project_id}/ks6a/export/word")
async def ks6a_export_word(
project_id: int,
date_from: str = "",
date_to: str = "",
system_id: str = "",
db: Session = Depends(get_db),
):
project = _project(db, project_id)
parsed_from, parsed_to, sid, system_name = _export_filters(db, project_id, date_from, date_to, system_id)
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
from app.exporters.word.ks6a_renderer import render_ks6a_word
rows = fetch_ks6a_rows(db, project_id, parsed_from, parsed_to, sid)
dto = build_ks6a_export_dto(project, rows, parsed_from, parsed_to, system_name)
data = render_ks6a_word(dto)
filename = _export_filename(parsed_from, parsed_to, system_name, "docx")
return Response(
content=data,
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
headers={"Content-Disposition": _content_disposition(filename)},
)
+12 -6
View File
@@ -43,12 +43,18 @@
{% endif %}
{% if date_from and date_to and not error %}
<div class="mb-2 text-muted">
Период: {{ date_from }} — {{ date_to }}
{% if system_id and system_id != 'all' %}
{% for system in systems %}{% if system_id|string == system.id|string %} · Система: {{ system.name }}{% endif %}{% endfor %}
{% else %} · Все системы{% endif %}
· Строк: {{ total_count }}
<div class="mb-2 d-flex flex-wrap align-items-center gap-2">
<div class="text-muted">
Период: {{ date_from }} — {{ date_to }}
{% if system_id and system_id != 'all' %}
{% for system in systems %}{% if system_id|string == system.id|string %} · Система: {{ system.name }}{% endif %}{% endfor %}
{% else %} · Все системы{% endif %}
· Строк: {{ total_count }}
</div>
<a href="/projects/{{ project.id }}/ks6a/export/excel?date_from={{ date_from }}&amp;date_to={{ date_to }}&amp;system_id={{ system_id or 'all' }}"
class="btn btn-outline-success btn-sm">📊 Excel</a>
<a href="/projects/{{ project.id }}/ks6a/export/word?date_from={{ date_from }}&amp;date_to={{ date_to }}&amp;system_id={{ system_id or 'all' }}"
class="btn btn-outline-primary btn-sm">📄 Word</a>
</div>
{% if rows %}