feat: add official artifact download endpoints and UI for KS-2/KS-3
This commit is contained in:
@@ -195,6 +195,39 @@ def _content_disposition(filename: str) -> str:
|
||||
return content_disposition(filename)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks2/{ks2_id}/artifact")
|
||||
async def ks2_download_artifact(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||
"""Download the official issued artifact (stored file, no re-render)."""
|
||||
from app.exporters import content_disposition, safe_export_filename
|
||||
from app.services.document_artifact_service import (
|
||||
ArtifactHashMismatchError,
|
||||
ArtifactNotFoundError,
|
||||
resolve_artifact,
|
||||
)
|
||||
|
||||
document = _document(db, project_id, ks2_id)
|
||||
if document.status == "draft":
|
||||
raise HTTPException(status_code=409, detail="Официальная форма доступна только после проведения КС-2")
|
||||
try:
|
||||
artifact, content = resolve_artifact(
|
||||
db,
|
||||
project_id=project_id,
|
||||
document_type="KS2",
|
||||
document_id=ks2_id,
|
||||
format="xlsx",
|
||||
)
|
||||
except ArtifactNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail="Официальная форма недоступна: файл документа не найден.") from exc
|
||||
except ArtifactHashMismatchError as exc:
|
||||
raise HTTPException(status_code=500, detail="Файл документа повреждён и не может быть выдан.") from exc
|
||||
filename = safe_export_filename("КС-2", document.number, document.date, "xlsx")
|
||||
return Response(
|
||||
content=content,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": content_disposition(filename)},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks2/{ks2_id}/export/excel")
|
||||
async def ks2_export_excel(project_id: int, ks2_id: int, db: Session = Depends(get_db)):
|
||||
document = _document(db, project_id, ks2_id)
|
||||
|
||||
@@ -191,6 +191,39 @@ async def ks3_cancel(project_id: int, ks3_id: int, db: Session = Depends(get_db)
|
||||
return RedirectResponse(f"/projects/{project_id}/ks3/{ks3_id}", status_code=303)
|
||||
|
||||
|
||||
@router.get("/{project_id}/ks3/{ks3_id}/artifact")
|
||||
async def ks3_download_artifact(project_id: int, ks3_id: int, db: Session = Depends(get_db)):
|
||||
"""Download the official issued artifact (stored file, no re-render)."""
|
||||
from app.exporters import content_disposition, safe_export_filename
|
||||
from app.services.document_artifact_service import (
|
||||
ArtifactHashMismatchError,
|
||||
ArtifactNotFoundError,
|
||||
resolve_artifact,
|
||||
)
|
||||
|
||||
document = _document(db, project_id, ks3_id)
|
||||
if document.status == "draft":
|
||||
raise HTTPException(status_code=409, detail="Официальная форма доступна только после проведения КС-3")
|
||||
try:
|
||||
artifact, content = resolve_artifact(
|
||||
db,
|
||||
project_id=project_id,
|
||||
document_type="KS3",
|
||||
document_id=ks3_id,
|
||||
format="docx",
|
||||
)
|
||||
except ArtifactNotFoundError as exc:
|
||||
raise HTTPException(status_code=404, detail="Официальная форма недоступна: файл документа не найден.") from exc
|
||||
except ArtifactHashMismatchError as exc:
|
||||
raise HTTPException(status_code=500, detail="Файл документа повреждён и не может быть выдан.") from exc
|
||||
filename = safe_export_filename("КС-3", document.number, document.date, "docx")
|
||||
return Response(
|
||||
content=content,
|
||||
media_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||||
headers={"Content-Disposition": content_disposition(filename)},
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
|
||||
@@ -32,6 +32,12 @@
|
||||
<div class="mt-2">
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/excel" class="btn btn-outline-success btn-sm">📊 Excel</a>
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/export/word" class="btn btn-outline-primary btn-sm">📄 Word</a>
|
||||
{% if document.status != 'draft' %}
|
||||
<a href="/projects/{{ project.id }}/ks2/{{ document.id }}/artifact" class="btn btn-outline-dark btn-sm">
|
||||
📎 Официальная форма (Excel)
|
||||
{% if document.status == 'cancelled' %}<span class="badge bg-danger ms-1">СТОРНИРОВАН</span>{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -32,6 +32,12 @@
|
||||
<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>
|
||||
{% if document.status != 'draft' %}
|
||||
<a href="/projects/{{ project.id }}/ks3/{{ document.id }}/artifact" class="btn btn-outline-dark btn-sm">
|
||||
📎 Официальная форма (Word)
|
||||
{% if document.status == 'cancelled' %}<span class="badge bg-danger ms-1">СТОРНИРОВАН</span>{% endif %}
|
||||
</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Implementation Report — DOC-B6-artifact-download-ui
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### Changed files
|
||||
|
||||
| Файл | Что |
|
||||
|---|---|
|
||||
| `app/routers/ks2.py` | endpoint `GET /{project_id}/ks2/{ks2_id}/artifact` |
|
||||
| `app/routers/ks3.py` | endpoint `GET /{project_id}/ks3/{ks3_id}/artifact` |
|
||||
| `app/templates/ks2/view.html` | кнопка «Официальная форма (Excel)» + badge «СТОРНИРОВАН» |
|
||||
| `app/templates/ks3/view.html` | кнопка «Официальная форма (Word)» + badge «СТОРНИРОВАН» |
|
||||
| `tests/test_doc_b6_artifact_download.py` | 16 тестов |
|
||||
|
||||
### Endpoints
|
||||
|
||||
```
|
||||
GET /projects/{project_id}/ks2/{ks2_id}/artifact → XLSX
|
||||
GET /projects/{project_id}/ks3/{ks3_id}/artifact → DOCX
|
||||
```
|
||||
|
||||
### Поведение Draft / Issued / Cancelled
|
||||
|
||||
| Статус | UI | Endpoint |
|
||||
|---|---|---|
|
||||
| **Draft** | кнопка скрыта | 409 «доступна только после проведения» |
|
||||
| **Issued** | «Официальная форма (Excel/Word)» | отдаёт сохранённый artifact |
|
||||
| **Cancelled** | кнопка + badge **СТОРНИРОВАН** | отдаёт **тот же** оригинальный artifact |
|
||||
|
||||
### Hash verification
|
||||
|
||||
Используется существующий `resolve_artifact()` (DOC-B2) с `verify_hash=True`:
|
||||
- hash mismatch → HTTP 500 «Файл документа повреждён…», файл не отдаётся;
|
||||
- никакой автоматической перегенерации.
|
||||
|
||||
### Отсутствующий / повреждённый artifact
|
||||
|
||||
| Случай | Ответ |
|
||||
|---|---|
|
||||
| Нет artifact / нет файла | 404 «Официальная форма недоступна: файл документа не найден.» |
|
||||
| Hash mismatch | 500 «Файл документа повреждён и не может быть выдан.» |
|
||||
| Draft | 409 |
|
||||
| Путь не раскрывается | да |
|
||||
|
||||
### Security / cross-project
|
||||
|
||||
1. `project_id` существует (`_project`);
|
||||
2. документ существует и принадлежит проекту (`_document`);
|
||||
3. artifact резолвится через `resolve_artifact` (project-scoped);
|
||||
4. `storage_key` не принимается от пользователя;
|
||||
5. path traversal невозможен (DOC-B2 `resolve_storage_path`);
|
||||
6. hash проверяется перед отдачей.
|
||||
|
||||
### Тесты (16)
|
||||
|
||||
KS-2: issued download + bytes, MIME, Content-Disposition, неизменность artifact, cancelled → тот же файл, draft → 409, missing → 404, hash mismatch → 500, cross-project → 404.
|
||||
KS-3: аналогично (issued/cancelled/draft/missing/cross-project).
|
||||
UI: кнопка только для non-draft, «СТОРНИРОВАН» для cancelled, существующие export работают.
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
430 passed, 648 warnings in 32.37s
|
||||
```
|
||||
|
||||
(414 существующих + 16 новых.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок)
|
||||
```
|
||||
|
||||
### Browser/manual checks
|
||||
|
||||
Playwright, реальный проект. **13/13 passed.**
|
||||
|
||||
| Проверка | KS-2 | KS-3 |
|
||||
|---|---|---|
|
||||
| Draft — кнопка скрыта | ✓ | — |
|
||||
| Issued — кнопка видна | ✓ | ✓ |
|
||||
| Скачивание запускается | ✓ (.xlsx) | ✓ (.docx) |
|
||||
| Имя файла корректное | `КС-2 №… .xlsx` | `КС-3 №… .docx` |
|
||||
| Cancelled — «СТОРНИРОВАН» | ✓ | — |
|
||||
| Cancelled — скачивание | ✓ | — |
|
||||
| Существующий export работает | ✓ | — |
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Recommended next task
|
||||
|
||||
**DOC-B7** — Project Export/Import: включение artifacts в `.wvt.zip`, remap, валидация при import.
|
||||
@@ -0,0 +1,526 @@
|
||||
# DOC-B6 — UI и безопасное скачивание DocumentArtifact
|
||||
|
||||
## Цель
|
||||
|
||||
Добавить пользовательский доступ к уже созданным `DocumentArtifact` для KS-2 и KS-3.
|
||||
|
||||
После задачи пользователь должен из карточки документа скачать официальную форму, которая была создана при выпуске документа.
|
||||
|
||||
Ключевой принцип:
|
||||
|
||||
```text
|
||||
Draft
|
||||
→ artifact может отсутствовать
|
||||
→ обычный export может работать по существующим механизмам
|
||||
|
||||
Issued
|
||||
→ artifact создан при issue
|
||||
→ UI скачивает именно сохранённый artifact
|
||||
→ повторного render нет
|
||||
|
||||
Cancelled
|
||||
→ оригинальный issued artifact сохраняется
|
||||
→ UI скачивает тот же оригинальный файл
|
||||
→ отдельный СТОРНИРОВАН derivative в DOC-B6 НЕ генерируется
|
||||
```
|
||||
|
||||
DOC-B6 не меняет lifecycle из DOC-B5.
|
||||
|
||||
---
|
||||
|
||||
# 1. Изучить перед реализацией
|
||||
|
||||
Прочитать:
|
||||
|
||||
- `app/models/document_artifact.py`
|
||||
- `app/services/document_artifact_service.py`
|
||||
- `app/services/ks2_service.py`
|
||||
- `app/services/ks3_service.py`
|
||||
- существующие KS-2/KS-3 routers
|
||||
- существующие карточки/шаблоны KS-2 и KS-3
|
||||
- существующие export endpoints
|
||||
- `app/templates_docs/ks2/`
|
||||
- `app/templates_docs/ks3/`
|
||||
- тесты DOC-B5.
|
||||
|
||||
Не создавать второй механизм хранения или рендеринга документов.
|
||||
|
||||
---
|
||||
|
||||
# 2. UI KS-2
|
||||
|
||||
На карточке KS-2 добавить действие:
|
||||
|
||||
**«Официальная форма»**
|
||||
|
||||
Поведение:
|
||||
|
||||
### Draft
|
||||
|
||||
Если KS-2 ещё не issued:
|
||||
|
||||
- официального immutable artifact может не быть;
|
||||
- кнопка не должна пытаться скачать несуществующий issued artifact.
|
||||
|
||||
Допустимый вариант:
|
||||
|
||||
- скрыть кнопку для draft;
|
||||
- существующие Excel/Word export оставить без изменений, если они уже есть.
|
||||
|
||||
Предпочтительно именно скрывать «Официальная форма» для draft.
|
||||
|
||||
### Issued
|
||||
|
||||
Показать:
|
||||
|
||||
**Официальная форма (Excel)**
|
||||
|
||||
Кнопка скачивает сохранённый `DocumentArtifact`.
|
||||
|
||||
При скачивании:
|
||||
|
||||
- не вызывается renderer;
|
||||
- не создаётся новый artifact;
|
||||
- не изменяется `is_current`;
|
||||
- не меняются hash;
|
||||
- не создаётся новая версия файла.
|
||||
|
||||
### Cancelled
|
||||
|
||||
Показать:
|
||||
|
||||
**Официальная форма (Excel)**
|
||||
|
||||
С дополнительной визуальной пометкой:
|
||||
|
||||
**СТОРНИРОВАН**
|
||||
|
||||
Но скачивается именно исходный artifact, созданный при issue.
|
||||
|
||||
Не создавать новый файл и не изменять исходный.
|
||||
|
||||
---
|
||||
|
||||
# 3. UI KS-3
|
||||
|
||||
Аналогично:
|
||||
|
||||
### Issued
|
||||
|
||||
**Официальная форма (Word)**
|
||||
|
||||
Скачивается сохранённый DOCX artifact.
|
||||
|
||||
### Cancelled
|
||||
|
||||
Показывать:
|
||||
|
||||
**Официальная форма (Word)**
|
||||
|
||||
+ визуальную пометку:
|
||||
|
||||
**СТОРНИРОВАН**
|
||||
|
||||
Но файл остаётся исходным issued artifact.
|
||||
|
||||
### Draft
|
||||
|
||||
«Официальная форма» скрыта.
|
||||
|
||||
Существующий обычный export не ломать.
|
||||
|
||||
---
|
||||
|
||||
# 4. Download endpoint
|
||||
|
||||
Добавить отдельные endpoints для artifact download.
|
||||
|
||||
Рекомендуемый вид:
|
||||
|
||||
```text
|
||||
GET /projects/{project_id}/ks2/{ks2_id}/artifact
|
||||
GET /projects/{project_id}/ks3/{ks3_id}/artifact
|
||||
```
|
||||
|
||||
или эквивалентный существующему стилю проекта вариант.
|
||||
|
||||
Важно: endpoint должен работать только в контексте указанного проекта.
|
||||
|
||||
Нельзя получить artifact другого проекта, подставив чужой `document_id`.
|
||||
|
||||
---
|
||||
|
||||
# 5. Безопасность
|
||||
|
||||
Endpoint обязан проверить:
|
||||
|
||||
1. `project_id` существует;
|
||||
2. документ существует;
|
||||
3. документ принадлежит указанному проекту;
|
||||
4. существует artifact именно для этого:
|
||||
- `document_type`;
|
||||
- `document_id`;
|
||||
- ожидаемого `format`;
|
||||
5. artifact корректно разрешается через `document_artifact_service`;
|
||||
6. файл существует;
|
||||
7. hash файла проходит существующую проверку DOC-B2.
|
||||
|
||||
Не передавать пользователем filesystem path.
|
||||
|
||||
Не принимать `storage_key` из query/path как путь к файлу.
|
||||
|
||||
Путь должен определяться исключительно сервером через `DocumentArtifact`.
|
||||
|
||||
Не использовать `send_file(user_supplied_path)`.
|
||||
|
||||
---
|
||||
|
||||
# 6. Как выбирать artifact
|
||||
|
||||
Для KS-2:
|
||||
|
||||
```text
|
||||
document_type = KS2
|
||||
document_id = ks2.id
|
||||
format = xlsx
|
||||
```
|
||||
|
||||
Для KS-3:
|
||||
|
||||
```text
|
||||
document_type = KS3
|
||||
document_id = ks3.id
|
||||
format = docx
|
||||
```
|
||||
|
||||
Использовать существующий:
|
||||
|
||||
```python
|
||||
resolve_artifact(...)
|
||||
```
|
||||
|
||||
или соответствующий метод DOC-B2.
|
||||
|
||||
Не писать собственный поиск файлов.
|
||||
|
||||
---
|
||||
|
||||
# 7. Current / historical
|
||||
|
||||
Для обычного скачивания использовать текущий artifact.
|
||||
|
||||
После DOC-B5:
|
||||
|
||||
- issued document → current official artifact;
|
||||
- cancelled document → тот же current official artifact.
|
||||
|
||||
Не искать последний файл по имени или timestamp.
|
||||
|
||||
Не выбирать artifact через `ORDER BY id DESC` как замену `is_current`.
|
||||
|
||||
---
|
||||
|
||||
# 8. Hash verification
|
||||
|
||||
Перед отдачей файла использовать существующую проверку DOC-B2.
|
||||
|
||||
Если hash не совпадает:
|
||||
|
||||
- не отдавать повреждённый файл;
|
||||
- вернуть контролируемую HTTP-ошибку;
|
||||
- записать понятную серверную ошибку в лог.
|
||||
|
||||
Не пытаться автоматически перегенерировать документ.
|
||||
|
||||
Особенно важно для issued/cancelled:
|
||||
|
||||
```text
|
||||
hash mismatch
|
||||
≠
|
||||
rerender
|
||||
```
|
||||
|
||||
Файл считается повреждённым и требует отдельного восстановления.
|
||||
|
||||
---
|
||||
|
||||
# 9. HTTP ошибки
|
||||
|
||||
Предусмотреть понятные ответы:
|
||||
|
||||
### 404
|
||||
|
||||
- проект не найден;
|
||||
- документ не найден в проекте;
|
||||
- artifact отсутствует.
|
||||
|
||||
### 409 или 422
|
||||
|
||||
Допустимо использовать для некорректного lifecycle, например если draft пытается обратиться к official artifact.
|
||||
|
||||
Конкретный статус выбрать в соответствии с существующим стилем приложения.
|
||||
|
||||
### 500
|
||||
|
||||
Только для реальной внутренней ошибки.
|
||||
|
||||
Не раскрывать filesystem path пользователю.
|
||||
|
||||
---
|
||||
|
||||
# 10. Content-Disposition / имя файла
|
||||
|
||||
Использовать существующие helpers из:
|
||||
|
||||
```text
|
||||
app/exporters/__init__.py
|
||||
```
|
||||
|
||||
Если там уже есть:
|
||||
|
||||
- `safe_export_filename()`
|
||||
- `content_disposition()`
|
||||
|
||||
использовать их, а не создавать второй вариант.
|
||||
|
||||
Имя должно быть человекочитаемым.
|
||||
|
||||
Например:
|
||||
|
||||
```text
|
||||
КС-2 №12 от 29.09.2026.xlsx
|
||||
КС-3 №7 от 29.09.2026.docx
|
||||
```
|
||||
|
||||
Фактический формат имени согласовать с существующей системой export filenames.
|
||||
|
||||
Не допускать path traversal.
|
||||
|
||||
---
|
||||
|
||||
# 11. MIME types
|
||||
|
||||
Использовать правильные MIME:
|
||||
|
||||
### XLSX
|
||||
|
||||
```text
|
||||
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
|
||||
```
|
||||
|
||||
### DOCX
|
||||
|
||||
```text
|
||||
application/vnd.openxmlformats-officedocument.wordprocessingml.document
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
# 12. Existing exports
|
||||
|
||||
Не ломать существующие endpoints:
|
||||
|
||||
```text
|
||||
/export/excel
|
||||
/export/word
|
||||
```
|
||||
|
||||
если они уже существуют.
|
||||
|
||||
Разница:
|
||||
|
||||
### Existing export
|
||||
|
||||
```text
|
||||
DTO → renderer → download
|
||||
```
|
||||
|
||||
### Official artifact
|
||||
|
||||
```text
|
||||
stored artifact → hash check → download
|
||||
```
|
||||
|
||||
После DOC-B6 UI должен ясно различать эти два действия.
|
||||
|
||||
---
|
||||
|
||||
# 13. UI текст
|
||||
|
||||
Для issued:
|
||||
|
||||
```text
|
||||
Официальная форма
|
||||
```
|
||||
|
||||
или:
|
||||
|
||||
```text
|
||||
Официальная форма (Excel)
|
||||
```
|
||||
|
||||
/
|
||||
|
||||
```text
|
||||
Официальная форма (Word)
|
||||
```
|
||||
|
||||
Для cancelled рядом:
|
||||
|
||||
```text
|
||||
СТОРНИРОВАН
|
||||
```
|
||||
|
||||
Важно: это UI-индикация статуса документа, а не генерация нового файла.
|
||||
|
||||
Не добавлять watermark в файл на этом этапе.
|
||||
|
||||
---
|
||||
|
||||
# 14. Artifact отсутствует
|
||||
|
||||
Если документ уже issued, но artifact отсутствует:
|
||||
|
||||
- UI не должен показывать успешную ссылку на несуществующий файл;
|
||||
- endpoint должен вернуть контролируемую ошибку;
|
||||
- не выполнять автоматический render.
|
||||
|
||||
Можно показать пользователю:
|
||||
|
||||
```text
|
||||
Официальная форма недоступна: файл документа не найден.
|
||||
```
|
||||
|
||||
Но не показывать внутренний storage path.
|
||||
|
||||
---
|
||||
|
||||
# 15. Artifact повреждён
|
||||
|
||||
Если `resolve_artifact()` обнаруживает hash mismatch:
|
||||
|
||||
- HTTP ошибка;
|
||||
- понятное сообщение пользователю;
|
||||
- запись в лог;
|
||||
- никакого автоматического regeneration.
|
||||
|
||||
---
|
||||
|
||||
# 16. Тесты
|
||||
|
||||
Добавить минимум следующие тесты.
|
||||
|
||||
## KS-2
|
||||
|
||||
1. issued KS-2 → download XLSX;
|
||||
2. downloaded bytes совпадают с сохранённым artifact;
|
||||
3. content type корректный;
|
||||
4. Content-Disposition корректный;
|
||||
5. cancelled KS-2 → скачивается тот же artifact;
|
||||
6. draft KS-2 → official artifact endpoint отклоняется/404;
|
||||
7. artifact отсутствует → контролируемая ошибка;
|
||||
8. hash mismatch → файл не отдается;
|
||||
9. чужой `project_id` → artifact недоступен;
|
||||
10. чужой `ks2_id` из другого проекта → недоступен;
|
||||
11. download не меняет `is_current`;
|
||||
12. download не создаёт новый artifact.
|
||||
|
||||
## KS-3
|
||||
|
||||
Аналогичные проверки:
|
||||
|
||||
1. issued → DOCX;
|
||||
2. bytes совпадают;
|
||||
3. MIME;
|
||||
4. Content-Disposition;
|
||||
5. cancelled;
|
||||
6. draft;
|
||||
7. отсутствующий artifact;
|
||||
8. hash mismatch;
|
||||
9. cross-project access;
|
||||
10. отсутствие изменений artifact после download.
|
||||
|
||||
---
|
||||
|
||||
# 17. Browser/manual check
|
||||
|
||||
Проверить минимум:
|
||||
|
||||
### KS-2
|
||||
|
||||
- Draft;
|
||||
- Issued;
|
||||
- Cancelled.
|
||||
|
||||
### KS-3
|
||||
|
||||
- Draft;
|
||||
- Issued;
|
||||
- Cancelled.
|
||||
|
||||
Проверить:
|
||||
|
||||
- кнопка видна только там, где должна;
|
||||
- скачивание запускается;
|
||||
- имя файла корректное;
|
||||
- cancelled визуально имеет `СТОРНИРОВАН`;
|
||||
- после скачивания документ и artifact не изменились.
|
||||
|
||||
---
|
||||
|
||||
# 18. Не делать
|
||||
|
||||
В DOC-B6 НЕ реализовывать:
|
||||
|
||||
- генерацию `СТОРНИРОВАН` derivative;
|
||||
- watermark в существующий файл;
|
||||
- перегенерацию issued документов;
|
||||
- изменение шаблонов;
|
||||
- новый artifact при каждом download;
|
||||
- PDF;
|
||||
- export/import;
|
||||
- database reset;
|
||||
- удаление физических файлов;
|
||||
- новую систему авторизации.
|
||||
|
||||
---
|
||||
|
||||
# 19. Acceptance criteria
|
||||
|
||||
- [ ] KS-2 issued имеет кнопку «Официальная форма».
|
||||
- [ ] KS-3 issued имеет кнопку «Официальная форма».
|
||||
- [ ] Draft не предлагает official artifact.
|
||||
- [ ] Cancelled показывает статус `СТОРНИРОВАН`.
|
||||
- [ ] Cancelled скачивает оригинальный issued artifact.
|
||||
- [ ] Download не вызывает renderer.
|
||||
- [ ] Download не создаёт новый artifact.
|
||||
- [ ] Download не меняет `is_current`.
|
||||
- [ ] Hash проверяется перед отдачей.
|
||||
- [ ] Hash mismatch не отдаёт файл.
|
||||
- [ ] Cross-project access невозможен.
|
||||
- [ ] Filesystem path не принимается от пользователя.
|
||||
- [ ] MIME корректный.
|
||||
- [ ] Content-Disposition безопасный.
|
||||
- [ ] Существующие export endpoints не сломаны.
|
||||
- [ ] Полный pytest проходит.
|
||||
- [ ] `git diff --check` чистый.
|
||||
- [ ] Browser/manual checks выполнены.
|
||||
|
||||
---
|
||||
|
||||
# 20. Implementation report
|
||||
|
||||
После выполнения предоставить:
|
||||
|
||||
1. изменённые файлы;
|
||||
2. endpoints;
|
||||
3. поведение Draft / Issued / Cancelled;
|
||||
4. способ проверки hash;
|
||||
5. поведение при отсутствующем/повреждённом artifact;
|
||||
6. security/cross-project checks;
|
||||
7. тесты и итоговое количество;
|
||||
8. browser/manual checks;
|
||||
9. deviations, если есть;
|
||||
10. рекомендацию по следующей задаче.
|
||||
|
||||
Не менять несвязанные части проекта.
|
||||
@@ -0,0 +1,378 @@
|
||||
"""Tests for DOC-B6: artifact download UI and endpoints."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.config import ENV_DOCUMENT_STORAGE_ROOT
|
||||
from app.database.database import Base
|
||||
from app.main import app
|
||||
from app.models import ( # noqa: F401
|
||||
agreement, boq, daily_report, document_artifact,
|
||||
ks2 as ks2_models, ks3 as ks3_models, payment, project, work_journal,
|
||||
)
|
||||
from app.models.boq import BoqDocument, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.document_artifact import DocumentArtifact
|
||||
from app.models.ks2 import KS2
|
||||
from app.models.ks3 import KS3
|
||||
from app.models.project import Project
|
||||
from app.routers import ks2 as ks2_router, ks3 as ks3_router
|
||||
from app.services.document_artifact_service import (
|
||||
compute_content_hash,
|
||||
persist_artifact,
|
||||
resolve_storage_path,
|
||||
)
|
||||
from app.services.ks2_service import cancel_ks2, issue_ks2, save_draft as save_ks2_draft
|
||||
from app.services.ks3_service import cancel_ks3, issue_ks3, save_draft as save_ks3_draft
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def storage_root(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv(ENV_DOCUMENT_STORAGE_ROOT, str(tmp_path / "b6-storage"))
|
||||
return tmp_path / "b6-storage"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session(storage_root):
|
||||
engine = create_engine("sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool)
|
||||
Base.metadata.create_all(engine)
|
||||
Session = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
session = Session()
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
session.close()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ctx(db_session):
|
||||
"""Project + work item + DR so KS-2 can be issued."""
|
||||
p = Project(name="B6 project")
|
||||
db_session.add(p)
|
||||
db_session.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ")
|
||||
db_session.add(doc)
|
||||
db_session.flush()
|
||||
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="Item", unit="шт",
|
||||
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"))
|
||||
db_session.add(wi)
|
||||
db_session.flush()
|
||||
dr = DailyReport(project_id=p.id, report_date=date(2026, 2, 1))
|
||||
db_session.add(dr)
|
||||
db_session.flush()
|
||||
db_session.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("50")))
|
||||
db_session.commit()
|
||||
return {"project_id": p.id, "work_item_id": wi.id}
|
||||
|
||||
|
||||
def _client(Session):
|
||||
def override():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
app.dependency_overrides[ks2_router.get_db] = override
|
||||
app.dependency_overrides[ks3_router.get_db] = override
|
||||
from app.routers import projects as project_router
|
||||
app.dependency_overrides[project_router.get_db] = override
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
from fastapi.testclient import TestClient # noqa: E402
|
||||
|
||||
|
||||
def _clear():
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
def _make_issued_ks2(db, ctx, number="K2-B6"):
|
||||
draft = save_ks2_draft(db, ctx["project_id"], number, date(2026, 3, 1), None,
|
||||
[(ctx["work_item_id"], Decimal("10"))],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
return issue_ks2(db, ctx["project_id"], draft.id)
|
||||
|
||||
|
||||
def _make_issued_ks3(db, ctx, ks2, number="K3-B6"):
|
||||
draft = save_ks3_draft(db, ctx["project_id"], number, date(2026, 4, 1), None,
|
||||
[ks2.id],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
return issue_ks3(db, ctx["project_id"], draft.id)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# KS-2
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ks2_issued_download_xlsx(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.document_id == ks2.id,
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/artifact")
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == stored
|
||||
assert "spreadsheetml" in resp.headers["content-type"]
|
||||
assert "attachment" in resp.headers["content-disposition"]
|
||||
assert ".xlsx" in resp.headers["content-disposition"]
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_download_does_not_mutate_artifact(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
art_id, is_current, ch, ih = art.id, art.is_current, art.content_hash, art.input_hash
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/artifact")
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
art = db_session.get(DocumentArtifact, art_id)
|
||||
assert art.is_current == is_current
|
||||
assert art.content_hash == ch
|
||||
assert art.input_hash == ih
|
||||
count = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2")).all()
|
||||
assert len(count) == 1
|
||||
|
||||
|
||||
def test_ks2_cancelled_download_same_artifact(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
cancel_ks2(db_session, ctx["project_id"], ks2.id)
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/artifact")
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == stored
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_draft_artifact_rejected(storage_root, db_session, ctx):
|
||||
draft = save_ks2_draft(db_session, ctx["project_id"], "K2-D", date(2026, 3, 1), None,
|
||||
[(ctx["work_item_id"], Decimal("10"))],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{draft.id}/artifact")
|
||||
assert resp.status_code == 409
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_missing_artifact_404(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
# Delete the physical file
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
resolve_storage_path(art.storage_key).unlink()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/artifact")
|
||||
assert resp.status_code == 404
|
||||
assert "недоступна" in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_hash_mismatch_not_served(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS2", DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
path = resolve_storage_path(art.storage_key)
|
||||
path.write_bytes(b"tampered")
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/artifact")
|
||||
assert resp.status_code == 500
|
||||
assert b"tampered" not in resp.content
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_cross_project_rejected(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
other = Project(name="Other")
|
||||
db_session.add(other)
|
||||
db_session.commit()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
# Wrong project id
|
||||
resp = client.get(f"/projects/{other.id}/ks2/{ks2.id}/artifact")
|
||||
assert resp.status_code == 404
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# KS-3
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ks3_issued_download_docx(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
ks3 = _make_issued_ks3(db_session, ctx, ks2)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS3",
|
||||
DocumentArtifact.document_id == ks3.id,
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks3/{ks3.id}/artifact")
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == stored
|
||||
assert "wordprocessingml" in resp.headers["content-type"]
|
||||
assert ".docx" in resp.headers["content-disposition"]
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks3_cancelled_download_same_artifact(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
ks3 = _make_issued_ks3(db_session, ctx, ks2)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS3",
|
||||
DocumentArtifact.is_current.is_(True),
|
||||
)).scalar_one()
|
||||
stored = resolve_storage_path(art.storage_key).read_bytes()
|
||||
cancel_ks3(db_session, ctx["project_id"], ks3.id)
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks3/{ks3.id}/artifact")
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == stored
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks3_draft_artifact_rejected(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
draft = save_ks3_draft(db_session, ctx["project_id"], "K3-D", date(2026, 4, 1), None,
|
||||
[ks2.id],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks3/{draft.id}/artifact")
|
||||
assert resp.status_code == 409
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks3_missing_artifact_404(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
ks3 = _make_issued_ks3(db_session, ctx, ks2)
|
||||
art = db_session.execute(select(DocumentArtifact).where(
|
||||
DocumentArtifact.document_type == "KS3", DocumentArtifact.is_current.is_(True))).scalar_one()
|
||||
resolve_storage_path(art.storage_key).unlink()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks3/{ks3.id}/artifact")
|
||||
assert resp.status_code == 404
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks3_cross_project_rejected(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
ks3 = _make_issued_ks3(db_session, ctx, ks2)
|
||||
other = Project(name="Other2")
|
||||
db_session.add(other)
|
||||
db_session.commit()
|
||||
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{other.id}/ks3/{ks3.id}/artifact")
|
||||
assert resp.status_code == 404
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# UI visibility
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_ks2_ui_shows_official_button_only_non_draft(storage_root, db_session, ctx):
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
# Draft: no official button
|
||||
draft = save_ks2_draft(db_session, ctx["project_id"], "K2-UI", date(2026, 3, 1), None,
|
||||
[(ctx["work_item_id"], Decimal("5"))],
|
||||
reporting_period_from=date(2026, 2, 1),
|
||||
reporting_period_to=date(2026, 2, 28))
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{draft.id}")
|
||||
assert "Официальная форма" not in resp.text
|
||||
|
||||
# Issued: button present
|
||||
ks2 = issue_ks2(db_session, ctx["project_id"], draft.id)
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}")
|
||||
assert "Официальная форма" in resp.text
|
||||
assert "/artifact" in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks2_ui_cancelled_shows_storno_badge(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
cancel_ks2(db_session, ctx["project_id"], ks2.id)
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}")
|
||||
assert "Официальная форма" in resp.text
|
||||
assert "СТОРНИРОВАН" in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_ks3_ui_shows_official_button(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
ks3 = _make_issued_ks3(db_session, ctx, ks2)
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
resp = client.get(f"/projects/{ctx['project_id']}/ks3/{ks3.id}")
|
||||
assert "Официальная форма" in resp.text
|
||||
assert "/artifact" in resp.text
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
|
||||
def test_existing_export_endpoints_still_work(storage_root, db_session, ctx):
|
||||
ks2 = _make_issued_ks2(db_session, ctx)
|
||||
client = _client(sessionmaker(bind=db_session.get_bind(), expire_on_commit=False))
|
||||
try:
|
||||
assert client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/export/excel").status_code == 200
|
||||
assert client.get(f"/projects/{ctx['project_id']}/ks2/{ks2.id}/export/word").status_code == 200
|
||||
finally:
|
||||
_clear()
|
||||
Reference in New Issue
Block a user