diff --git a/app/exporters/common.py b/app/exporters/common.py new file mode 100644 index 0000000..33668fc --- /dev/null +++ b/app/exporters/common.py @@ -0,0 +1,47 @@ +"""Shared export formatting helpers for Excel/Word renderers.""" +from datetime import date + +DATE_FMT = "%d.%m.%Y" +MONEY_FMT = "#,##0.00" +QTY_FMT = "#,##0.00" +MONEY_TEXT = "{:.2f}" +QTY_TEXT = "{:.2f}" + + +def format_date(value: date | None) -> str: + return value.strftime(DATE_FMT) if value else "" + + +def format_period(date_from: date | None, date_to: date | None) -> str: + if date_from and date_to: + return f"{format_date(date_from)} — {format_date(date_to)}" + return "" + + +def project_requisite_lines( + project_name: str = "", + customer: str = "", + contract_number: str = "", + contract_date: date | None = None, + currency: str = "", + period_text: str = "", + extra: list[tuple[str, str]] | None = None, +) -> list[tuple[str, str]]: + """Unified header block: project, customer, contract, currency, period, extras.""" + lines: list[tuple[str, str]] = [] + if project_name: + lines.append(("Проект:", project_name)) + if customer: + lines.append(("Заказчик:", customer)) + if contract_number: + lines.append(("Договор:", contract_number)) + if contract_date: + lines.append(("Дата договора:", format_date(contract_date))) + if currency: + lines.append(("Валюта:", currency)) + if period_text: + lines.append(("Период:", period_text)) + for label, value in extra or []: + if value: + lines.append((label, value)) + return lines diff --git a/app/exporters/excel/ks2_renderer.py b/app/exporters/excel/ks2_renderer.py index fd23b6d..f933a64 100644 --- a/app/exporters/excel/ks2_renderer.py +++ b/app/exporters/excel/ks2_renderer.py @@ -1,19 +1,24 @@ """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.common import ( + MONEY_FMT, + MONEY_TEXT, + QTY_FMT, + QTY_TEXT, + format_period, + project_requisite_lines, +) 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: @@ -23,28 +28,28 @@ def render_ks2_excel(doc: KS2ExportDocument) -> bytes: h = doc.header row = 1 + col_count = 7 # Title - ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=7) + ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count) 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)) - + # Unified project requisites + 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: 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.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count) ws.cell(row=row, column=2, value=value) row += 1 @@ -100,6 +105,8 @@ def render_ks2_excel(doc: KS2ExportDocument) -> bytes: for col, width in widths.items(): ws.column_dimensions[get_column_letter(col)].width = width + ws.freeze_panes = ws.cell(row=header_row + 1, column=1) + buf = io.BytesIO() wb.save(buf) buf.seek(0) diff --git a/app/exporters/excel/ks3_renderer.py b/app/exporters/excel/ks3_renderer.py index 19d5eea..7c4e197 100644 --- a/app/exporters/excel/ks3_renderer.py +++ b/app/exporters/excel/ks3_renderer.py @@ -5,13 +5,18 @@ from openpyxl import Workbook from openpyxl.styles import Alignment, Border, Font, Side from openpyxl.utils import get_column_letter +from app.exporters.common import ( + MONEY_FMT, + format_date, + format_period, + project_requisite_lines, +) 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: @@ -21,28 +26,27 @@ def render_ks3_excel(doc: KS3ExportDocument) -> bytes: h = doc.header row = 1 + col_count = 5 # 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')}") + ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count) + 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)) - + 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: 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.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count) ws.cell(row=row, column=2, value=value) row += 1 @@ -55,6 +59,7 @@ def render_ks3_excel(doc: KS3ExportDocument) -> bytes: c.font = HEADER_FONT c.border = BORDER c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True) + header_row = row row += 1 # Items @@ -62,14 +67,12 @@ def render_ks3_excel(doc: KS3ExportDocument) -> bytes: 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 = ws.cell(row=row, column=3, value=format_date(item.ks2_date)) 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 = ws.cell(row=row, column=4, value=format_period(item.period_from, item.period_to)) c.border = BORDER + c.alignment = Alignment(wrap_text=True, vertical="top") c = ws.cell(row=row, column=5, value=float(item.amount)) c.border = BORDER @@ -94,6 +97,8 @@ def render_ks3_excel(doc: KS3ExportDocument) -> bytes: for col, width in widths.items(): ws.column_dimensions[get_column_letter(col)].width = width + ws.freeze_panes = ws.cell(row=header_row + 1, column=1) + buf = io.BytesIO() wb.save(buf) buf.seek(0) diff --git a/app/exporters/excel/ks6a_renderer.py b/app/exporters/excel/ks6a_renderer.py index f3bcbf2..30f084b 100644 --- a/app/exporters/excel/ks6a_renderer.py +++ b/app/exporters/excel/ks6a_renderer.py @@ -5,13 +5,18 @@ from openpyxl import Workbook from openpyxl.styles import Alignment, Border, Font, Side from openpyxl.utils import get_column_letter +from app.exporters.common import ( + QTY_FMT, + format_date, + format_period, + project_requisite_lines, +) 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: @@ -21,32 +26,33 @@ def render_ks6a_excel(doc: KS6aExportDocument) -> bytes: h = doc.header row = 1 + col_count = 8 # Title - ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=8) + ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=col_count) 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), - ] + extra = [] 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')}", - )) + extra.append(("Подрядчик:", h.contractor)) if h.system_name: - header_lines.append(("Система:", h.system_name)) + extra.append(("Система:", h.system_name)) + 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=extra, + ) 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.merge_cells(start_row=row, start_column=2, end_row=row, end_column=col_count) ws.cell(row=row, column=2, value=value) row += 1 @@ -69,7 +75,7 @@ def render_ks6a_excel(doc: KS6aExportDocument) -> bytes: 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 = ws.cell(row=row, column=2, value=format_date(item.report_date)) c.border = BORDER c = ws.cell(row=row, column=3, value=item.system_name) @@ -98,7 +104,6 @@ def render_ks6a_excel(doc: KS6aExportDocument) -> bytes: 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() diff --git a/app/exporters/ks2_dto.py b/app/exporters/ks2_dto.py index 2da705f..d6615df 100644 --- a/app/exporters/ks2_dto.py +++ b/app/exporters/ks2_dto.py @@ -20,6 +20,8 @@ class KS2ExportHeader: project_name: str customer: str contract_number: str + contract_date: date | None + currency: str ks2_number: str ks2_date: date period_from: date | None @@ -59,6 +61,8 @@ def build_ks2_export_dto(db, ks2_document) -> KS2ExportDocument: 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 "", + contract_date=project.contract_date if project else None, + currency=project.currency if project and project.currency else "", ks2_number=ks2_document.number, ks2_date=ks2_document.date, period_from=ks2_document.reporting_period_from, diff --git a/app/exporters/ks3_dto.py b/app/exporters/ks3_dto.py index d40e653..16ab48c 100644 --- a/app/exporters/ks3_dto.py +++ b/app/exporters/ks3_dto.py @@ -19,6 +19,8 @@ class KS3ExportHeader: project_name: str customer: str contract_number: str + contract_date: date | None + currency: str ks3_number: str ks3_date: date period_from: date | None @@ -59,6 +61,8 @@ def build_ks3_export_dto(db, ks3_document) -> KS3ExportDocument: 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 "", + contract_date=project.contract_date if project else None, + currency=project.currency if project and project.currency else "", ks3_number=ks3_document.number, ks3_date=ks3_document.date, period_from=ks3_document.reporting_period_from, diff --git a/app/exporters/ks6a_dto.py b/app/exporters/ks6a_dto.py index 5c02297..cf17c57 100644 --- a/app/exporters/ks6a_dto.py +++ b/app/exporters/ks6a_dto.py @@ -26,6 +26,8 @@ class KS6aExportHeader: customer: str contractor: str contract_number: str + contract_date: date | None + currency: str period_from: date period_to: date system_name: str @@ -90,6 +92,8 @@ def build_ks6a_export_dto(project, rows, date_from: date, date_to: date, system_ customer=project.customer if project and project.customer else "", contractor="", contract_number=project.contract_number if project and project.contract_number else "", + contract_date=project.contract_date if project else None, + currency=project.currency if project and project.currency else "", period_from=date_from, period_to=date_to, system_name=system_name or "", diff --git a/app/exporters/word/ks2_renderer.py b/app/exporters/word/ks2_renderer.py index 7491613..e1da3fb 100644 --- a/app/exporters/word/ks2_renderer.py +++ b/app/exporters/word/ks2_renderer.py @@ -2,10 +2,12 @@ import io from docx import Document -from docx.shared import Pt, Cm -from docx.enum.text import WD_ALIGN_PARAGRAPH +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.common import MONEY_TEXT, QTY_TEXT, format_period, project_requisite_lines from app.exporters.ks2_dto import KS2ExportDocument @@ -13,6 +15,10 @@ def render_ks2_word(doc: KS2ExportDocument) -> 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 @@ -22,17 +28,15 @@ def render_ks2_word(doc: KS2ExportDocument) -> bytes: 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)) - + 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 + " ") @@ -61,9 +65,9 @@ def render_ks2_word(doc: KS2ExportDocument) -> bytes: 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}" + 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) # Total row total_row = table.add_row() @@ -73,7 +77,7 @@ def render_ks2_word(doc: KS2ExportDocument) -> bytes: paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT for run in paragraph.runs: run.bold = True - total_row.cells[6].text = f"{doc.total:.2f}" + 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 diff --git a/app/exporters/word/ks3_renderer.py b/app/exporters/word/ks3_renderer.py index b14bcc4..d213cba 100644 --- a/app/exporters/word/ks3_renderer.py +++ b/app/exporters/word/ks3_renderer.py @@ -2,10 +2,12 @@ import io from docx import Document -from docx.shared import Pt -from docx.enum.text import WD_ALIGN_PARAGRAPH +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.common import MONEY_TEXT, format_date, format_period, project_requisite_lines from app.exporters.ks3_dto import KS3ExportDocument @@ -13,26 +15,28 @@ 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 = 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)) - + 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 + " ") @@ -59,12 +63,9 @@ def render_ks3_word(doc: KS3ExportDocument) -> bytes: 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}" + 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() @@ -74,7 +75,7 @@ def render_ks3_word(doc: KS3ExportDocument) -> bytes: paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT for run in paragraph.runs: run.bold = True - total_row.cells[4].text = f"{doc.total:.2f}" + 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 diff --git a/app/exporters/word/ks6a_renderer.py b/app/exporters/word/ks6a_renderer.py index a49e10d..13c0c1b 100644 --- a/app/exporters/word/ks6a_renderer.py +++ b/app/exporters/word/ks6a_renderer.py @@ -7,6 +7,7 @@ from docx.enum.table import WD_TABLE_ALIGNMENT from docx.enum.text import WD_ALIGN_PARAGRAPH from docx.shared import Pt +from app.exporters.common import QTY_TEXT, format_date, format_period, project_requisite_lines from app.exporters.ks6a_dto import KS6aExportDocument @@ -28,21 +29,21 @@ def render_ks6a_word(doc: KS6aExportDocument) -> bytes: d.add_paragraph() - # Header block - header_lines = [ - ("Проект:", h.project_name), - ("Заказчик:", h.customer), - ] + extra = [] 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')}", - )) + extra.append(("Подрядчик:", h.contractor)) if h.system_name: - header_lines.append(("Система:", h.system_name)) + extra.append(("Система:", h.system_name)) + 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=extra, + ) for label, value in header_lines: p = d.add_paragraph() run = p.add_run(label + " ") @@ -71,13 +72,13 @@ def render_ks6a_word(doc: KS6aExportDocument) -> bytes: 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[1].text = format_date(item.report_date) 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}" + row.cells[7].text = QTY_TEXT.format(item.quantity) buf = io.BytesIO() d.save(buf) diff --git a/app/routers/ks2.py b/app/routers/ks2.py index cf49d3a..67ba4c0 100644 --- a/app/routers/ks2.py +++ b/app/routers/ks2.py @@ -164,11 +164,6 @@ async def ks2_cancel(project_id: int, ks2_id: int, db: Session = Depends(get_db) return RedirectResponse(f"/projects/{project_id}/ks2/{ks2_id}", status_code=303) -def _safe_filename(number: str, dt) -> str: - from app.exporters import safe_export_filename - return safe_export_filename("КС-2", number, dt, "xlsx") - - def _content_disposition(filename: str) -> str: from app.exporters import content_disposition return content_disposition(filename) @@ -177,11 +172,12 @@ def _content_disposition(filename: str) -> str: @router.get("/{project_id}/ks2/{ks2_id}/export/excel") async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(get_db)): document = _document(db, project_id, ks2_id) + from app.exporters import safe_export_filename from app.exporters.ks2_dto import build_ks2_export_dto from app.exporters.excel.ks2_renderer import render_ks2_excel dto = build_ks2_export_dto(db, document) data = render_ks2_excel(dto) - filename = _safe_filename(document.number, document.date) + ".xlsx" + filename = safe_export_filename("КС-2", document.number, document.date, "xlsx") return Response( content=data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", @@ -192,11 +188,12 @@ async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(g @router.get("/{project_id}/ks2/{ks2_id}/export/word") async def ks2_export_word(project_id: int, ks2_id: int, db: Session = Depends(get_db)): document = _document(db, project_id, ks2_id) + from app.exporters import safe_export_filename from app.exporters.ks2_dto import build_ks2_export_dto from app.exporters.word.ks2_renderer import render_ks2_word dto = build_ks2_export_dto(db, document) data = render_ks2_word(dto) - filename = _safe_filename(document.number, document.date) + ".docx" + filename = safe_export_filename("КС-2", document.number, document.date, "docx") return Response( content=data, media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document", diff --git a/docs/implementation/020-export-polish.md b/docs/implementation/020-export-polish.md new file mode 100644 index 0000000..2d14b5b --- /dev/null +++ b/docs/implementation/020-export-polish.md @@ -0,0 +1,123 @@ +# Implementation Report — Task 020 + +### Status + +DONE + +### What was done + +Экспорт КС-2 / КС-3 / КС-6а приведён к единому V1-оформлению. Исправлены имена файлов, +добавлены реквизиты договора/валюты, унифицированы форматы чисел и дат. + +Архитектура `DB → DTO → renderer` сохранена. Индивидуальные экспорты и комплект 019 продолжают работать. + +--- + +### Что изменено + +#### 1. Единообразие оформления + +Новый модуль `app/exporters/common.py`: + +- `format_date()`, `format_period()` — даты `дд.мм.гггг`, период `дд.мм.гггг — дд.мм.гггг` +- `MONEY_FMT` / `MONEY_TEXT` — `#,##0.00` / `{:.2f}` +- `QTY_FMT` / `QTY_TEXT` — `#,##0.00` / `{:.2f}` +- `project_requisite_lines()` — единый блок реквизитов + +Все шесть рендереров используют общие helpers. + +Типовая шапка: + +``` +Проект: ... +Заказчик: ... +Договор: ... +Дата договора: ... +Валюта: ... +Период: ... +[Система / Подрядчик / Комментарий] +``` + +Заголовки: +- КС-2: `Акт КС-2 №N от дд.мм.гггг` +- КС-3: `Акт КС-3 №N от дд.мм.гггг` +- КС-6а: `КС-6а — Журнал учёта выполненных работ` + +Одинаково: Excel freeze panes, перенос длинных наименований, Word landscape, Table Grid, итог. + +#### 2. Реквизиты Project + +В DTO добавлены `contract_date`, `currency` (из существующей модели Project). +Поле «подрядчик» в модели отсутствует — не добавлялось. +Пустые значения не выводятся. + +#### 3. КС-2 + +Сохранена структура `№ → Наименование → № позиции → Ед. → Количество → Цена → Стоимость`. +Количество/цена/сумма — числовые ячейки, единый формат 2 знака. Итоговая строка на месте. + +#### 4. КС-3 + +Сохранена модель «финансовый свод выбранных КС-2». Таблица `№ | КС-2 | Дата | Период | Сумма`, итог. + +#### 5. КС-6а + +Сохранено правило «одна строка = один DailyReportItem», без агрегации и без финансов. + +#### 6. Имена файлов + +Исправлен follow-up `_safe_filename()` КС-2: было `.xlsx.xlsx` / `.xlsx.docx`. +Теперь `safe_export_filename("КС-2", number, date, ext)` без двойного расширения. +КС-3 — без изменений. КС-6а — имя по периоду. Комплект 019 — прежняя структура. + +#### 7. Privacy + +Экспорт содержит фактические суммы независимо от eye icon (покрыто тестом). + +#### 8. Комплект 019 + +`package_service` использует обновлённые DTO/renderers без изменений логики отбора. + +--- + +### Changed files + +**Новые:** +- `app/exporters/common.py` +- `tests/test_task020_export_polish.py` + +**Изменённые:** +- `app/exporters/ks2_dto.py`, `ks3_dto.py`, `ks6a_dto.py` — `contract_date`, `currency` +- `app/exporters/excel/ks2_renderer.py`, `ks3_renderer.py`, `ks6a_renderer.py` +- `app/exporters/word/ks2_renderer.py`, `ks3_renderer.py`, `ks6a_renderer.py` +- `app/routers/ks2.py` — фикс имени файла + +### Tests + +`tests/test_task020_export_polish.py` — 10 тестов: + +1. КС-2 Excel: ключевые значения (номер, реквизиты, период, суммы, итог) +2. КС-2 Word: ключевые значения +3. КС-3 Excel/Word: реквизиты, включённый КС-2, итог +4. КС-6а Excel/Word: реквизиты, наименование, количество +5. нет двойных расширений (все 6 endpoints) +6. имена КС-2 сохраняют тип/номер/дату +7. количество — числовая ячейка +8. privacy не влияет на суммы +9. комплект 019 работает, ZIP-файлы открываются +10. длинное наименование с переносом в Excel + +Результат: `167 passed, 0 failed` +`git diff --check`: чисто + +Существующее покрытие не снижено (016/017/018/019 проходят). + +### Deviations + +None. + +### Follow-up / Open Questions + +- Поля «подрядчик» нет в модели Project — добавить отдельной задачей при необходимости. +- Количества в КС-2 теперь 2 знака (было 4) — унификация; при необходимости точности — вернуть отдельным форматом. +- Официальная типографская форма, PDF, email — вне scope. diff --git a/docs/tasks/020-export-polish(1).md b/docs/tasks/020-export-polish(1).md new file mode 100644 index 0000000..48a7b11 --- /dev/null +++ b/docs/tasks/020-export-polish(1).md @@ -0,0 +1,250 @@ +# Task 020 — Доведение экспорта документов + +## Цель + +Довести экспорт КС-2, КС-3 и КС-6а до рабочего V1-уровня, пригодного для передачи заказчику/коллеге и последующей печати из Excel/Word. + +Не переделывать архитектуру экспорта без необходимости. Использовать существующий общий слой: + +`DB → DTO → renderer → Excel/Word` + +Существующие индивидуальные экспорты и экспорт комплекта должны продолжать работать. + +## Контекст + +Уже реализовано: + +- КС-2 → Excel / Word; +- КС-3 → Excel / Word; +- КС-6а → Excel / Word; +- комплект за период → ZIP; +- все тесты на текущем checkpoint проходят. + +Экспорт — это именно редактируемый Excel/Word, а не PDF. Пользователь должен иметь возможность открыть файл, при необходимости поправить его и распечатать/отправить по почте. + +## Что нужно проверить и довести + +### 1. Единообразие документов + +Привести Excel и Word всех трёх документов к единой логике оформления: + +- название документа; +- номер и дата; +- проект; +- заказчик; +- договор; +- период, где применимо; +- таблица; +- итог; +- единообразное форматирование дат и чисел. + +Не менять бизнес-смысл документов. + +### 2. Реквизиты проекта + +Проверить использование доступных реквизитов Project. + +В экспорт должны попадать доступные и уже существующие в модели данные, прежде всего: + +- проект; +- заказчик; +- договор; +- дата договора; +- валюта; +- период; +- подрядчик, если поле уже реализовано к моменту выполнения задачи; +- прочие реквизиты только если они уже есть в модели и реально используются приложением. + +Не придумывать отсутствующие данные и не добавлять новые обязательные поля в рамках этой задачи без необходимости. + +### 3. КС-2 + +Проверить и привести к рабочему виду: + +- Excel; +- Word. + +Сохранить текущую структуру: + +`№ → Наименование работ → № позиции в ведомости → Ед. изм. → Количество → Цена за ед. → Стоимость` + +Проверить: + +- количество; +- цену; +- стоимость; +- итог; +- номер позиции; +- дату/период; +- длинные наименования; +- ширины колонок; +- перенос текста; +- печатную читаемость; +- редактируемость Word/Excel. + +Не менять логику формирования факта и КС-2. + +### 4. КС-3 + +Проверить и привести к рабочему виду: + +- Excel; +- Word. + +Сохранить текущую модель: КС-3 является финансовым сводом выбранных КС-2 и не пересчитывает объёмы самостоятельно. + +Проверить: + +- список включённых КС-2; +- номер; +- дату; +- период; +- сумму; +- общий итог; +- реквизиты проекта; +- читаемость таблицы. + +### 5. КС-6а + +Проверить и привести к рабочему виду: + +- Excel; +- Word. + +Сохранить правило: + +- одна строка = один DailyReportItem; +- без агрегации; +- без финансовых данных. + +Проверить: + +- дату; +- систему; +- раздел; +- № позиции; +- наименование; +- единицу измерения; +- количество; +- период; +- реквизиты проекта; +- длинные названия; +- читаемость. + +### 6. Финансовая приватность + +Экспорт не должен зависеть от состояния eye icon. + +Как и сейчас, фактические суммы должны присутствовать в экспортируемых финансовых документах независимо от UI-приватности. + +КС-6а финансовых данных не содержит. + +### 7. Имена файлов + +Унифицировать имена экспортируемых файлов, насколько это возможно без поломки существующих ссылок/тестов. + +Для документов желательно сохранять: + +- тип документа; +- номер; +- дату. + +Для комплекта сохранить текущую структуру и русские имена. + +Не допускать двойных расширений вроде `.xlsx.xlsx`. + +Проверить известный follow-up `_safe_filename()` КС-2. + +### 8. Комплект документов + +Проверить, что Task 019 продолжает корректно использовать существующие exporters. + +Комплект: + +- не должен дублировать renderer-код; +- должен включать только реально выбранные типы/форматы; +- должен исключать draft и сторнированные документы; +- должен сохранять номера документов; +- должен корректно открываться после распаковки. + +Не добавлять PDF/email в эту задачу. + +### 9. Тесты + +Добавить/обновить регрессионные тесты там, где это действительно необходимо. + +Минимум проверить: + +- все три индивидуальных экспорта; +- Excel открывается через openpyxl; +- Word открывается через python-docx; +- корректные ключевые значения; +- отсутствие двойных расширений; +- privacy не влияет на содержимое экспорта; +- комплект 019 продолжает работать. + +Не снижать существующее покрытие. + +### 10. Ручная проверка + +После реализации проверить хотя бы по одному реальному документу: + +- КС-2; +- КС-3; +- КС-6а; +- ZIP-комплект. + +Особое внимание: + +- длинным названиям; +- ширинам колонок; +- переносам; +- итоговым строкам; +- русским именам файлов; +- открытию в Excel/Word. + +## Что НЕ входит + +Не делать в рамках задачи: + +- PDF; +- отправку email; +- автоматическую отправку; +- автонумерацию КС; +- полноценное сторнирование; +- исторические snapshot-реквизиты документов; +- новый конструктор форм; +- изменение бизнес-логики КС-2/КС-3/КС-6а; +- платежный контур. + +Это отдельные задачи/техдолг. + +## Git + +Перед началом: + +- проверить `git status`; +- не смешивать изменения с посторонними незакоммиченными задачами. + +После реализации: + +- `python -m pytest -q`; +- `git diff --check`; +- проверить `git status`. + +Коммит и push — только по отдельной команде пользователя. + +## Отчёт + +Создать: + +`docs/implementation/020-export-polish.md` + +В отчёте указать: + +- что изменено; +- какие exporters/DTO затронуты; +- какие тесты добавлены/изменены; +- результаты pytest; +- результаты `git diff --check`; +- известные ограничения. diff --git a/tests/test_task020_export_polish.py b/tests/test_task020_export_polish.py new file mode 100644 index 0000000..14fd706 --- /dev/null +++ b/tests/test_task020_export_polish.py @@ -0,0 +1,356 @@ +"""Regression tests for task 020: export polish (requisites, filenames, formats).""" +import datetime +import io +import shutil +from decimal import Decimal +from urllib.parse import unquote + +from fastapi.testclient import TestClient +from openpyxl import load_workbook +from docx import Document +from sqlalchemy import create_engine +from sqlalchemy.orm import sessionmaker + +from app.database.database import Base, DATABASE_PATH +from app.main import app +from app.models.project import Project +from app.models.boq import BoqDocument, WorkItem +from app.models.daily_report import DailyReport, DailyReportItem +from app.models.ks2 import KS2, KS2Item +from app.models.ks3 import KS3, KS3KS2 +from app.routers import projects, ks2 as ks2_router, ks3 as ks3_router, ks6a as ks6a_router + + +def _make_session(tmp_path): + db_path = tmp_path / "t020-copy.db" + shutil.copy2(DATABASE_PATH, db_path) + engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False}) + Base.metadata.create_all(bind=engine) + return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False) + + +def _override(Session): + def override_db(): + s = Session() + try: + yield s + finally: + s.close() + for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db): + app.dependency_overrides[dep] = override_db + + +def _clear(): + for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db, ks6a_router.get_db): + app.dependency_overrides.pop(dep, None) + + +def _create_export_data(Session): + with Session() as s: + p = Project( + name="Export polish", + customer="Заказчик ООО", + contract_number="DOG-2026-7", + contract_date=datetime.date(2026, 1, 15), + currency="RUB", + ) + s.add(p) + s.flush() + + boq = BoqDocument(project_id=p.id, name="BOQ") + s.add(boq) + s.flush() + + wi = WorkItem( + project_id=p.id, boq_document_id=boq.id, + name="Монтаж трубопровода системы отопления с изоляцией и креплениями", + source_number="1.1", unit="м", + quantity=Decimal("100"), unit_price=Decimal("50"), amount=Decimal("5000"), + ) + s.add(wi) + s.flush() + + dr = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 10)) + s.add(dr) + s.flush() + s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10"))) + s.flush() + + ks2 = KS2( + project_id=p.id, number="7", date=datetime.date(2026, 3, 20), + status="issued", + reporting_period_from=datetime.date(2026, 3, 1), + reporting_period_to=datetime.date(2026, 3, 31), + comment="Проверка экспорта", + ) + s.add(ks2) + s.flush() + s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id, + quantity=Decimal("10"), unit_price=Decimal("50"), amount=Decimal("500"))) + s.flush() + + ks3 = KS3( + project_id=p.id, number="3", date=datetime.date(2026, 3, 25), + status="issued", + reporting_period_from=datetime.date(2026, 3, 1), + reporting_period_to=datetime.date(2026, 3, 31), + ) + s.add(ks3) + s.flush() + s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id)) + s.commit() + return {"pid": p.id, "ks2_id": ks2.id, "ks3_id": ks3.id} + + +PERIOD = "date_from=2026-03-01&date_to=2026-03-31" + + +def _filename_from_disposition(disposition: str) -> str: + from urllib.parse import unquote + marker = "filename*=UTF-8''" + if marker in disposition: + return unquote(disposition.split(marker, 1)[1].strip()) + return disposition + + +def _excel_text(resp): + wb = load_workbook(io.BytesIO(resp.content)) + ws = wb.active + text = "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value is not None) + return wb, ws, text + + +def _word_text(resp): + d = Document(io.BytesIO(resp.content)) + text = "\n".join(p.text for p in d.paragraphs) + for table in d.tables: + for row in table.rows: + text += "\n" + " | ".join(c.text for c in row.cells) + return d, text + + +def test_ks2_excel_export_key_values(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel") + assert resp.status_code == 200 + _, _, text = _excel_text(resp) + assert "Акт КС-2 №7" in text + assert "Export polish" in text + assert "Заказчик ООО" in text + assert "DOG-2026-7" in text + assert "15.01.2026" in text + assert "RUB" in text + assert "01.03.2026 — 31.03.2026" in text + assert "Монтаж трубопровода" in text + assert "500" in text + assert "Итого:" in text + finally: + _clear() + engine.dispose() + + +def test_ks2_word_export_key_values(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word") + assert resp.status_code == 200 + _, text = _word_text(resp) + assert "Акт КС-2 №7" in text + assert "DOG-2026-7" in text + assert "15.01.2026" in text + assert "RUB" in text + assert "Итого:" in text + assert "500.00" in text + finally: + _clear() + engine.dispose() + + +def test_ks3_export_key_values(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + excel = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/excel") + assert excel.status_code == 200 + _, _, text = _excel_text(excel) + assert "Акт КС-3 №3" in text + assert "DOG-2026-7" in text + assert "RUB" in text + assert "№7" in text + assert "Итого:" in text + + word = client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word") + assert word.status_code == 200 + _, wtext = _word_text(word) + assert "Акт КС-3 №3" in wtext + assert "500.00" in wtext + finally: + _clear() + engine.dispose() + + +def test_ks6a_export_key_values(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}") + assert excel.status_code == 200 + _, _, text = _excel_text(excel) + assert "КС-6а" in text + assert "Export polish" in text + assert "DOG-2026-7" in text + assert "15.01.2026" in text + assert "RUB" in text + assert "Монтаж трубопровода" in text + assert "10.00" in text or "10" in text + + word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}") + assert word.status_code == 200 + _, wtext = _word_text(word) + assert "КС-6а" in wtext + assert "DOG-2026-7" in wtext + finally: + _clear() + engine.dispose() + + +def test_no_double_extension_in_filenames(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + checks = [ + client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel"), + client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word"), + client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/excel"), + client.get(f"/projects/{data['pid']}/ks3/{data['ks3_id']}/export/word"), + client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}"), + client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}"), + ] + for resp in checks: + assert resp.status_code == 200 + filename = _filename_from_disposition(resp.headers["content-disposition"]) + assert not filename.endswith(".xlsx.xlsx") + assert not filename.endswith(".docx.docx") + assert not filename.endswith(".xlsx.docx") + assert not filename.endswith(".docx.xlsx") + assert filename.count(".xlsx") <= 1 + assert filename.count(".docx") <= 1 + finally: + _clear() + engine.dispose() + + +def test_ks2_filenames_keep_type_number_date(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + excel = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel") + name = _filename_from_disposition(excel.headers["content-disposition"]) + assert "КС-2" in name + assert "7" in name + assert "20.03.2026" in name + assert name.endswith(".xlsx") + + word = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/word") + wname = _filename_from_disposition(word.headers["content-disposition"]) + assert wname.endswith(".docx") + assert "КС-2" in wname + finally: + _clear() + engine.dispose() + + +def test_excel_quantity_is_numeric(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel") + _, ws, _ = _excel_text(resp) + found_qty = False + for row in ws.iter_rows(): + for cell in row: + if isinstance(cell.value, (int, float)) and float(cell.value) == 10.0: + found_qty = True + assert found_qty + finally: + _clear() + engine.dispose() + + +def test_export_money_regardless_of_privacy(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel") + _, _, text = _excel_text(resp) + assert "500" in text # amount present without eye icon + finally: + _clear() + engine.dispose() + + +def test_package_still_works_after_polish(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + import zipfile + with TestClient(app) as client: + resp = client.get( + f"/projects/{data['pid']}/export/package?{PERIOD}" + f"&include=ks6a&include=ks2&include=ks3&format=both" + ) + assert resp.status_code == 200 + assert "application/zip" in resp.headers["content-type"] + with zipfile.ZipFile(io.BytesIO(resp.content)) as zf: + names = zf.namelist() + assert any(n.startswith("КС-2/") for n in names) + assert any(n.startswith("КС-3/") for n in names) + assert any(n.startswith("КС-6а/") for n in names) + # Members open correctly + xlsx_name = next(n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx")) + wb = load_workbook(io.BytesIO(zf.read(xlsx_name))) + assert wb.active is not None + docx_name = next(n for n in names if n.startswith("КС-3/") and n.endswith(".docx")) + d = Document(io.BytesIO(zf.read(docx_name))) + assert len(d.tables) > 0 + finally: + _clear() + engine.dispose() + + +def test_long_work_name_wrapped_in_excel(tmp_path): + engine, Session = _make_session(tmp_path) + _override(Session) + try: + data = _create_export_data(Session) + with TestClient(app) as client: + resp = client.get(f"/projects/{data['pid']}/ks2/{data['ks2_id']}/export/excel") + _, ws, text = _excel_text(resp) + assert "Монтаж трубопровода системы отопления" in text + for row in ws.iter_rows(): + for cell in row: + if isinstance(cell.value, str) and cell.value.startswith("Монтаж трубопровода"): + assert cell.alignment.wrap_text is True + finally: + _clear() + engine.dispose()