feat: add document package ZIP export
This commit is contained in:
@@ -0,0 +1,174 @@
|
|||||||
|
"""Build a ZIP package of project documents for a selected period.
|
||||||
|
|
||||||
|
Uses existing export DTO/renderers. Does not duplicate generation logic.
|
||||||
|
Only issued KS-2/KS-3 with a fully set reporting period that falls into
|
||||||
|
the selected range are included. KS-6a is a reporting view of Daily Reports.
|
||||||
|
"""
|
||||||
|
import io
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
from app.exporters import _clean_export_name
|
||||||
|
|
||||||
|
|
||||||
|
class PackageEmptyError(Exception):
|
||||||
|
"""No documents match the selected package composition."""
|
||||||
|
|
||||||
|
|
||||||
|
class PackageValidationError(Exception):
|
||||||
|
"""Invalid package request parameters."""
|
||||||
|
|
||||||
|
|
||||||
|
VALID_DOCS = ("ks6a", "ks2", "ks3")
|
||||||
|
VALID_FORMATS = ("excel", "word", "both")
|
||||||
|
|
||||||
|
|
||||||
|
def _period_formats(export_format: str) -> list[str]:
|
||||||
|
if export_format == "excel":
|
||||||
|
return ["xlsx"]
|
||||||
|
if export_format == "word":
|
||||||
|
return ["docx"]
|
||||||
|
return ["xlsx", "docx"]
|
||||||
|
|
||||||
|
|
||||||
|
def _period_text(date_from: date, date_to: date) -> str:
|
||||||
|
return f"{date_from.strftime('%d.%m.%Y')}-{date_to.strftime('%d.%m.%Y')}"
|
||||||
|
|
||||||
|
|
||||||
|
def package_filename(project_name: str, date_from: date, date_to: date) -> str:
|
||||||
|
raw = f"Комплект_{project_name}_{_period_text(date_from, date_to)}"
|
||||||
|
raw = re.sub(r"\s+", "_", raw.strip())
|
||||||
|
return f"{_clean_export_name(raw)}.zip"
|
||||||
|
|
||||||
|
|
||||||
|
def _member_filename(prefix: str, number: str, dt) -> str:
|
||||||
|
raw = f"{prefix}_№{number}_{dt.strftime('%d.%m.%Y')}"
|
||||||
|
return _clean_export_name(raw)
|
||||||
|
|
||||||
|
|
||||||
|
def _period_fits(doc_from: date | None, doc_to: date | None, date_from: date, date_to: date) -> bool:
|
||||||
|
if doc_from is None or doc_to is None:
|
||||||
|
return False
|
||||||
|
return doc_from <= date_to and doc_to >= date_from
|
||||||
|
|
||||||
|
|
||||||
|
def _ks2_in_period(db, project_id: int, date_from: date, date_to: date):
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
|
||||||
|
return db.query(KS2).options(
|
||||||
|
joinedload(KS2.items)
|
||||||
|
).filter(
|
||||||
|
KS2.project_id == project_id,
|
||||||
|
KS2.status == "issued",
|
||||||
|
KS2.reporting_period_from.isnot(None),
|
||||||
|
KS2.reporting_period_to.isnot(None),
|
||||||
|
KS2.reporting_period_from <= date_to,
|
||||||
|
KS2.reporting_period_to >= date_from,
|
||||||
|
).order_by(KS2.date, KS2.id).all()
|
||||||
|
|
||||||
|
|
||||||
|
def _ks3_in_period(db, project_id: int, date_from: date, date_to: date):
|
||||||
|
from sqlalchemy.orm import joinedload
|
||||||
|
|
||||||
|
from app.models.ks2 import KS2
|
||||||
|
from app.models.ks3 import KS3, KS3KS2
|
||||||
|
|
||||||
|
return db.query(KS3).options(
|
||||||
|
joinedload(KS3.links).joinedload(KS3KS2.ks2).joinedload(KS2.items)
|
||||||
|
).filter(
|
||||||
|
KS3.project_id == project_id,
|
||||||
|
KS3.status == "issued",
|
||||||
|
KS3.reporting_period_from.isnot(None),
|
||||||
|
KS3.reporting_period_to.isnot(None),
|
||||||
|
KS3.reporting_period_from <= date_to,
|
||||||
|
KS3.reporting_period_to >= date_from,
|
||||||
|
).order_by(KS3.date, KS3.id).all()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_package_params(date_from: str, date_to: str, include, export_format: str):
|
||||||
|
if not date_from or not date_to:
|
||||||
|
raise PackageValidationError("Необходимо указать период (date_from и date_to)")
|
||||||
|
try:
|
||||||
|
parsed_from = date.fromisoformat(date_from)
|
||||||
|
parsed_to = date.fromisoformat(date_to)
|
||||||
|
except ValueError:
|
||||||
|
raise PackageValidationError("Неверный формат даты")
|
||||||
|
if parsed_to < parsed_from:
|
||||||
|
raise PackageValidationError("Дата окончания не может быть раньше даты начала")
|
||||||
|
|
||||||
|
selected = []
|
||||||
|
for item in include or []:
|
||||||
|
if item in VALID_DOCS and item not in selected:
|
||||||
|
selected.append(item)
|
||||||
|
if not selected:
|
||||||
|
raise PackageValidationError("Выберите хотя бы один тип документов (КС-6а, КС-2, КС-3)")
|
||||||
|
|
||||||
|
if export_format not in VALID_FORMATS:
|
||||||
|
raise PackageValidationError("Неверный формат экспорта")
|
||||||
|
|
||||||
|
return parsed_from, parsed_to, selected, export_format
|
||||||
|
|
||||||
|
|
||||||
|
def build_document_package(db, project, date_from: date, date_to: date,
|
||||||
|
include: list[str], export_format: str) -> tuple[bytes, str]:
|
||||||
|
"""Return (zip_bytes, filename). Raises PackageEmptyError when nothing to pack."""
|
||||||
|
from app.exporters.ks2_dto import build_ks2_export_dto
|
||||||
|
from app.exporters.ks3_dto import build_ks3_export_dto
|
||||||
|
from app.exporters.ks6a_dto import build_ks6a_export_dto, fetch_ks6a_rows
|
||||||
|
|
||||||
|
formats = _period_formats(export_format)
|
||||||
|
members: list[tuple[str, bytes]] = [] # (zip arcname, data)
|
||||||
|
|
||||||
|
if "ks6a" in include:
|
||||||
|
from app.exporters.excel.ks6a_renderer import render_ks6a_excel
|
||||||
|
from app.exporters.word.ks6a_renderer import render_ks6a_word
|
||||||
|
|
||||||
|
rows = fetch_ks6a_rows(db, project.id, date_from, date_to, None)
|
||||||
|
dto = build_ks6a_export_dto(project, rows, date_from, date_to, "")
|
||||||
|
base = f"КС-6а_{_period_text(date_from, date_to)}"
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-6а/{base}.xlsx", render_ks6a_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-6а/{base}.docx", render_ks6a_word(dto)))
|
||||||
|
|
||||||
|
if "ks2" in include:
|
||||||
|
from app.exporters.excel.ks2_renderer import render_ks2_excel
|
||||||
|
from app.exporters.word.ks2_renderer import render_ks2_word
|
||||||
|
|
||||||
|
for doc in _ks2_in_period(db, project.id, date_from, date_to):
|
||||||
|
dto = build_ks2_export_dto(db, doc)
|
||||||
|
base = _member_filename("КС-2", doc.number, doc.date)
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-2/{base}.xlsx", render_ks2_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-2/{base}.docx", render_ks2_word(dto)))
|
||||||
|
|
||||||
|
if "ks3" in include:
|
||||||
|
from app.exporters.excel.ks3_renderer import render_ks3_excel
|
||||||
|
from app.exporters.word.ks3_renderer import render_ks3_word
|
||||||
|
|
||||||
|
for doc in _ks3_in_period(db, project.id, date_from, date_to):
|
||||||
|
dto = build_ks3_export_dto(db, doc)
|
||||||
|
base = _member_filename("КС-3", doc.number, doc.date)
|
||||||
|
for fmt in formats:
|
||||||
|
if fmt == "xlsx":
|
||||||
|
members.append((f"КС-3/{base}.xlsx", render_ks3_excel(dto)))
|
||||||
|
else:
|
||||||
|
members.append((f"КС-3/{base}.docx", render_ks3_word(dto)))
|
||||||
|
|
||||||
|
if not members:
|
||||||
|
raise PackageEmptyError(
|
||||||
|
"За выбранный период нет документов для включения в комплект"
|
||||||
|
)
|
||||||
|
|
||||||
|
buf = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(buf, "w", compression=zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for arcname, data in members:
|
||||||
|
zf.writestr(arcname, data)
|
||||||
|
buf.seek(0)
|
||||||
|
return buf.read(), package_filename(project.name or "проект", date_from, date_to)
|
||||||
+44
-2
@@ -1,5 +1,5 @@
|
|||||||
from fastapi import APIRouter, Depends, HTTPException, Request, Form
|
from fastapi import APIRouter, Depends, HTTPException, Query, Request, Form
|
||||||
from fastapi.responses import RedirectResponse
|
from fastapi.responses import RedirectResponse, Response
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from app.database import database
|
from app.database import database
|
||||||
from app.models import project
|
from app.models import project
|
||||||
@@ -308,3 +308,45 @@ async def archive_project(project_id: int, db: Session = Depends(get_db)):
|
|||||||
db_project.status = "archived"
|
db_project.status = "archived"
|
||||||
db.commit()
|
db.commit()
|
||||||
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
return RedirectResponse(url=f"/projects/{project_id}", status_code=303)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{project_id}/export/package")
|
||||||
|
async def export_document_package(
|
||||||
|
project_id: int,
|
||||||
|
date_from: str = "",
|
||||||
|
date_to: str = "",
|
||||||
|
include: list[str] = Query(default=[]),
|
||||||
|
export_format: str = Query("both", alias="format"),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
):
|
||||||
|
db_project = db.query(project.Project).filter(project.Project.id == project_id).first()
|
||||||
|
if db_project is None:
|
||||||
|
raise HTTPException(status_code=404, detail="Project not found")
|
||||||
|
|
||||||
|
from app.exporters.package_service import (
|
||||||
|
PackageEmptyError,
|
||||||
|
PackageValidationError,
|
||||||
|
build_document_package,
|
||||||
|
parse_package_params,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
parsed_from, parsed_to, selected, export_format = parse_package_params(
|
||||||
|
date_from, date_to, include, export_format
|
||||||
|
)
|
||||||
|
except PackageValidationError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
try:
|
||||||
|
data, filename = build_document_package(
|
||||||
|
db, db_project, parsed_from, parsed_to, selected, export_format
|
||||||
|
)
|
||||||
|
except PackageEmptyError as exc:
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
|
||||||
|
from app.exporters import content_disposition
|
||||||
|
return Response(
|
||||||
|
content=data,
|
||||||
|
media_type="application/zip",
|
||||||
|
headers={"Content-Disposition": content_disposition(filename)},
|
||||||
|
)
|
||||||
|
|||||||
@@ -146,6 +146,52 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
<section class="card border-0 shadow-sm mt-4" aria-labelledby="package-heading">
|
||||||
|
<div class="card-header bg-white">
|
||||||
|
<h2 class="h5 mb-0" id="package-heading">Комплект документов</h2>
|
||||||
|
</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p class="text-muted small mb-3">Единый ZIP-архив документации за период (КС-6а, КС-2, КС-3) для отправки заказчику или коллеге.</p>
|
||||||
|
<form method="get" action="/projects/{{ project.id }}/export/package" class="row g-3 align-items-end">
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label class="form-label" for="package-date-from">Дата с</label>
|
||||||
|
<input type="date" class="form-control" id="package-date-from" name="date_from" required>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<label class="form-label" for="package-date-to">Дата по</label>
|
||||||
|
<input type="date" class="form-control" id="package-date-to" name="date_to" required>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<span class="form-label d-block">Состав комплекта</span>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks6a" id="package-ks6a" checked>
|
||||||
|
<label class="form-check-label" for="package-ks6a">КС-6а</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks2" id="package-ks2" checked>
|
||||||
|
<label class="form-check-label" for="package-ks2">КС-2</label>
|
||||||
|
</div>
|
||||||
|
<div class="form-check form-check-inline">
|
||||||
|
<input class="form-check-input" type="checkbox" name="include" value="ks3" id="package-ks3" checked>
|
||||||
|
<label class="form-check-label" for="package-ks3">КС-3</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-3">
|
||||||
|
<label class="form-label" for="package-format">Формат</label>
|
||||||
|
<select class="form-select" id="package-format" name="format">
|
||||||
|
<option value="both" selected>Excel + Word</option>
|
||||||
|
<option value="excel">Excel</option>
|
||||||
|
<option value="word">Word</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-2">
|
||||||
|
<button type="submit" class="btn btn-primary w-100">Сформировать комплект</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
<div id="package-error" class="alert alert-danger mt-3 mb-0" role="alert" hidden></div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
<section class="card border-0 shadow-sm mt-4">
|
<section class="card border-0 shadow-sm mt-4">
|
||||||
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Последние Daily Reports</h2><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-sm btn-outline-primary">Все отчёты</a></div>
|
<div class="card-header bg-white d-flex justify-content-between align-items-center"><h2 class="h5 mb-0">Последние Daily Reports</h2><a href="/projects/{{ project.id }}/daily-reports" class="btn btn-sm btn-outline-primary">Все отчёты</a></div>
|
||||||
{% if recent_reports %}
|
{% if recent_reports %}
|
||||||
@@ -300,6 +346,47 @@
|
|||||||
document.getElementById('toggleMoney').addEventListener('click', () => {
|
document.getElementById('toggleMoney').addEventListener('click', () => {
|
||||||
document.body.classList.toggle('money-hidden');
|
document.body.classList.toggle('money-hidden');
|
||||||
});
|
});
|
||||||
|
const packageForm = document.querySelector('form[action*="/export/package"]');
|
||||||
|
const packageError = document.getElementById('package-error');
|
||||||
|
if (packageForm) {
|
||||||
|
packageForm.addEventListener('submit', async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
packageError.hidden = true;
|
||||||
|
const action = packageForm.getAttribute('action');
|
||||||
|
const params = new URLSearchParams(new FormData(packageForm));
|
||||||
|
if (!params.getAll('include').length) {
|
||||||
|
packageError.textContent = 'Выберите хотя бы один тип документов (КС-6а, КС-2, КС-3).';
|
||||||
|
packageError.hidden = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${action}?${params.toString()}`);
|
||||||
|
if (!response.ok) {
|
||||||
|
let message = 'Не удалось сформировать комплект.';
|
||||||
|
try {
|
||||||
|
const payload = await response.json();
|
||||||
|
if (payload && payload.detail) message = payload.detail;
|
||||||
|
} catch { /* keep default */ }
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
const blob = await response.blob();
|
||||||
|
const disposition = response.headers.get('Content-Disposition') || '';
|
||||||
|
const utfMatch = disposition.match(/filename\*=UTF-8''([^;]+)/);
|
||||||
|
const plainMatch = disposition.match(/filename="?([^";]+)"?/);
|
||||||
|
const filename = utfMatch ? decodeURIComponent(utfMatch[1]) : (plainMatch ? plainMatch[1] : 'Комплект.zip');
|
||||||
|
const link = document.createElement('a');
|
||||||
|
link.href = URL.createObjectURL(blob);
|
||||||
|
link.download = filename;
|
||||||
|
document.body.append(link);
|
||||||
|
link.click();
|
||||||
|
link.remove();
|
||||||
|
URL.revokeObjectURL(link.href);
|
||||||
|
} catch (e) {
|
||||||
|
packageError.textContent = e.message;
|
||||||
|
packageError.hidden = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
})();
|
})();
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# Implementation Report — Task 019
|
||||||
|
|
||||||
|
### Status
|
||||||
|
|
||||||
|
DONE
|
||||||
|
|
||||||
|
### What was done
|
||||||
|
|
||||||
|
Реализован общий комплект документации за период: единый ZIP из КС-6а / КС-2 / КС-3
|
||||||
|
в выбранном формате (Excel / Word / Excel + Word). Существующие экспортеры не переделаны.
|
||||||
|
|
||||||
|
Сценарий:
|
||||||
|
`проект → период → состав комплекта → формат → ZIP`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Архитектура
|
||||||
|
|
||||||
|
```
|
||||||
|
Project page («Комплект документов» form)
|
||||||
|
↓
|
||||||
|
GET /projects/{id}/export/package
|
||||||
|
↓
|
||||||
|
package_service.parse_package_params / build_document_package
|
||||||
|
↓
|
||||||
|
┌──────────────┬──────────────┬──────────────┐
|
||||||
|
│ KS-6a DTO + │ KS-2 DTO + │ KS-3 DTO + │
|
||||||
|
│ renderers │ renderers │ renderers │
|
||||||
|
└──────────────┴──────────────┴──────────────┘
|
||||||
|
↓
|
||||||
|
ZIP in memory (io.BytesIO / zipfile)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Service
|
||||||
|
|
||||||
|
`app/exporters/package_service.py`:
|
||||||
|
|
||||||
|
- `parse_package_params()` — валидация дат, состава, формата
|
||||||
|
- `build_document_package()` — отбор документов, вызов существующих DTO/renderers, сборка ZIP
|
||||||
|
- `PackageValidationError` / `PackageEmptyError`
|
||||||
|
- `package_filename()` — имя архива `Комплект_{Проект}_{дд.мм.гггг-дд.мм.гггг}.zip`
|
||||||
|
|
||||||
|
Отбор документов:
|
||||||
|
|
||||||
|
| Тип | Правило |
|
||||||
|
|-----|---------|
|
||||||
|
| КС-6а | один журнал за весь период из DailyReportItem (если выбран) |
|
||||||
|
| КС-2 | только `status=issued`, `reporting_period_from/to` заданы и период пересекает выбранный |
|
||||||
|
| КС-3 | только `status=issued`, `reporting_period_from/to` заданы и период пересекает выбранный |
|
||||||
|
|
||||||
|
Исключены: черновики, сторнированные, документы без периода, документы вне периода, документы другого проекта.
|
||||||
|
|
||||||
|
### ZIP structure
|
||||||
|
|
||||||
|
```
|
||||||
|
Комплект_Саудовская_Аравия_01.03.2026-31.03.2026.zip
|
||||||
|
├── КС-6а/КС-6а_01.03.2026-31.03.2026.xlsx
|
||||||
|
├── КС-2/КС-2_№1_20.03.2026.xlsx
|
||||||
|
└── КС-3/КС-3_№1_25.03.2026.xlsx
|
||||||
|
```
|
||||||
|
|
||||||
|
- только реально выбранные форматы и существующие документы;
|
||||||
|
- пустые каталоги не создаются;
|
||||||
|
- русские имена допустимы;
|
||||||
|
- номер документа сохраняется в имени файла;
|
||||||
|
- сборка в памяти, без временных файлов на диске.
|
||||||
|
|
||||||
|
### Endpoint
|
||||||
|
|
||||||
|
`GET /projects/{project_id}/export/package`
|
||||||
|
|
||||||
|
Параметры:
|
||||||
|
- `date_from`, `date_to` — обязательны, `date_to >= date_from`
|
||||||
|
- `include` — `ks6a` / `ks2` / `ks3` (можно несколько)
|
||||||
|
- `format` — `excel` / `word` / `both`
|
||||||
|
|
||||||
|
Ответ:
|
||||||
|
- `application/zip` + `Content-Disposition` (UTF-8 filename)
|
||||||
|
- 400 — невалидные параметры или пустой комплект («За выбранный период нет документов…»)
|
||||||
|
- 404 — проект не найден
|
||||||
|
|
||||||
|
### UI
|
||||||
|
|
||||||
|
На странице проекта — отдельный блок «Комплект документов» (не смешан с кнопками отдельных документов):
|
||||||
|
- дата с / дата по;
|
||||||
|
- чекбоксы КС-6а / КС-2 / КС-3;
|
||||||
|
- селект формата;
|
||||||
|
- кнопка «Сформировать комплект».
|
||||||
|
|
||||||
|
Форма отправляет GET на package endpoint; при ошибке (в т.ч. пустой комплект) показывается alert без ухода со страницы.
|
||||||
|
|
||||||
|
### Privacy
|
||||||
|
|
||||||
|
ZIP содержит фактические суммы документов независимо от eye icon (eye icon — только UI).
|
||||||
|
|
||||||
|
### Переиспользование
|
||||||
|
|
||||||
|
- существующие DTO: `ks2_dto`, `ks3_dto`, `ks6a_dto`
|
||||||
|
- существующие Excel/Word renderers КС-2 / КС-3 / КС-6а
|
||||||
|
- `content_disposition()`, `_clean_export_name()`
|
||||||
|
- `fetch_ks6a_rows()` для КС-6а
|
||||||
|
|
||||||
|
Генерация Excel/Word не дублируется.
|
||||||
|
|
||||||
|
### Changed files
|
||||||
|
|
||||||
|
**Новые:**
|
||||||
|
- `app/exporters/package_service.py`
|
||||||
|
- `tests/test_task019_document_package.py`
|
||||||
|
|
||||||
|
**Изменённые:**
|
||||||
|
- `app/routers/projects.py` — `GET /{project_id}/export/package`
|
||||||
|
- `app/templates/projects/detail.html` — блок «Комплект документов» + JS загрузки/ошибок
|
||||||
|
|
||||||
|
### Tests
|
||||||
|
|
||||||
|
`tests/test_task019_document_package.py` — 21 тест:
|
||||||
|
|
||||||
|
1. форма на странице проекта;
|
||||||
|
2. package endpoint доступен, `application/zip`;
|
||||||
|
3. ZIP создаётся;
|
||||||
|
4. ZIP содержит КС-6а (xlsx+docx);
|
||||||
|
5. ZIP содержит КС-2 (с номером);
|
||||||
|
6. ZIP содержит КС-3 (с номером);
|
||||||
|
7. только один тип документов;
|
||||||
|
8. только Excel;
|
||||||
|
9. только Word;
|
||||||
|
10. Excel + Word;
|
||||||
|
11. сторнированный КС-2 не попадает;
|
||||||
|
12. сторнированный КС-3 не попадает;
|
||||||
|
13. draft КС-2/КС-3 не попадает;
|
||||||
|
14. документы другого периода не попадают;
|
||||||
|
15. документы другого проекта не попадают;
|
||||||
|
16. пустой комплект → 400;
|
||||||
|
17. только КС-6а → ZIP создаётся;
|
||||||
|
18. имя ZIP содержит проект и период;
|
||||||
|
19. Excel/Word из ZIP открываются (openpyxl/python-docx);
|
||||||
|
20. суммы экспортируются независимо от privacy;
|
||||||
|
21. индивидуальные экспорты КС-2/КС-3/КС-6а продолжают работать.
|
||||||
|
|
||||||
|
Результат: `157 passed, 0 failed`
|
||||||
|
`git diff --check`: чисто
|
||||||
|
|
||||||
|
### Deviations
|
||||||
|
|
||||||
|
None.
|
||||||
|
|
||||||
|
### Follow-up / Open Questions
|
||||||
|
|
||||||
|
- Включение КС-2/КС-3 по пересечению reporting-периодов; при необходимости — более строгий критерий (полное попадание).
|
||||||
|
- КС-3 без `reporting_period_from/to` не включается, даже если связанные КС-2 попадают в период.
|
||||||
|
- PDF / email / автотправка / платежи / сложный конструктор комплектов — вне scope.
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
# Task 019 — Общий комплект документации за период
|
||||||
|
|
||||||
|
## Цель
|
||||||
|
|
||||||
|
Сделать единый экспорт комплекта проектной документации за выбранный период.
|
||||||
|
|
||||||
|
Сейчас отдельные документы уже умеют выгружаться в Excel/Word:
|
||||||
|
- КС-2;
|
||||||
|
- КС-3;
|
||||||
|
- КС-6а.
|
||||||
|
|
||||||
|
Задача 019 должна не переделывать существующие экспортеры, а собрать их в единый пользовательский сценарий.
|
||||||
|
|
||||||
|
Главная идея:
|
||||||
|
|
||||||
|
`проект → период → выбрать состав комплекта → сформировать ZIP → скачать`
|
||||||
|
|
||||||
|
Комплект должен быть пригоден для отправки заказчику/коллеге по почте.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. UI
|
||||||
|
|
||||||
|
На странице проекта добавить отдельный блок/кнопку:
|
||||||
|
|
||||||
|
**«Комплект документов»**
|
||||||
|
|
||||||
|
Не смешивать её с кнопками отдельных документов.
|
||||||
|
|
||||||
|
Форма:
|
||||||
|
- Дата с;
|
||||||
|
- Дата по;
|
||||||
|
- состав комплекта:
|
||||||
|
- КС-6а;
|
||||||
|
- КС-2;
|
||||||
|
- КС-3;
|
||||||
|
- формат:
|
||||||
|
- Excel;
|
||||||
|
- Word;
|
||||||
|
- Excel + Word.
|
||||||
|
|
||||||
|
Дата по не может быть меньше даты с.
|
||||||
|
|
||||||
|
После формирования пользователь получает один `.zip`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Состав комплекта
|
||||||
|
|
||||||
|
### КС-6а
|
||||||
|
|
||||||
|
Формировать журнал за выбранный период.
|
||||||
|
|
||||||
|
Использовать существующий экспорт КС-6а.
|
||||||
|
|
||||||
|
В комплект попадает:
|
||||||
|
- один КС-6а за весь выбранный период;
|
||||||
|
- при выбранном формате Excel — `.xlsx`;
|
||||||
|
- при выбранном формате Word — `.docx`.
|
||||||
|
|
||||||
|
Если выбран только КС-6а, ZIP всё равно создаётся.
|
||||||
|
|
||||||
|
### КС-2
|
||||||
|
|
||||||
|
В комплект включать КС-2 проекта, относящиеся к выбранному периоду.
|
||||||
|
|
||||||
|
Для первой версии считать документ относящимся к периоду, если его `reporting_period_from` и `reporting_period_to` полностью заданы и документ попадает в выбранный период.
|
||||||
|
|
||||||
|
В комплект включать только **проведённые** КС-2.
|
||||||
|
|
||||||
|
Сторнированные КС-2 в обычный комплект не включать.
|
||||||
|
|
||||||
|
Для каждого КС-2:
|
||||||
|
- использовать существующий экспорт КС-2;
|
||||||
|
- не дублировать код генерации Excel/Word;
|
||||||
|
- имя файла должно сохранять номер КС-2.
|
||||||
|
|
||||||
|
### КС-3
|
||||||
|
|
||||||
|
В комплект включать КС-3 проекта, относящиеся к выбранному периоду.
|
||||||
|
|
||||||
|
В комплект включать только **проведённые** КС-3.
|
||||||
|
|
||||||
|
Сторнированные КС-3 в обычный комплект не включать.
|
||||||
|
|
||||||
|
Для каждого КС-3:
|
||||||
|
- использовать существующий экспорт КС-3;
|
||||||
|
- не дублировать renderer;
|
||||||
|
- имя файла должно сохранять номер КС-3.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Формат ZIP
|
||||||
|
|
||||||
|
Рекомендуемая структура:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Комплект_Саудовская_Аравия_01.09.2026-30.09.2026.zip
|
||||||
|
├── КС-6а/
|
||||||
|
│ ├── КС-6а_01.09.2026-30.09.2026.xlsx
|
||||||
|
│ └── КС-6а_01.09.2026-30.09.2026.docx
|
||||||
|
├── КС-2/
|
||||||
|
│ ├── КС-2_№1_26.09.2026.xlsx
|
||||||
|
│ ├── КС-2_№1_26.09.2026.docx
|
||||||
|
│ └── ...
|
||||||
|
└── КС-3/
|
||||||
|
├── КС-3_№1_26.09.2026.xlsx
|
||||||
|
├── КС-3_№1_26.09.2026.docx
|
||||||
|
└── ...
|
||||||
|
```
|
||||||
|
|
||||||
|
В ZIP добавлять только реально выбранные форматы и существующие документы.
|
||||||
|
|
||||||
|
Не создавать пустые каталоги.
|
||||||
|
|
||||||
|
Русские имена файлов допустимы.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Если документов нет
|
||||||
|
|
||||||
|
Не считать это ошибкой.
|
||||||
|
|
||||||
|
Например, если за период есть КС-6а, но нет КС-2 и КС-3 — ZIP содержит только КС-6а.
|
||||||
|
|
||||||
|
Если вообще нет данных для выбранного состава:
|
||||||
|
- показать понятное сообщение пользователю;
|
||||||
|
- ZIP с пустым комплектом не создавать.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Финансовая приватность
|
||||||
|
|
||||||
|
Комплект документов содержит финансовые данные.
|
||||||
|
|
||||||
|
На текущем этапе отдельный экспортный ZIP не должен зависеть от eye icon.
|
||||||
|
|
||||||
|
Eye icon — только UI-механизм скрытия сумм на экране.
|
||||||
|
|
||||||
|
Экспорт должен содержать фактические данные документа независимо от состояния eye icon.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Архитектура
|
||||||
|
|
||||||
|
Не копировать существующую логику экспорта.
|
||||||
|
|
||||||
|
Использовать существующие:
|
||||||
|
- DTO;
|
||||||
|
- Excel renderer;
|
||||||
|
- Word renderer;
|
||||||
|
- `content_disposition`;
|
||||||
|
- `safe_export_filename` / helpers.
|
||||||
|
|
||||||
|
Добавить отдельный service/module для сборки комплекта, например:
|
||||||
|
|
||||||
|
```text
|
||||||
|
app/exporters/package_service.py
|
||||||
|
```
|
||||||
|
|
||||||
|
или эквивалентное место по текущей архитектуре.
|
||||||
|
|
||||||
|
Ответственности:
|
||||||
|
|
||||||
|
1. определить документы проекта, попадающие в период;
|
||||||
|
2. вызвать существующие export DTO/renderers;
|
||||||
|
3. собрать ZIP в памяти (`io.BytesIO` / `zipfile`);
|
||||||
|
4. вернуть готовый архив роутеру.
|
||||||
|
|
||||||
|
Не писать временные файлы на диск без необходимости.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Endpoint
|
||||||
|
|
||||||
|
Добавить отдельный endpoint уровня проекта, например:
|
||||||
|
|
||||||
|
```text
|
||||||
|
GET /projects/{project_id}/export/package
|
||||||
|
```
|
||||||
|
|
||||||
|
или POST, если это удобнее для формы.
|
||||||
|
|
||||||
|
Параметры:
|
||||||
|
- `date_from`;
|
||||||
|
- `date_to`;
|
||||||
|
- выбранные типы документов;
|
||||||
|
- выбранные форматы.
|
||||||
|
|
||||||
|
Ответ:
|
||||||
|
- `application/zip`;
|
||||||
|
- корректный `Content-Disposition`;
|
||||||
|
- безопасное имя файла.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Важные правила
|
||||||
|
|
||||||
|
- Только документы текущего проекта.
|
||||||
|
- Не допускать попадания документов другого проекта.
|
||||||
|
- Сторнированные КС-2/КС-3 не включать.
|
||||||
|
- Черновики КС-2/КС-3 не включать.
|
||||||
|
- КС-6а строится из фактических DailyReportItem и не зависит от статуса КС-2/КС-3.
|
||||||
|
- Не менять существующую бизнес-логику КС-2, КС-3, КС-6а.
|
||||||
|
- Не менять существующие индивидуальные export endpoints.
|
||||||
|
- Не реализовывать PDF.
|
||||||
|
- Не реализовывать email-отправку.
|
||||||
|
- Не реализовывать автоматическую отправку ZIP.
|
||||||
|
- Не добавлять платежи в комплект на этом этапе.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Тесты
|
||||||
|
|
||||||
|
Добавить тесты минимум на:
|
||||||
|
|
||||||
|
1. открытие формы/доступность package endpoint;
|
||||||
|
2. ZIP создаётся;
|
||||||
|
3. ZIP содержит КС-6а;
|
||||||
|
4. ZIP содержит КС-2;
|
||||||
|
5. ZIP содержит КС-3;
|
||||||
|
6. выбор только одного типа документов работает;
|
||||||
|
7. выбор только Excel работает;
|
||||||
|
8. выбор только Word работает;
|
||||||
|
9. Excel + Word даёт оба формата;
|
||||||
|
10. сторнированный КС-2 не попадает;
|
||||||
|
11. сторнированный КС-3 не попадает;
|
||||||
|
12. draft КС-2/КС-3 не попадает;
|
||||||
|
13. документы другого периода не попадают;
|
||||||
|
14. документы другого проекта не попадают;
|
||||||
|
15. пустой комплект корректно обрабатывается;
|
||||||
|
16. имя ZIP содержит проект и период;
|
||||||
|
17. существующие индивидуальные экспорты продолжают работать.
|
||||||
|
|
||||||
|
Проверить открытие содержимого ZIP хотя бы для одного Excel и одного Word файла.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. Что НЕ делать
|
||||||
|
|
||||||
|
Не делать в этой задаче:
|
||||||
|
- PDF;
|
||||||
|
- печать;
|
||||||
|
- email;
|
||||||
|
- электронную подпись;
|
||||||
|
- официальную типографскую форму;
|
||||||
|
- автоматическую отправку заказчику;
|
||||||
|
- платежные документы;
|
||||||
|
- сложный конструктор комплектов;
|
||||||
|
- переделку существующих renderer'ов без необходимости.
|
||||||
|
|
||||||
|
Это первая рабочая версия общего комплекта.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. Результат
|
||||||
|
|
||||||
|
После задачи пользователь должен иметь возможность:
|
||||||
|
|
||||||
|
1. открыть проект;
|
||||||
|
2. нажать «Комплект документов»;
|
||||||
|
3. выбрать период;
|
||||||
|
4. выбрать КС-6а / КС-2 / КС-3;
|
||||||
|
5. выбрать Excel / Word / оба;
|
||||||
|
6. нажать «Сформировать комплект»;
|
||||||
|
7. получить один ZIP, который можно сразу приложить к письму.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. Проверка
|
||||||
|
|
||||||
|
Перед завершением:
|
||||||
|
|
||||||
|
```text
|
||||||
|
python -m pytest -q
|
||||||
|
git diff --check
|
||||||
|
```
|
||||||
|
|
||||||
|
Подготовить implementation report:
|
||||||
|
|
||||||
|
```text
|
||||||
|
docs/implementation/019-document-package.md
|
||||||
|
```
|
||||||
|
|
||||||
|
Коммит и push в этой задаче **не выполнять без отдельной команды**.
|
||||||
@@ -0,0 +1,499 @@
|
|||||||
|
"""Regression tests for task 019: document package ZIP export."""
|
||||||
|
import datetime
|
||||||
|
import io
|
||||||
|
import shutil
|
||||||
|
import zipfile
|
||||||
|
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, 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 / "t019-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_project_package_data(Session):
|
||||||
|
"""One project with DailyReportItems, issued/draft/cancelled KS-2 and KS-3."""
|
||||||
|
with Session() as s:
|
||||||
|
p = Project(name="Саудовская Аравия", customer="Customer LLC", contract_number="DOG-019")
|
||||||
|
s.add(p)
|
||||||
|
s.flush()
|
||||||
|
other = Project(name="Other project", customer="Other")
|
||||||
|
s.add(other)
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||||||
|
s.add(doc)
|
||||||
|
s.flush()
|
||||||
|
other_doc = BoqDocument(project_id=other.id, name="BOQ other")
|
||||||
|
s.add(other_doc)
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Монтаж трубы",
|
||||||
|
source_number="1.1", unit="м", quantity=Decimal("100"),
|
||||||
|
unit_price=Decimal("50"), amount=Decimal("5000"))
|
||||||
|
other_wi = WorkItem(project_id=other.id, boq_document_id=other_doc.id, name="Чужая работа",
|
||||||
|
source_number="9.9", unit="шт", quantity=Decimal("10"),
|
||||||
|
unit_price=Decimal("1"), amount=Decimal("10"))
|
||||||
|
s.add_all([wi, other_wi])
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
dr = DailyReport(project_id=p.id, report_date=datetime.date(2026, 3, 10))
|
||||||
|
other_dr = DailyReport(project_id=other.id, report_date=datetime.date(2026, 3, 10))
|
||||||
|
s.add_all([dr, other_dr])
|
||||||
|
s.flush()
|
||||||
|
s.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("10")))
|
||||||
|
s.add(DailyReportItem(daily_report_id=other_dr.id, work_item_id=other_wi.id, completed_quantity=Decimal("5")))
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
period_from = datetime.date(2026, 3, 1)
|
||||||
|
period_to = datetime.date(2026, 3, 31)
|
||||||
|
|
||||||
|
ks2_ok = KS2(project_id=p.id, number="1", date=datetime.date(2026, 3, 20),
|
||||||
|
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks2_draft = KS2(project_id=p.id, number="2", date=datetime.date(2026, 3, 21),
|
||||||
|
status="draft", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks2_cancelled = KS2(project_id=p.id, number="3", date=datetime.date(2026, 3, 22),
|
||||||
|
status="cancelled", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks2_other_period = KS2(project_id=p.id, number="4", date=datetime.date(2026, 5, 1),
|
||||||
|
status="issued",
|
||||||
|
reporting_period_from=datetime.date(2026, 5, 1),
|
||||||
|
reporting_period_to=datetime.date(2026, 5, 31))
|
||||||
|
ks2_other_project = KS2(project_id=other.id, number="1", date=datetime.date(2026, 3, 20),
|
||||||
|
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
s.add_all([ks2_ok, ks2_draft, ks2_cancelled, ks2_other_period, ks2_other_project])
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
for ks2 in (ks2_ok, ks2_draft, ks2_cancelled, ks2_other_period, ks2_other_project):
|
||||||
|
item_wi = wi if ks2.project_id == p.id else other_wi
|
||||||
|
s.add(KS2Item(ks2_id=ks2.id, work_item_id=item_wi.id,
|
||||||
|
quantity=Decimal("5"), unit_price=Decimal("50"), amount=Decimal("250")))
|
||||||
|
s.flush()
|
||||||
|
|
||||||
|
ks3_ok = KS3(project_id=p.id, number="1", date=datetime.date(2026, 3, 25),
|
||||||
|
status="issued", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks3_draft = KS3(project_id=p.id, number="2", date=datetime.date(2026, 3, 26),
|
||||||
|
status="draft", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks3_cancelled = KS3(project_id=p.id, number="3", date=datetime.date(2026, 3, 27),
|
||||||
|
status="cancelled", reporting_period_from=period_from, reporting_period_to=period_to)
|
||||||
|
ks3_other_period = KS3(project_id=p.id, number="4", date=datetime.date(2026, 6, 1),
|
||||||
|
status="issued",
|
||||||
|
reporting_period_from=datetime.date(2026, 6, 1),
|
||||||
|
reporting_period_to=datetime.date(2026, 6, 30))
|
||||||
|
s.add_all([ks3_ok, ks3_draft, ks3_cancelled, ks3_other_period])
|
||||||
|
s.flush()
|
||||||
|
s.add(KS3KS2(ks3_id=ks3_ok.id, ks2_id=ks2_ok.id))
|
||||||
|
s.commit()
|
||||||
|
return {"pid": p.id, "other_pid": other.id}
|
||||||
|
|
||||||
|
|
||||||
|
PERIOD = "date_from=2026-03-01&date_to=2026-03-31"
|
||||||
|
ALL_DOCS = "include=ks6a&include=ks2&include=ks3"
|
||||||
|
|
||||||
|
|
||||||
|
def _package_url(pid, query=""):
|
||||||
|
base = f"/projects/{pid}/export/package?{PERIOD}"
|
||||||
|
return f"{base}&{query}" if query else base
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_namelist(resp):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
|
||||||
|
return zf.namelist()
|
||||||
|
|
||||||
|
|
||||||
|
def _zip_read(resp, name):
|
||||||
|
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
|
||||||
|
return zf.read(name)
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_form_available_on_project_page(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
page = client.get(f"/projects/{data['pid']}")
|
||||||
|
assert page.status_code == 200
|
||||||
|
assert "Комплект документов" in page.text
|
||||||
|
assert "/export/package" in page.text
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_endpoint_available(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert "application/zip" in resp.headers["content-type"]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_zip_created(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
|
||||||
|
assert zipfile.is_zipfile(io.BytesIO(resp.content))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert len(names) > 0
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_contains_ks6a(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks6a&format=both"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert any(n.startswith("КС-6а/") and n.endswith(".xlsx") for n in names)
|
||||||
|
assert any(n.startswith("КС-6а/") and n.endswith(".docx") for n in names)
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_contains_ks2(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
ks2_files = [n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx")]
|
||||||
|
assert len(ks2_files) == 1
|
||||||
|
assert "1" in ks2_files[0]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_contains_ks3(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks3&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
ks3_files = [n for n in names if n.startswith("КС-3/") and n.endswith(".xlsx")]
|
||||||
|
assert len(ks3_files) == 1
|
||||||
|
assert "1" in ks3_files[0]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_single_doc_type_only(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks6a&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert names
|
||||||
|
assert all(n.startswith("КС-6а/") for n in names)
|
||||||
|
assert not any(n.startswith("КС-2/") for n in names)
|
||||||
|
assert not any(n.startswith("КС-3/") for n in names)
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_excel_only(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert names
|
||||||
|
assert all(n.endswith(".xlsx") for n in names)
|
||||||
|
assert not any(n.endswith(".docx") for n in names)
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_word_only(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=word"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert names
|
||||||
|
assert all(n.endswith(".docx") for n in names)
|
||||||
|
assert not any(n.endswith(".xlsx") for n in names)
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_both_formats(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks6a&format=both"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert any(n.endswith(".xlsx") for n in names)
|
||||||
|
assert any(n.endswith(".docx") for n in names)
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_skips_cancelled_ks2(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
# Only issued #1; cancelled #3 must be absent
|
||||||
|
assert len(names) == 1
|
||||||
|
assert "_№1_" in names[0]
|
||||||
|
assert "_№3_" not in names[0]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_skips_cancelled_ks3(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks3&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert len(names) == 1
|
||||||
|
assert "_№1_" in names[0]
|
||||||
|
assert "_№3_" not in names[0]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_skips_draft_documents(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks2&include=ks3&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
basenames = [n.split("/")[-1] for n in names]
|
||||||
|
assert len(names) == 2 # issued KS-2 #1 + issued KS-3 #1
|
||||||
|
for name in basenames:
|
||||||
|
assert "_№2_" not in name # draft numbers
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_excludes_other_period(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks2&include=ks3&format=excel"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
basenames = [n.split("/")[-1] for n in names]
|
||||||
|
assert len(names) == 2
|
||||||
|
for name in basenames:
|
||||||
|
assert "_№4_" not in name # other-period numbers
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_excludes_other_project(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
|
||||||
|
with zipfile.ZipFile(io.BytesIO(resp.content)) as zf:
|
||||||
|
for name in zf.namelist():
|
||||||
|
payload = zf.read(name)
|
||||||
|
if name.endswith((".xlsx", ".docx")) and not name.startswith("КС-6а/"):
|
||||||
|
assert b"Other project" not in payload
|
||||||
|
if name.startswith("KS-2/") or name.startswith("KS-3/"):
|
||||||
|
raise AssertionError("unexpected")
|
||||||
|
# Also: other project's package must not contain this project's work
|
||||||
|
other_resp = client.get(_package_url(data["other_pid"], "include=ks2&format=excel"))
|
||||||
|
other_names = _zip_namelist(other_resp)
|
||||||
|
assert len(other_names) == 1
|
||||||
|
assert "9.9" not in other_names[0]
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_empty_composition(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
# No matching issued KS-2/KS-3 for this narrow window; KS-6a also empty
|
||||||
|
resp = client.get(
|
||||||
|
f"/projects/{data['pid']}/export/package"
|
||||||
|
f"?date_from=2026-07-01&date_to=2026-07-31&include=ks2&include=ks3&format=both"
|
||||||
|
)
|
||||||
|
assert resp.status_code == 400
|
||||||
|
assert "нет документов" in resp.json()["detail"].lower() or "нет документов" in resp.text.lower()
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_only_ks6a_still_builds_zip(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks6a&format=excel"))
|
||||||
|
assert resp.status_code == 200
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
assert len(names) == 1
|
||||||
|
assert names[0].startswith("КС-6а/")
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_filename_contains_project_and_period(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
|
||||||
|
disposition = resp.headers["content-disposition"]
|
||||||
|
assert "01.03.2026-31.03.2026" in disposition
|
||||||
|
assert "Саудовская" in disposition or "filename" in disposition
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_members_openable(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], f"{ALL_DOCS}&format=both"))
|
||||||
|
names = _zip_namelist(resp)
|
||||||
|
excel_name = next(n for n in names if n.startswith("КС-2/") and n.endswith(".xlsx"))
|
||||||
|
word_name = next(n for n in names if n.startswith("КС-3/") and n.endswith(".docx"))
|
||||||
|
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
wb = load_workbook(io.BytesIO(_zip_read(resp, excel_name)))
|
||||||
|
assert wb.active is not None
|
||||||
|
text = "\n".join(
|
||||||
|
str(cell.value) for row in wb.active.iter_rows() for cell in row if cell.value is not None
|
||||||
|
)
|
||||||
|
assert "Монтаж трубы" in text
|
||||||
|
|
||||||
|
from docx import Document
|
||||||
|
d = Document(io.BytesIO(_zip_read(resp, word_name)))
|
||||||
|
assert len(d.tables) > 0
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_package_includes_money_regardless_of_privacy(tmp_path):
|
||||||
|
"""ZIP contains real amounts; eye icon is UI-only."""
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get(_package_url(data["pid"], "include=ks2&format=excel"))
|
||||||
|
name = _zip_namelist(resp)[0]
|
||||||
|
from openpyxl import load_workbook
|
||||||
|
wb = load_workbook(io.BytesIO(_zip_read(resp, name)))
|
||||||
|
text = "\n".join(
|
||||||
|
str(cell.value) for row in wb.active.iter_rows() for cell in row if cell.value is not None
|
||||||
|
)
|
||||||
|
assert "250" in text # KS-2 amount present
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_individual_exports_still_work(tmp_path):
|
||||||
|
engine, Session = _make_session(tmp_path)
|
||||||
|
_override(Session)
|
||||||
|
try:
|
||||||
|
data = _create_project_package_data(Session)
|
||||||
|
with Session() as s:
|
||||||
|
ks2_id = s.query(KS2).filter(KS2.project_id == data["pid"], KS2.number == "1").one().id
|
||||||
|
ks3_id = s.query(KS3).filter(KS3.project_id == data["pid"], KS3.number == "1").one().id
|
||||||
|
with TestClient(app) as client:
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks2/{ks2_id}/export/excel").status_code == 200
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks2/{ks2_id}/export/word").status_code == 200
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks3/{ks3_id}/export/excel").status_code == 200
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks3/{ks3_id}/export/word").status_code == 200
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks6a/export/excel?{PERIOD}").status_code == 200
|
||||||
|
assert client.get(f"/projects/{data['pid']}/ks6a/export/word?{PERIOD}").status_code == 200
|
||||||
|
finally:
|
||||||
|
_clear()
|
||||||
|
engine.dispose()
|
||||||
Reference in New Issue
Block a user