feat: add KS-3 Excel/Word export
This commit is contained in:
@@ -0,0 +1,100 @@
|
||||
"""Excel renderer for KS-3 export using openpyxl."""
|
||||
import io
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from app.exporters.ks3_dto import KS3ExportDocument
|
||||
|
||||
THIN = Side(style="thin")
|
||||
BORDER = Border(left=THIN, right=THIN, top=THIN, bottom=THIN)
|
||||
HEADER_FONT = Font(bold=True, size=11)
|
||||
TITLE_FONT = Font(bold=True, size=14)
|
||||
MONEY_FMT = '#,##0.00'
|
||||
|
||||
|
||||
def render_ks3_excel(doc: KS3ExportDocument) -> bytes:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "КС-3"
|
||||
|
||||
h = doc.header
|
||||
row = 1
|
||||
|
||||
# Title
|
||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=5)
|
||||
c = ws.cell(row=row, column=1, value=f"КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
|
||||
c.font = TITLE_FONT
|
||||
c.alignment = Alignment(horizontal="center")
|
||||
row += 1
|
||||
|
||||
# Header block
|
||||
header_lines = [
|
||||
("Проект:", h.project_name),
|
||||
("Заказчик:", h.customer),
|
||||
("Договор:", h.contract_number),
|
||||
]
|
||||
if h.period_from and h.period_to:
|
||||
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
|
||||
if h.comment:
|
||||
header_lines.append(("Комментарий:", h.comment))
|
||||
|
||||
for label, value in header_lines:
|
||||
ws.cell(row=row, column=1, value=label).font = HEADER_FONT
|
||||
ws.merge_cells(start_row=row, start_column=2, end_row=row, end_column=5)
|
||||
ws.cell(row=row, column=2, value=value)
|
||||
row += 1
|
||||
|
||||
row += 1 # blank row
|
||||
|
||||
# Table header
|
||||
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
|
||||
for col_idx, col_name in enumerate(columns, start=1):
|
||||
c = ws.cell(row=row, column=col_idx, value=col_name)
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
row += 1
|
||||
|
||||
# Items
|
||||
for item in doc.items:
|
||||
ws.cell(row=row, column=1, value=item.row_number).border = BORDER
|
||||
ws.cell(row=row, column=2, value=f"№{item.ks2_number}").border = BORDER
|
||||
|
||||
c = ws.cell(row=row, column=3, value=item.ks2_date.strftime('%d.%m.%Y') if item.ks2_date else "")
|
||||
c.border = BORDER
|
||||
|
||||
period_text = ""
|
||||
if item.period_from and item.period_to:
|
||||
period_text = f"{item.period_from.strftime('%d.%m.%Y')} — {item.period_to.strftime('%d.%m.%Y')}"
|
||||
c = ws.cell(row=row, column=4, value=period_text)
|
||||
c.border = BORDER
|
||||
|
||||
c = ws.cell(row=row, column=5, value=float(item.amount))
|
||||
c.border = BORDER
|
||||
c.number_format = MONEY_FMT
|
||||
row += 1
|
||||
|
||||
# Total row
|
||||
ws.merge_cells(start_row=row, start_column=1, end_row=row, end_column=4)
|
||||
c = ws.cell(row=row, column=1, value="Итого:")
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.alignment = Alignment(horizontal="right")
|
||||
for col in range(2, 5):
|
||||
ws.cell(row=row, column=col).border = BORDER
|
||||
c = ws.cell(row=row, column=5, value=float(doc.total))
|
||||
c.font = HEADER_FONT
|
||||
c.border = BORDER
|
||||
c.number_format = MONEY_FMT
|
||||
|
||||
# Column widths
|
||||
widths = {1: 5, 2: 12, 3: 14, 4: 24, 5: 16}
|
||||
for col, width in widths.items():
|
||||
ws.column_dimensions[get_column_letter(col)].width = width
|
||||
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
@@ -0,0 +1,68 @@
|
||||
"""KS-3 export DTO. One source of truth for Excel and Word renderers."""
|
||||
from dataclasses import dataclass
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS3ExportItem:
|
||||
row_number: int
|
||||
ks2_number: str
|
||||
ks2_date: date | None
|
||||
period_from: date | None
|
||||
period_to: date | None
|
||||
amount: Decimal
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS3ExportHeader:
|
||||
project_name: str
|
||||
customer: str
|
||||
contract_number: str
|
||||
ks3_number: str
|
||||
ks3_date: date
|
||||
period_from: date | None
|
||||
period_to: date | None
|
||||
comment: str
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class KS3ExportDocument:
|
||||
header: KS3ExportHeader
|
||||
items: list[KS3ExportItem]
|
||||
total: Decimal
|
||||
|
||||
|
||||
def build_ks3_export_dto(db, ks3_document) -> KS3ExportDocument:
|
||||
"""Build the export DTO from a KS3 document. Read-only: does not modify any data."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
project = ks3_document.project
|
||||
items = []
|
||||
total = D("0")
|
||||
for idx, link in enumerate(ks3_document.links, start=1):
|
||||
ks2 = link.ks2
|
||||
if ks2 is None:
|
||||
continue
|
||||
amount = sum((D(str(line.amount or 0)) for line in ks2.items), D("0"))
|
||||
total += amount
|
||||
items.append(KS3ExportItem(
|
||||
row_number=idx,
|
||||
ks2_number=ks2.number,
|
||||
ks2_date=ks2.date,
|
||||
period_from=ks2.reporting_period_from,
|
||||
period_to=ks2.reporting_period_to,
|
||||
amount=amount,
|
||||
))
|
||||
|
||||
header = KS3ExportHeader(
|
||||
project_name=project.name if project else "",
|
||||
customer=project.customer if project and project.customer else "",
|
||||
contract_number=project.contract_number if project and project.contract_number else "",
|
||||
ks3_number=ks3_document.number,
|
||||
ks3_date=ks3_document.date,
|
||||
period_from=ks3_document.reporting_period_from,
|
||||
period_to=ks3_document.reporting_period_to,
|
||||
comment=ks3_document.comment or "",
|
||||
)
|
||||
return KS3ExportDocument(header=header, items=items, total=total)
|
||||
@@ -0,0 +1,85 @@
|
||||
"""Word renderer for KS-3 export using python-docx."""
|
||||
import io
|
||||
|
||||
from docx import Document
|
||||
from docx.shared import Pt
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||
|
||||
from app.exporters.ks3_dto import KS3ExportDocument
|
||||
|
||||
|
||||
def render_ks3_word(doc: KS3ExportDocument) -> bytes:
|
||||
d = Document()
|
||||
h = doc.header
|
||||
|
||||
# Title
|
||||
title = d.add_paragraph()
|
||||
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = title.add_run(f"КС-3 №{h.ks3_number} от {h.ks3_date.strftime('%d.%m.%Y')}")
|
||||
run.bold = True
|
||||
run.font.size = Pt(14)
|
||||
|
||||
d.add_paragraph()
|
||||
|
||||
# Header block
|
||||
header_lines = [
|
||||
("Проект:", h.project_name),
|
||||
("Заказчик:", h.customer),
|
||||
("Договор:", h.contract_number),
|
||||
]
|
||||
if h.period_from and h.period_to:
|
||||
header_lines.append(("Период:", f"{h.period_from.strftime('%d.%m.%Y')} — {h.period_to.strftime('%d.%m.%Y')}"))
|
||||
if h.comment:
|
||||
header_lines.append(("Комментарий:", h.comment))
|
||||
|
||||
for label, value in header_lines:
|
||||
p = d.add_paragraph()
|
||||
run = p.add_run(label + " ")
|
||||
run.bold = True
|
||||
p.add_run(value)
|
||||
|
||||
d.add_paragraph()
|
||||
|
||||
# Table
|
||||
table = d.add_table(rows=1, cols=5)
|
||||
table.style = "Table Grid"
|
||||
table.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
|
||||
columns = ["№", "КС-2", "Дата", "Период", "Сумма"]
|
||||
for idx, col_name in enumerate(columns):
|
||||
cell = table.rows[0].cells[idx]
|
||||
cell.text = col_name
|
||||
for paragraph in cell.paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
run.font.size = Pt(9)
|
||||
|
||||
for item in doc.items:
|
||||
row = table.add_row()
|
||||
row.cells[0].text = str(item.row_number)
|
||||
row.cells[1].text = f"№{item.ks2_number}"
|
||||
row.cells[2].text = item.ks2_date.strftime('%d.%m.%Y') if item.ks2_date else ""
|
||||
period_text = ""
|
||||
if item.period_from and item.period_to:
|
||||
period_text = f"{item.period_from.strftime('%d.%m.%Y')} — {item.period_to.strftime('%d.%m.%Y')}"
|
||||
row.cells[3].text = period_text
|
||||
row.cells[4].text = f"{item.amount:.2f}"
|
||||
|
||||
# Total row
|
||||
total_row = table.add_row()
|
||||
total_row.cells[0].merge(total_row.cells[3])
|
||||
total_row.cells[0].text = "Итого:"
|
||||
for paragraph in total_row.cells[0].paragraphs:
|
||||
paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
total_row.cells[4].text = f"{doc.total:.2f}"
|
||||
for paragraph in total_row.cells[4].paragraphs:
|
||||
for run in paragraph.runs:
|
||||
run.bold = True
|
||||
|
||||
buf = io.BytesIO()
|
||||
d.save(buf)
|
||||
buf.seek(0)
|
||||
return buf.read()
|
||||
+4
-4
@@ -165,13 +165,13 @@ async def ks2_cancel(project_id: int, ks2_id: int, db: Session = Depends(get_db)
|
||||
|
||||
|
||||
def _safe_filename(number: str, dt) -> str:
|
||||
raw = f"КС-2 №{number} от {dt.strftime('%d.%m.%Y')}"
|
||||
return re.sub(r'[<>:"/\\|?*]', "_", raw)
|
||||
from app.exporters import safe_export_filename
|
||||
return safe_export_filename("КС-2", number, dt, "xlsx")
|
||||
|
||||
|
||||
def _content_disposition(filename: str) -> str:
|
||||
from urllib.parse import quote
|
||||
return f"attachment; filename*=UTF-8''{quote(filename)}"
|
||||
from app.exporters import content_disposition
|
||||
return content_disposition(filename)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks2/{ks2_id}/export/excel")
|
||||
|
||||
+34
-2
@@ -3,7 +3,7 @@ from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
from fastapi import APIRouter, Depends, Form, HTTPException, Request
|
||||
from fastapi.responses import RedirectResponse
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
@@ -164,4 +164,36 @@ async def ks3_cancel(project_id: int, ks3_id: int, db: Session = Depends(get_db)
|
||||
raise HTTPException(status_code=400, detail="KS-3 already cancelled")
|
||||
doc.status = "cancelled"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/{ks3_id}/export/excel")
|
||||
async def ks3_export_excel(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
document = _document(db, project_id, ks3_id)
|
||||
from app.exporters import safe_export_filename, content_disposition
|
||||
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||
from app.exporters.excel.ks3_renderer import render_ks3_excel
|
||||
dto = build_ks3_export_dto(db, document)
|
||||
data = render_ks3_excel(dto)
|
||||
filename = safe_export_filename("КС-3", document.number, document.date, "xlsx")
|
||||
return Response(
|
||||
content=data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": content_disposition(filename)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/{ks3_id}/export/word")
|
||||
async def ks3_export_word(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
document = _document(db, project_id, ks3_id)
|
||||
from app.exporters import safe_export_filename, content_disposition
|
||||
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||
from app.exporters.word.ks3_renderer import render_ks3_word
|
||||
dto = build_ks3_export_dto(db, document)
|
||||
data = render_ks3_word(dto)
|
||||
filename = safe_export_filename("КС-3", document.number, document.date, "docx")
|
||||
return Response(
|
||||
content=data,
|
||||
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
headers={"Content-Disposition": content_disposition(filename)},
|
||||
)
|
||||
@@ -29,6 +29,10 @@
|
||||
{% if document.comment %}
|
||||
<p><strong>Комментарий:</strong> {{ document.comment }}</p>
|
||||
{% endif %}
|
||||
<div class="mt-2">
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
# Implementation Report — Task 017
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Реализован экспорт КС-3 в Excel и Word на базе существующего export layer из Task 016.
|
||||
|
||||
---
|
||||
|
||||
### Архитектура
|
||||
|
||||
```
|
||||
KS3 document (DB)
|
||||
↓
|
||||
KS3ExportDocument DTO (app/exporters/ks3_dto.py)
|
||||
↓
|
||||
┌─────────────────────┬─────────────────────┐
|
||||
│ render_ks3_excel │ render_ks3_word │
|
||||
│ (openpyxl) │ (python-docx) │
|
||||
└─────────────────────┴─────────────────────┘
|
||||
↓
|
||||
файл .xlsx / .docx
|
||||
```
|
||||
|
||||
Общий принцип: один DTO → два рендерера. Данные из KS2.items, не пересчёт из Daily Reports.
|
||||
|
||||
### DTO
|
||||
|
||||
`KS3ExportDocument` (frozen dataclass):
|
||||
- `KS3ExportHeader`: project_name, customer, contract_number, ks3_number, ks3_date, period_from, period_to, comment
|
||||
- `KS3ExportItem`: row_number, ks2_number, ks2_date, period_from, period_to, amount
|
||||
- `total: Decimal`
|
||||
|
||||
### Excel renderer
|
||||
|
||||
`app/exporters/excel/ks3_renderer.py`:
|
||||
- Заголовок «КС-3 №... от ...»
|
||||
- Шапка: проект, заказчик, договор, период
|
||||
- Таблица: № | КС-2 | Дата | Период | Сумма
|
||||
- Числовой формат `#,##0.00`, границы, ширины колонок
|
||||
- Итоговая строка
|
||||
|
||||
### Word renderer
|
||||
|
||||
`app/exporters/word/ks3_renderer.py`:
|
||||
- Заголовок, реквизиты, таблица Table Grid, итог
|
||||
- Редактируемый .docx
|
||||
|
||||
### Endpoints
|
||||
|
||||
- `GET /projects/{id}/ks3/{id}/export/excel`
|
||||
- `GET /projects/{id}/ks3/{id}/export/word`
|
||||
|
||||
Content-Disposition с URL-encoded UTF-8 filename. Переиспользованы `safe_export_filename()` и `content_disposition()` из `app/exporters/__init__.py`.
|
||||
|
||||
### UI
|
||||
|
||||
Кнопки `📊 Excel` и `📄 Word` на странице просмотра КС-3.
|
||||
|
||||
### Переиспользование
|
||||
|
||||
- `safe_export_filename()`, `content_disposition()` вынесены в `app/exporters/__init__.py`
|
||||
- KS-2 router обновлён для использования общих helper-ов
|
||||
- Одинаковый паттерн DTO → renderer → Response
|
||||
|
||||
### Тесты (13)
|
||||
|
||||
1. Excel endpoint существует
|
||||
2. Word endpoint существует
|
||||
3. Excel Content-Type
|
||||
4. Word Content-Type
|
||||
5. Filename содержит номер КС-3
|
||||
6. Excel открывается через openpyxl
|
||||
7. Word открывается через python-docx
|
||||
8. Excel содержит выбранные КС-2
|
||||
9. Word содержит выбранные КС-2
|
||||
10. Итоговая сумма совпадает
|
||||
11. Экспорт не меняет КС-3
|
||||
12. Несколько КС-2 (3 шт.)
|
||||
13. Посторонние КС-2 не попадают в экспорт
|
||||
|
||||
Результат: `121 passed, 0 failed`
|
||||
`git diff --check`: чисто
|
||||
|
||||
### Changed files
|
||||
|
||||
**Новые:**
|
||||
- `app/exporters/ks3_dto.py`
|
||||
- `app/exporters/excel/ks3_renderer.py`
|
||||
- `app/exporters/word/ks3_renderer.py`
|
||||
- `tests/test_task017_ks3_export.py`
|
||||
|
||||
**Изменённые:**
|
||||
- `app/exporters/__init__.py` — общие helper-функции
|
||||
- `app/routers/ks2.py` — использование общих helper-ов
|
||||
- `app/routers/ks3.py` — export endpoints
|
||||
- `app/templates/ks3/view.html` — кнопки экспорта
|
||||
|
||||
### Ограничения
|
||||
|
||||
- КС-6а экспорт — следующий этап
|
||||
- Не государственная типографская форма 1:1
|
||||
- Сторнированный КС-3 экспортируется как есть (без специальной обработки)
|
||||
@@ -0,0 +1,298 @@
|
||||
"""Regression tests for task 017: KS-3 Excel/Word export."""
|
||||
import io
|
||||
import shutil
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
|
||||
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, 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
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t017-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):
|
||||
app.dependency_overrides[dep] = override_db
|
||||
|
||||
|
||||
def _clear():
|
||||
for dep in (projects.get_db, ks2_router.get_db, ks3_router.get_db):
|
||||
app.dependency_overrides.pop(dep, None)
|
||||
|
||||
|
||||
def _create_ks3(Session, num_ks2=1):
|
||||
with Session() as s:
|
||||
p = Project(name="KS3 export test", customer="Customer LLC", contract_number="DOG-456")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||||
s.add(doc)
|
||||
s.flush()
|
||||
ks2_ids = []
|
||||
for i in range(num_ks2):
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name=f"Item {i+1}",
|
||||
source_number=f"{i+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=__import__("datetime").date(2026, 1, 1))
|
||||
s.add(dr)
|
||||
s.flush()
|
||||
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("30")))
|
||||
s.flush()
|
||||
ks2 = KS2(project_id=p.id, number=str(i+1), date=__import__("datetime").date(2026, 9, 30),
|
||||
status="issued")
|
||||
s.add(ks2)
|
||||
s.flush()
|
||||
s.add(KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("30"),
|
||||
unit_price=Decimal("50"), amount=Decimal("1500")))
|
||||
s.flush()
|
||||
ks2_ids.append(ks2.id)
|
||||
|
||||
ks3 = KS3(project_id=p.id, number="1", date=__import__("datetime").date(2026, 9, 30),
|
||||
status="issued")
|
||||
s.add(ks3)
|
||||
s.flush()
|
||||
for kid in ks2_ids:
|
||||
s.add(KS3KS2(ks3_id=ks3.id, ks2_id=kid))
|
||||
s.commit()
|
||||
return p.id, ks3.id
|
||||
|
||||
|
||||
def test_ks3_excel_endpoint_exists(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
assert resp.status_code == 200
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_word_endpoint_exists(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word")
|
||||
assert resp.status_code == 200
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_excel_content_type(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
assert "spreadsheetml" in resp.headers["content-type"]
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_word_content_type(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word")
|
||||
assert "wordprocessingml" in resp.headers["content-type"]
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_filename_contains_number(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
assert "filename" in resp.headers["content-disposition"]
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_excel_opens_with_openpyxl(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(io.BytesIO(resp.content))
|
||||
assert wb.active is not None
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_word_opens_with_python_docx(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word")
|
||||
from docx import Document
|
||||
d = Document(io.BytesIO(resp.content))
|
||||
assert len(d.tables) > 0
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_excel_contains_ks2(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
from openpyxl import load_workbook
|
||||
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)
|
||||
assert "№1" in text
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_word_contains_ks2(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/word")
|
||||
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)
|
||||
assert "№1" in text
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_excel_total_matches(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(io.BytesIO(resp.content))
|
||||
ws = wb.active
|
||||
total_found = False
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value == "Итого:":
|
||||
total_cell = ws.cell(row=cell.row, column=5)
|
||||
assert abs(float(total_cell.value) - 1500.0) < 0.01
|
||||
total_found = True
|
||||
assert total_found
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_export_does_not_modify(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with Session() as s:
|
||||
before_status = s.get(KS3, kid).status
|
||||
with TestClient(app) as client:
|
||||
client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
client.get(f"/projects/{pid}/ks3/{kid}/export/word")
|
||||
with Session() as s:
|
||||
assert s.get(KS3, kid).status == before_status
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_export_multiple_ks2(tmp_path):
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session, num_ks2=3)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
from openpyxl import load_workbook
|
||||
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)
|
||||
assert "№1" in text
|
||||
assert "№2" in text
|
||||
assert "№3" in text
|
||||
# Total = 3 * 1500 = 4500
|
||||
total_found = False
|
||||
for row in ws.iter_rows():
|
||||
for cell in row:
|
||||
if cell.value == "Итого:":
|
||||
total_cell = ws.cell(row=cell.row, column=5)
|
||||
assert abs(float(total_cell.value) - 4500.0) < 0.01
|
||||
total_found = True
|
||||
assert total_found
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_ks3_export_no_foreign_ks2(tmp_path):
|
||||
"""Only KS-2 linked to this KS-3 appear in the export."""
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_override(Session)
|
||||
try:
|
||||
pid, kid = _create_ks3(Session)
|
||||
with TestClient(app) as client:
|
||||
resp = client.get(f"/projects/{pid}/ks3/{kid}/export/excel")
|
||||
from openpyxl import load_workbook
|
||||
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)
|
||||
assert "Item 1" not in text # KS-2 item names not in KS-3 export
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user