diff --git a/app/exporters/__init__.py b/app/exporters/__init__.py
index e69de29..05cd25b 100644
--- a/app/exporters/__init__.py
+++ b/app/exporters/__init__.py
@@ -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)}"
diff --git a/app/exporters/excel/ks6a_renderer.py b/app/exporters/excel/ks6a_renderer.py
new file mode 100644
index 0000000..f3bcbf2
--- /dev/null
+++ b/app/exporters/excel/ks6a_renderer.py
@@ -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()
diff --git a/app/exporters/ks6a_dto.py b/app/exporters/ks6a_dto.py
new file mode 100644
index 0000000..5c02297
--- /dev/null
+++ b/app/exporters/ks6a_dto.py
@@ -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)
diff --git a/app/exporters/word/ks6a_renderer.py b/app/exporters/word/ks6a_renderer.py
new file mode 100644
index 0000000..a49e10d
--- /dev/null
+++ b/app/exporters/word/ks6a_renderer.py
@@ -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()
diff --git a/app/routers/ks6a.py b/app/routers/ks6a.py
index ae86332..c58849e 100644
--- a/app/routers/ks6a.py
+++ b/app/routers/ks6a.py
@@ -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,
- })
\ No newline at end of file
+ })
+
+
+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)},
+ )
diff --git a/app/templates/ks6a/journal.html b/app/templates/ks6a/journal.html
index 377a7c5..58cfbc3 100644
--- a/app/templates/ks6a/journal.html
+++ b/app/templates/ks6a/journal.html
@@ -43,12 +43,18 @@
{% endif %}
{% if date_from and date_to and not error %}
-
- Период: {{ 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 }}
+
+
+ Период: {{ 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 }}
+
+
📊 Excel
+
📄 Word
{% if rows %}
diff --git a/docs/implementation/018-ks6a-export.md b/docs/implementation/018-ks6a-export.md
new file mode 100644
index 0000000..dbbf451
--- /dev/null
+++ b/docs/implementation/018-ks6a-export.md
@@ -0,0 +1,148 @@
+# Implementation Report — Task 018
+
+### Status
+
+DONE
+
+### What was done
+
+Реализован экспорт КС-6а в Excel и Word на базе существующего export layer (Task 016/017).
+
+КС-6а остаётся отчётным представлением фактического выполнения из Daily Reports.
+Отдельная таблица фактов не создана. Одна строка экспорта = один DailyReportItem.
+
+---
+
+### DTO
+
+`app/exporters/ks6a_dto.py`:
+
+- `KS6aExportHeader` — project_name, customer, contractor, contract_number, period_from, period_to, system_name
+- `KS6aExportItem` — row_number, report_date, system_name, section_name, source_number, name, unit, quantity
+- `KS6aExportDocument` — header + items
+- `fetch_ks6a_rows()` — общий запрос строк (переиспользуется страницей журнала и экспортом)
+- `build_ks6a_export_dto()` — сборка DTO, read-only
+
+Подрядчик (`contractor`) объявлен в header, но всегда пустой: в модели `Project` нет поля подрядчика.
+Комментарий Daily Report не включён: текущий экран КС-6а его не отображает.
+
+**Не включено:** цена, стоимость, сумма, план, остаток, закрыто по КС-2.
+
+### Источник данных
+
+- DailyReport (дата, проект)
+- DailyReportItem (факт — completed_quantity)
+- WorkItem (наименование, ед., № позиции)
+- System / Section (через WorkItem)
+
+Запрос: join DailyReport + WorkItem, `joinedload` work_item/report, фильтры project + период (+ system),
+сортировка по дате/отчёту/позиции. Без агрегации одинаковых WorkItem из разных Daily Reports.
+
+### Фильтры
+
+Те же, что и на экране КС-6а:
+
+- `date_from`, `date_to` — обязательны для экспорта; `date_to >= date_from`
+- `system_id` — опционально; пусто / `all` = все системы
+
+Ошибки фильтров → HTTP 400.
+
+### Excel renderer
+
+`app/exporters/excel/ks6a_renderer.py` (openpyxl):
+
+- Заголовок «КС-6а — Журнал учёта выполненных работ»
+- Шапка: Проект, Заказчик, (Подрядчик), Договор, Период, (Система)
+- Таблица: № | Дата | Система | Раздел | № позиции | Наименование работ | Ед. изм. | Количество
+- Количество — числовая ячейка, формат `#,##0.00`
+- Границы, перенос текста, ширины колонок, freeze panes на заголовке таблицы
+- Файл остаётся редактируемым .xlsx
+
+### Word renderer
+
+`app/exporters/word/ks6a_renderer.py` (python-docx):
+
+- Заголовок, реквизиты, период
+- Таблица Table Grid (8 колонок), без финансовых значений
+- Landscape orientation для широкой таблицы
+- Редактируемый .docx
+
+### Endpoints
+
+- `GET /projects/{project_id}/ks6a/export/excel?date_from&date_to&system_id`
+- `GET /projects/{project_id}/ks6a/export/word?date_from&date_to&system_id`
+
+Content-Type: `spreadsheetml` / `wordprocessingml`.
+Content-Disposition: `attachment; filename*=UTF-8''...`.
+
+Имя файла: `КС-6а_01.09.2026-30.09.2026.xlsx` / `.docx`.
+Если выбрана система — её название добавляется в имя файла.
+
+### UI
+
+Кнопки `📊 Excel` и `📄 Word` на странице КС-6а (при выбранном периоде),
+с текущими параметрами фильтрации.
+
+### Privacy
+
+КС-6а не содержит финансовых данных, поэтому экспорт работает независимо от eye icon.
+
+### Сторнирование
+
+Логика сторнирования КС-6а не вводилась.
+
+### Переиспользование
+
+- `content_disposition()` — общий helper
+- `safe_export_filename()` — переиспользован через `_clean_export_name()`
+- Добавлен `safe_export_filename_period()` для имён по периоду
+- Паттерн DTO → renderer → Response (как в КС-2/КС-3)
+- `fetch_ks6a_rows()` — единый источник строк для страницы и экспорта
+
+### Changed files
+
+**Новые:**
+- `app/exporters/ks6a_dto.py`
+- `app/exporters/excel/ks6a_renderer.py`
+- `app/exporters/word/ks6a_renderer.py`
+- `tests/test_task018_ks6a_export.py`
+
+**Изменённые:**
+- `app/exporters/__init__.py` — `_clean_export_name()`, `safe_export_filename_period()`
+- `app/routers/ks6a.py` — export endpoints, `_export_filters()`, общий `fetch_ks6a_rows`
+- `app/templates/ks6a/journal.html` — кнопки Excel/Word
+
+### Tests
+
+`tests/test_task018_ks6a_export.py` — 15 тестов:
+
+1. Excel endpoint существует
+2. Word endpoint существует
+3. корректный Content-Type (оба)
+4. filename содержит период
+5. Excel открывается через openpyxl
+6. Word открывается через python-docx
+7. Excel содержит все DailyReportItem периода
+8. Word содержит все DailyReportItem периода
+9. фильтр по системе работает
+10. фильтр по периоду работает
+11. одинаковый WorkItem из разных Daily Reports — отдельные строки
+12. в экспорте нет цены/стоимости
+13. количество экспортируется числом
+14. КС-2 не влияет на строки КС-6а
+15. КС-3 не влияет на строки КС-6а
+
+Результат: `136 passed, 0 failed`
+`git diff --check`: без ошибок пробелов (только штатные LF/CRLF warnings Windows)
+
+### Deviations
+
+None.
+
+### Follow-up / Open Questions
+
+- В `Project` нет поля «подрядчик»; DTO готов к выводу, когда поле появится.
+- Комментарий Daily Report (`notes`) не экспортируется — экран КС-6а его не показывает.
+- Официальная типографская форма КС-6а 1:1 — вне scope (как и PDF/email/ZIP-комплект).
+- В рабочем дереве есть незакоммиченные изменения Task 017 (КС-3 export) — не относятся к этой задаче.
+- У КС-2 `_safe_filename()` добавляет расширение дважды (`.xlsx.xlsx`) — существующее поведение, не трогал.
diff --git a/docs/tasks/018-ks6a-export.md b/docs/tasks/018-ks6a-export.md
new file mode 100644
index 0000000..d64ea64
--- /dev/null
+++ b/docs/tasks/018-ks6a-export.md
@@ -0,0 +1,293 @@
+# Task 018 — Экспорт КС-6а в Excel и Word
+
+## Цель
+
+Закрыть индивидуальный экспорт основных документов проекта:
+
+- КС-2 — уже есть;
+- КС-3 — уже есть;
+- КС-6а — добавить сейчас.
+
+После задачи должен работать экспорт КС-6а в:
+- Excel (.xlsx)
+- Word (.docx)
+
+Использовать существующий export layer и общий принцип:
+
+```text
+Daily Reports
+ ↓
+KS-6a reporting view
+ ↓
+KS6a Export DTO
+ ↓
+Excel renderer / Word renderer
+```
+
+КС-6а остаётся отчётным представлением фактического выполнения. Не создавать отдельную таблицу фактов.
+
+---
+
+# 1. Источник данных
+
+Использовать существующий механизм КС-6а из `app/routers/ks6a.py` / соответствующего service layer.
+
+Источник строк:
+- DailyReport;
+- DailyReportItem;
+- WorkItem;
+- System;
+- Section.
+
+Правило:
+**одна строка КС-6а = один DailyReportItem.**
+
+Не агрегировать одинаковые WorkItem из разных Daily Reports.
+
+КС-2 и КС-3 не должны изменять содержимое КС-6а.
+
+---
+
+# 2. Фильтры
+
+Экспорт должен использовать те же параметры, что и экран КС-6а:
+
+- `date_from`;
+- `date_to`;
+- `system_id` — если выбран конкретный system.
+
+`date_to >= date_from`.
+
+Если фильтр по системе не задан — экспортируются все системы.
+
+Не придумывать новые режимы фильтрации.
+
+---
+
+# 3. DTO
+
+Создать:
+
+`app/exporters/ks6a_dto.py`
+
+DTO должен содержать:
+
+### Header
+
+- проект;
+- заказчик;
+- подрядчик, если доступен;
+- договор;
+- период `date_from — date_to`;
+- выбранная система, если применён фильтр.
+
+### Rows
+
+Для каждой DailyReportItem:
+
+- дата;
+- система;
+- раздел;
+- № позиции в ведомости;
+- наименование работы;
+- единица измерения;
+- количество;
+- комментарий Daily Report, если доступен и уже поддерживается текущим экраном.
+
+### Важно
+
+Не включать:
+- цену;
+- стоимость;
+- сумму;
+- план;
+- остаток;
+- закрыто по КС-2.
+
+КС-6а — журнал фактических объёмов, не финансовый документ.
+
+---
+
+# 4. Excel
+
+Использовать `openpyxl`.
+
+Добавить endpoint:
+
+`GET /projects/{project_id}/ks6a/export/excel`
+
+Кнопка `Excel` на странице КС-6а.
+
+Имя файла примерно:
+
+`КС-6а_01.09.2026-30.09.2026.xlsx`
+
+Если выбран system, можно добавить его название в filename.
+
+Минимальная структура:
+
+```text
+КС-6а — Журнал учёта выполненных работ
+
+Проект: ...
+Заказчик: ...
+Договор: ...
+Период: ...
+
+№ | Дата | Система | Раздел | № позиции | Наименование работ | Ед. изм. | Количество
+---------------------------------------------------------------------------------------
+1 | ... | ... | ... | ... | ... | ... | ...
+2 | ... | ... | ... | ... | ... | ... | ...
+```
+
+Требования:
+- количество — числовая Excel cell;
+- формат количества с двумя знаками;
+- границы таблицы;
+- перенос длинного наименования;
+- разумные ширины колонок;
+- закрепление заголовка таблицы желательно;
+- документ должен оставаться редактируемым.
+
+Не пытаться пока воспроизводить официальную форму КС-6а 1:1.
+
+---
+
+# 5. Word
+
+Использовать `python-docx`.
+
+Добавить endpoint:
+
+`GET /projects/{project_id}/ks6a/export/word`
+
+Кнопка `Word`.
+
+Имя файла:
+
+`КС-6а_01.09.2026-30.09.2026.docx`
+
+Содержит:
+- заголовок;
+- реквизиты;
+- период;
+- таблицу фактических работ;
+- без финансовых значений.
+
+Документ должен быть редактируемым в Word.
+
+Настройка страницы должна учитывать широкую таблицу. Если необходимо — использовать landscape orientation.
+
+Пока не требуется официальная государственная форма.
+
+---
+
+# 6. Privacy
+
+Финансовая приватность не должна влиять на КС-6а, поскольку КС-6а не содержит финансовых данных.
+
+Экспорт должен работать независимо от состояния eye icon.
+
+---
+
+# 7. Сторнированные документы
+
+КС-6а не является документом, который сейчас сторнируется как КС-2/КС-3.
+
+Не вводить новую логику сторнирования КС-6а.
+
+---
+
+# 8. Тесты
+
+Добавить минимум:
+
+1. Excel endpoint существует;
+2. Word endpoint существует;
+3. корректный Content-Type;
+4. filename содержит период;
+5. Excel открывается через openpyxl;
+6. Word открывается через python-docx;
+7. Excel содержит все DailyReportItem в заданном периоде;
+8. Word содержит все DailyReportItem в заданном периоде;
+9. фильтр по системе работает;
+10. фильтр по периоду работает;
+11. одинаковый WorkItem из разных Daily Reports остаётся отдельными строками;
+12. в экспортированных данных нет цены/стоимости;
+13. количество экспортируется числом;
+14. КС-2 не влияет на строки КС-6а;
+15. КС-3 не влияет на строки КС-6а.
+
+Проверить:
+
+```text
+python -m pytest -q
+```
+
+Цель: `0 failed`.
+
+---
+
+# 9. Переиспользование инфраструктуры
+
+Переиспользовать существующие:
+- `safe_export_filename()`;
+- `content_disposition()`;
+- общие export helpers;
+- существующий подход DTO → renderer.
+
+Не дублировать код без необходимости.
+
+---
+
+# 10. Не делать
+
+В этой задаче НЕ делать:
+
+- официальный бланк КС-6а 1:1;
+- PDF;
+- email;
+- автоматическую отправку;
+- комплект документов за период;
+- переделку КС-2/КС-3;
+- косметическое вылизывание уже существующих Excel/Word.
+
+После этой задачи индивидуальный экспорт КС-2/КС-3/КС-6а будет функционально закрыт.
+
+Следующим этапом можно будет сделать:
+**экспорт комплекта документов за период в ZIP**.
+
+---
+
+# 11. Документация
+
+Создать:
+
+`docs/implementation/018-ks6a-export.md`
+
+Указать:
+- DTO;
+- источник данных;
+- фильтры;
+- Excel renderer;
+- Word renderer;
+- endpoints;
+- UI;
+- тесты;
+- ограничения.
+
+---
+
+# 12. Git
+
+Коммит и push НЕ выполнять без отдельной команды пользователя.
+
+Перед завершением:
+
+```text
+python -m pytest -q
+git diff --check
+git status
+```
+
+В конце дать краткий implementation report.
diff --git a/tests/test_task018_ks6a_export.py b/tests/test_task018_ks6a_export.py
new file mode 100644
index 0000000..3a41789
--- /dev/null
+++ b/tests/test_task018_ks6a_export.py
@@ -0,0 +1,425 @@
+"""Regression tests for task 018: KS-6a Excel/Word export."""
+import datetime
+import io
+import shutil
+from decimal import Decimal
+
+from fastapi.testclient import TestClient
+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, Section, System, WorkItem
+from app.models.daily_report import DailyReport, DailyReportItem
+from app.models.ks2 import KS2, KS2Item, KS2ItemSource
+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 / "t018-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_ks6a_data(Session):
+ """Project with 5 DailyReportItems across 2 systems and 3 dates."""
+ with Session() as s:
+ p = Project(name="KS6a export test", customer="Customer LLC", contract_number="DOG-789")
+ s.add(p)
+ s.flush()
+
+ system_a = System(project_id=p.id, name="Система A", sort_order=1)
+ system_b = System(project_id=p.id, name="Система B", sort_order=2)
+ s.add_all([system_a, system_b])
+ s.flush()
+
+ section_a = Section(system_id=system_a.id, name="Раздел A1")
+ s.add(section_a)
+ s.flush()
+
+ doc = BoqDocument(project_id=p.id, name="BOQ")
+ s.add(doc)
+ s.flush()
+
+ wi1 = WorkItem(
+ project_id=p.id, boq_document_id=doc.id,
+ system_id=system_a.id, section_id=section_a.id,
+ source_number="1.1", name="Монтаж трубы", unit="м",
+ quantity=Decimal("100"), unit_price=Decimal("50"), amount=Decimal("5000"),
+ )
+ wi2 = WorkItem(
+ project_id=p.id, boq_document_id=doc.id,
+ system_id=system_b.id,
+ source_number="2.1", name="Укладка кабеля", unit="м",
+ quantity=Decimal("200"), unit_price=Decimal("30"), amount=Decimal("6000"),
+ )
+ s.add_all([wi1, wi2])
+ s.flush()
+
+ dr1 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 1))
+ dr2 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 5))
+ dr3 = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 10))
+ s.add_all([dr1, dr2, dr3])
+ s.flush()
+
+ dri1 = DailyReportItem(daily_report_id=dr1.id, work_item_id=wi1.id, completed_quantity=Decimal("10"))
+ dri2 = DailyReportItem(daily_report_id=dr2.id, work_item_id=wi1.id, completed_quantity=Decimal("15"))
+ dri3 = DailyReportItem(daily_report_id=dr3.id, work_item_id=wi1.id, completed_quantity=Decimal("5"))
+ dri4 = DailyReportItem(daily_report_id=dr1.id, work_item_id=wi2.id, completed_quantity=Decimal("20"))
+ dri5 = DailyReportItem(daily_report_id=dr2.id, work_item_id=wi2.id, completed_quantity=Decimal("30"))
+ s.add_all([dri1, dri2, dri3, dri4, dri5])
+ s.commit()
+ return {
+ "pid": p.id,
+ "sa_id": system_a.id,
+ "sb_id": system_b.id,
+ "wi1_id": wi1.id,
+ "dri1_id": dri1.id,
+ }
+
+
+PERIOD = "date_from=2026-03-01&date_to=2026-03-31"
+
+
+def _excel_text(resp):
+ from openpyxl import load_workbook
+ wb = load_workbook(io.BytesIO(resp.content))
+ ws = wb.active
+ return wb, ws, "\n".join(str(cell.value) for row in ws.iter_rows() for cell in row if cell.value is not None)
+
+
+def _word_text(resp):
+ from docx import Document
+ 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_ks6a_excel_endpoint_exists(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ assert resp.status_code == 200
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_word_endpoint_exists(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ assert resp.status_code == 200
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_export_content_types(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ assert "spreadsheetml" in excel.headers["content-type"]
+ word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ assert "wordprocessingml" in word.headers["content-type"]
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_filename_contains_period(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ disposition = excel.headers["content-disposition"]
+ assert "01.03.2026-31.03.2026" in disposition
+ assert "КС-6а" in disposition or "filename" in disposition
+ word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ assert "01.03.2026-31.03.2026" in word.headers["content-disposition"]
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_excel_opens_with_openpyxl(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ from openpyxl import load_workbook
+ wb = load_workbook(io.BytesIO(resp.content))
+ assert wb.active is not None
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_word_opens_with_python_docx(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ from docx import Document
+ d = Document(io.BytesIO(resp.content))
+ assert len(d.tables) > 0
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_excel_contains_all_daily_report_items(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ _, _, text = _excel_text(resp)
+ assert text.count("Монтаж трубы") == 3
+ assert text.count("Укладка кабеля") == 2
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_word_contains_all_daily_report_items(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ _, text = _word_text(resp)
+ assert text.count("Монтаж трубы") == 3
+ assert text.count("Укладка кабеля") == 2
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_export_system_filter(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(
+ f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}&system_id={data['sa_id']}"
+ )
+ assert resp.status_code == 200
+ _, _, text = _excel_text(resp)
+ assert "Монтаж трубы" in text
+ assert "Укладка кабеля" not in text
+ assert "Система A" in text
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_export_period_filter(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(
+ f"/projects/{data['pid']}/ks6a/export/excel?date_from=2026-03-01&date_to=2026-03-03"
+ )
+ assert resp.status_code == 200
+ _, _, text = _excel_text(resp)
+ # Only dr1 (01.03): dri1 + dri4
+ assert text.count("Монтаж трубы") == 1
+ assert text.count("Укладка кабеля") == 1
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_same_work_item_stays_as_separate_rows(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(
+ f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}&system_id={data['sa_id']}"
+ )
+ wb, ws, _ = _excel_text(resp)
+ # Collect dates and quantities of "Монтаж трубы" rows
+ rows = []
+ for row in ws.iter_rows():
+ values = [cell.value for cell in row]
+ if "Монтаж трубы" in values:
+ rows.append(values)
+ assert len(rows) == 3
+ dates = {r[1] for r in rows}
+ assert dates == {"01.03.2026", "05.03.2026", "10.03.2026"}
+ quantities = {float(r[7]) for r in rows}
+ assert quantities == {10.0, 15.0, 5.0}
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_export_has_no_price_or_amount(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ excel = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ _, _, excel_text = _excel_text(excel)
+ for banned in ("Цена", "Стоимость", "Сумма", "unit_price", "amount"):
+ assert banned not in excel_text
+ # Money values from WorkItem must not appear
+ assert "5000" not in excel_text
+ assert "6000" not in excel_text
+
+ word = client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}")
+ _, word_text = _word_text(word)
+ for banned in ("Цена", "Стоимость", "Сумма"):
+ assert banned not in word_text
+ assert "5000" not in word_text
+ assert "6000" not in word_text
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_quantity_exported_as_number(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ _, ws, _ = _excel_text(resp)
+ numeric_quantities = []
+ for row in ws.iter_rows():
+ values = [cell.value for cell in row]
+ if "Монтаж трубы" in values or "Укладка кабеля" in values:
+ qty_cell = row[7]
+ assert isinstance(qty_cell.value, (int, float))
+ assert not isinstance(qty_cell.value, str)
+ numeric_quantities.append(float(qty_cell.value))
+ assert sorted(numeric_quantities) == [5.0, 10.0, 15.0, 20.0, 30.0]
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_rows_unaffected_by_ks2(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with Session() as s:
+ ks2 = KS2(
+ project_id=data["pid"], number="KS-001", status="issued",
+ date=datetime.date(2026, 3, 15),
+ reporting_period_from=datetime.date(2026, 3, 1),
+ reporting_period_to=datetime.date(2026, 3, 31),
+ )
+ s.add(ks2)
+ s.flush()
+ item = KS2Item(
+ ks2_id=ks2.id, work_item_id=data["wi1_id"],
+ quantity=Decimal("999"), unit_price=Decimal("50"), amount=Decimal("49950"),
+ )
+ s.add(item)
+ s.flush()
+ s.add(KS2ItemSource(
+ ks2_item_id=item.id,
+ daily_report_item_id=data["dri1_id"],
+ quantity=Decimal("10"),
+ ))
+ s.commit()
+
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ _, _, text = _excel_text(resp)
+ assert text.count("Монтаж трубы") == 3
+ assert text.count("Укладка кабеля") == 2
+ # Quantity is still the DailyReportItem fact, not the KS-2 amount
+ assert "999" not in text
+ assert "49950" not in text
+ finally:
+ _clear()
+ engine.dispose()
+
+
+def test_ks6a_rows_unaffected_by_ks3(tmp_path):
+ engine, Session = _make_session(tmp_path)
+ _override(Session)
+ try:
+ data = _create_ks6a_data(Session)
+ with Session() as s:
+ ks2 = KS2(
+ project_id=data["pid"], number="KS-100", status="issued",
+ date=datetime.date(2026, 3, 20),
+ )
+ s.add(ks2)
+ s.flush()
+ s.add(KS2Item(
+ ks2_id=ks2.id, work_item_id=data["wi1_id"],
+ quantity=Decimal("1"), unit_price=Decimal("50"), amount=Decimal("50"),
+ ))
+ ks3 = KS3(
+ project_id=data["pid"], number="KS3-1", status="issued",
+ date=datetime.date(2026, 3, 25),
+ )
+ s.add(ks3)
+ s.flush()
+ s.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
+ s.commit()
+
+ with TestClient(app) as client:
+ resp = client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}")
+ _, _, text = _excel_text(resp)
+ assert text.count("Монтаж трубы") == 3
+ assert text.count("Укладка кабеля") == 2
+ # KS-3 identifiers/amounts must not alter KS-6a rows
+ assert "KS3-1" not in text
+ finally:
+ _clear()
+ engine.dispose()