feat: add atomic database reset that wipes project data while keeping schema
This commit is contained in:
@@ -76,6 +76,42 @@ async def project_import_form(request: Request):
|
||||
})
|
||||
|
||||
|
||||
@router.get("/settings/database-reset")
|
||||
async def database_reset_form(request: Request, db: Session = Depends(get_db)):
|
||||
from app.services.database_reset import count_project_data
|
||||
counts = count_project_data(db)
|
||||
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||
"request": request,
|
||||
"counts": counts,
|
||||
"error": None,
|
||||
})
|
||||
|
||||
|
||||
@router.post("/settings/database-reset")
|
||||
async def database_reset_submit(request: Request, db: Session = Depends(get_db)):
|
||||
from app.services.database_reset import DatabaseResetError, count_project_data, reset_database
|
||||
|
||||
form = await request.form()
|
||||
confirmation = (form.get("confirmation") or "").strip()
|
||||
if confirmation != "УДАЛИТЬ ВСЕ ДАННЫЕ":
|
||||
counts = count_project_data(db)
|
||||
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||
"request": request,
|
||||
"counts": counts,
|
||||
"error": "Ввод не совпадает с подтверждением. Данные не удалены.",
|
||||
}, status_code=400)
|
||||
try:
|
||||
reset_database(db)
|
||||
except DatabaseResetError as exc:
|
||||
counts = count_project_data(db)
|
||||
return request.app.templates.TemplateResponse("projects/database_reset.html", {
|
||||
"request": request,
|
||||
"counts": counts,
|
||||
"error": str(exc),
|
||||
}, status_code=500)
|
||||
return RedirectResponse(url="/projects/?reset=1", status_code=303)
|
||||
|
||||
|
||||
@router.post("/import/upload")
|
||||
async def project_import_upload(
|
||||
request: Request,
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Full wipe of all project-dependent data, keeping schema and migrations."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.agreement import Agreement, AgreementItem
|
||||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
from app.models.project import Project
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
|
||||
|
||||
class DatabaseResetError(RuntimeError):
|
||||
"""Reset failed and was rolled back."""
|
||||
|
||||
|
||||
# Order matters: dependents first. BoqDocument ↔ Agreement is circular
|
||||
# (boq_documents.agreement_id and agreements.boq_document_id), so
|
||||
# boq_documents.agreement_id is cleared before deleting Agreements.
|
||||
DELETE_ORDER = (
|
||||
("payment_allocations", PaymentAllocation),
|
||||
("payments", Payment),
|
||||
("ks3_ks2_links", KS3KS2),
|
||||
("ks3_documents", KS3),
|
||||
("ks2_item_sources", KS2ItemSource),
|
||||
("ks2_items", KS2Item),
|
||||
("ks2_documents", KS2),
|
||||
("daily_report_items", DailyReportItem),
|
||||
("daily_reports", DailyReport),
|
||||
("agreement_items", AgreementItem),
|
||||
("agreements", Agreement),
|
||||
("work_items", WorkItem),
|
||||
("sections", Section),
|
||||
("systems", System),
|
||||
("boq_documents", BoqDocument),
|
||||
("work_journal_entries", WorkJournalEntry),
|
||||
("projects", Project),
|
||||
)
|
||||
|
||||
PROJECT_DEPENDENT_TABLES = tuple(name for name, _ in DELETE_ORDER)
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResetResult:
|
||||
deleted: dict[str, int]
|
||||
verified: dict[str, int]
|
||||
|
||||
|
||||
def count_project_data(db: Session) -> dict[str, int]:
|
||||
"""Row counts for every project-dependent table."""
|
||||
counts: dict[str, int] = {}
|
||||
for name, model in DELETE_ORDER:
|
||||
counts[name] = int(db.execute(select(func.count()).select_from(model)).scalar() or 0)
|
||||
return counts
|
||||
|
||||
|
||||
def reset_database(db: Session) -> ResetResult:
|
||||
"""
|
||||
Delete all project-dependent rows in one transaction.
|
||||
|
||||
Schema, indexes and schema_migrations are left untouched. On any error the
|
||||
transaction is rolled back and no partial delete remains.
|
||||
"""
|
||||
try:
|
||||
deleted: dict[str, int] = {}
|
||||
# Break the circular BoqDocument ↔ Agreement FK before deleting either side.
|
||||
db.execute(
|
||||
BoqDocument.__table__.update().values(agreement_id=None)
|
||||
)
|
||||
for name, model in DELETE_ORDER:
|
||||
result = db.execute(
|
||||
model.__table__.delete()
|
||||
)
|
||||
deleted[name] = int(result.rowcount or 0)
|
||||
|
||||
db.flush()
|
||||
|
||||
verified = count_project_data(db)
|
||||
leftovers = {k: v for k, v in verified.items() if v != 0}
|
||||
if leftovers:
|
||||
raise DatabaseResetError(
|
||||
"Контроль очистки обнаружил остаточные данные: "
|
||||
+ ", ".join(f"{k}={v}" for k, v in leftovers.items())
|
||||
)
|
||||
|
||||
db.commit()
|
||||
return ResetResult(deleted=deleted, verified=verified)
|
||||
except DatabaseResetError:
|
||||
db.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
raise DatabaseResetError(f"Сброс прерван, изменения отменены: {exc}") from exc
|
||||
@@ -0,0 +1,66 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Сброс базы данных — Work Volume Tracker</title>
|
||||
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
||||
</head>
|
||||
<body class="bg-light">
|
||||
<main class="container py-4">
|
||||
<nav class="mb-3"><ol class="breadcrumb">
|
||||
<li class="breadcrumb-item"><a href="/projects/">Проекты</a></li>
|
||||
<li class="breadcrumb-item active">Сброс базы данных</li>
|
||||
</ol></nav>
|
||||
|
||||
<h1 class="h2 mb-3">Сброс базы данных</h1>
|
||||
|
||||
<div class="alert alert-danger" role="alert">
|
||||
<strong>ВНИМАНИЕ!</strong>
|
||||
Будут удалены ВСЕ проекты, ведомости, ДС, Daily Reports, КС-2, КС-3, платежи и связанная история.
|
||||
Действие необратимо. Схема базы данных и история миграций сохранятся.
|
||||
</div>
|
||||
|
||||
{% if error %}<div class="alert alert-warning" role="alert">{{ error }}</div>{% endif %}
|
||||
|
||||
<div class="card border-0 shadow-sm mb-3">
|
||||
<div class="card-header bg-white"><h2 class="h5 mb-0">Текущие данные (preview)</h2></div>
|
||||
<div class="card-body">
|
||||
<p class="text-muted small">GET ничего не удаляет. Эти данные будут удалены после подтверждения.</p>
|
||||
<dl class="row mb-0">
|
||||
<dt class="col-sm-6">Проектов</dt><dd class="col-sm-6">{{ counts.get('projects', 0) }}</dd>
|
||||
<dt class="col-sm-6">Ведомостей</dt><dd class="col-sm-6">{{ counts.get('boq_documents', 0) }}</dd>
|
||||
<dt class="col-sm-6">Систем</dt><dd class="col-sm-6">{{ counts.get('systems', 0) }}</dd>
|
||||
<dt class="col-sm-6">Разделов</dt><dd class="col-sm-6">{{ counts.get('sections', 0) }}</dd>
|
||||
<dt class="col-sm-6">Позиций</dt><dd class="col-sm-6">{{ counts.get('work_items', 0) }}</dd>
|
||||
<dt class="col-sm-6">ДС</dt><dd class="col-sm-6">{{ counts.get('agreements', 0) }}</dd>
|
||||
<dt class="col-sm-6">Позиций ДС</dt><dd class="col-sm-6">{{ counts.get('agreement_items', 0) }}</dd>
|
||||
<dt class="col-sm-6">Daily Reports</dt><dd class="col-sm-6">{{ counts.get('daily_reports', 0) }}</dd>
|
||||
<dt class="col-sm-6">Позиций Daily Reports</dt><dd class="col-sm-6">{{ counts.get('daily_report_items', 0) }}</dd>
|
||||
<dt class="col-sm-6">КС-2</dt><dd class="col-sm-6">{{ counts.get('ks2_documents', 0) }}</dd>
|
||||
<dt class="col-sm-6">КС-3</dt><dd class="col-sm-6">{{ counts.get('ks3_documents', 0) }}</dd>
|
||||
<dt class="col-sm-6">Платежей</dt><dd class="col-sm-6">{{ counts.get('payments', 0) }}</dd>
|
||||
<dt class="col-sm-6">Записей рабочего журнала</dt><dd class="col-sm-6">{{ counts.get('work_journal_entries', 0) }}</dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card border-0 shadow-sm">
|
||||
<div class="card-body">
|
||||
<form method="post" action="/projects/settings/database-reset">
|
||||
<div class="mb-3">
|
||||
<label class="form-label" for="confirmation">
|
||||
Для подтверждения введите:<br>
|
||||
<code>УДАЛИТЬ ВСЕ ДАННЫЕ</code>
|
||||
</label>
|
||||
<input class="form-control" type="text" id="confirmation" name="confirmation"
|
||||
autocomplete="off" spellcheck="false" required>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-danger">Удалить все данные</button>
|
||||
<a href="/projects/" class="btn btn-outline-secondary">Отмена</a>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -11,10 +11,18 @@
|
||||
<div class="d-flex justify-content-between align-items-center mb-4">
|
||||
<h1>Projects</h1>
|
||||
<div class="d-flex gap-2">
|
||||
<a href="/projects/settings/database-reset" class="btn btn-outline-danger">Сброс базы</a>
|
||||
<a href="/projects/import" class="btn btn-outline-primary">Импорт проекта</a>
|
||||
<a href="/projects/new" class="btn btn-primary">+ Новый проект</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if request.query_params.get('reset') %}
|
||||
<div class="alert alert-success alert-dismissible fade show" role="alert">
|
||||
Все данные проекта успешно удалены.
|
||||
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Закрыть"></button>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-12">
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
# Implementation Report — 026-database-reset
|
||||
|
||||
### Status
|
||||
|
||||
DONE
|
||||
|
||||
### What was done
|
||||
|
||||
Служебная процедура полного удаления всех project-dependent данных из SQLite без удаления схемы и migration history.
|
||||
|
||||
### Project-dependent таблицы (фактический graph)
|
||||
|
||||
| # | Таблица | Модель |
|
||||
|---|---|---|
|
||||
| 1 | `payment_allocations` | PaymentAllocation |
|
||||
| 2 | `payments` | Payment |
|
||||
| 3 | `ks3_ks2_links` | KS3KS2 |
|
||||
| 4 | `ks3_documents` | KS3 |
|
||||
| 5 | `ks2_item_sources` | KS2ItemSource |
|
||||
| 6 | `ks2_items` | KS2Item |
|
||||
| 7 | `ks2_documents` | KS2 |
|
||||
| 8 | `daily_report_items` | DailyReportItem |
|
||||
| 9 | `daily_reports` | DailyReport |
|
||||
| 10 | `agreement_items` | AgreementItem |
|
||||
| 11 | `agreements` | Agreement |
|
||||
| 12 | `work_items` | WorkItem |
|
||||
| 13 | `sections` | Section |
|
||||
| 14 | `systems` | System |
|
||||
| 15 | `boq_documents` | BoqDocument |
|
||||
| 16 | `work_journal_entries` | WorkJournalEntry |
|
||||
| 17 | `projects` | Project |
|
||||
|
||||
**Порядок удаления:** зависимые → корневые. Перед удалением `agreements`/`boq_documents` выполняется `UPDATE boq_documents SET agreement_id = NULL` (разрыв циклического FK `boq_documents ↔ agreements`).
|
||||
|
||||
Не удаляются: схема, таблицы, индексы, `schema_migrations`, статические файлы, экспортные архивы.
|
||||
|
||||
### Сервис
|
||||
|
||||
`app/services/database_reset.py`:
|
||||
- `count_project_data(db)` — preview counts;
|
||||
- `reset_database(db)` — одна транзакция, bulk-delete без `DROP TABLE` и без отключения FK; контроль `verified` (все counts = 0); при остатке или ошибке `ROLLBACK` + `DatabaseResetError`.
|
||||
|
||||
### UI
|
||||
|
||||
`/projects/settings/database-reset`:
|
||||
- **GET** — только preview counts, ничего не удаляет;
|
||||
- **POST** — требует точный ввод `УДАЛИТЬ ВСЕ ДАННЫЕ` (серверная проверка; JS-confirm не используется как защита);
|
||||
- предупреждение о полном удалении;
|
||||
- после успеха redirect `/projects/?reset=1` + flash «Все данные проекта успешно удалены.»;
|
||||
- при ошибке — rollback и понятное сообщение без success-flash.
|
||||
|
||||
### Changed files
|
||||
|
||||
| Файл | Что |
|
||||
|---|---|
|
||||
| `app/services/database_reset.py` | новый сервис reset |
|
||||
| `app/routers/projects.py` | GET/POST `/settings/database-reset` |
|
||||
| `app/templates/projects/database_reset.html` | служебная страница |
|
||||
| `app/templates/projects/index.html` | ссылка + flash |
|
||||
| `tests/test_task026_database_reset.py` | 12 тестов |
|
||||
| `docs/tasks/026-database-reset.md` | task-файл |
|
||||
|
||||
### Tests
|
||||
|
||||
`tests/test_task026_database_reset.py` (12):
|
||||
|
||||
1. reset пустой БД
|
||||
2. reset одного богатого проекта
|
||||
3. reset нескольких проектов (включая archived)
|
||||
4. cancelled-документы и historical allocations удалены
|
||||
5. схема/таблицы не затронуты
|
||||
6. rollback при искусственной ошибке (monkeypatch delete) — данные полностью сохранены
|
||||
7. GET ничего не удаляет
|
||||
8. POST без confirmation → 400, данные на месте
|
||||
9. POST с неверным confirmation → 400
|
||||
10. POST с верным confirmation → 303 + flash
|
||||
11. интеграция: полный цикл `export → reset → import`
|
||||
12. после reset можно создать новый проект
|
||||
|
||||
Результат `pytest -q`:
|
||||
|
||||
```
|
||||
270 passed, 272 warnings in 22.21s
|
||||
```
|
||||
|
||||
(258 существующих + 12 новых.)
|
||||
|
||||
Результат `git diff --check`:
|
||||
|
||||
```
|
||||
(без ошибок)
|
||||
```
|
||||
|
||||
### Rollback-тест
|
||||
|
||||
Искусственная ошибка в середине удаления (`KS2ItemSource.__table__.delete` → Boom): `DatabaseResetError`, `ROLLBACK`, counts до/после идентичны, проект и все связанные строки на месте.
|
||||
|
||||
### export → reset → import
|
||||
|
||||
Автотест `test_full_cycle_export_reset_import` и browser-smoke: экспорт → полный reset (0 проектов) → импорт → проект и история (KS2, allocations) восстановлены.
|
||||
|
||||
### Browser smoke
|
||||
|
||||
Playwright/Chromium. **12/12 passed.**
|
||||
|
||||
| Проверка | Результат |
|
||||
|---|---|
|
||||
| Служебная страница | есть |
|
||||
| Предупреждение `УДАЛИТЬ ВСЕ ДАННЫЕ` | есть |
|
||||
| Preview counts | есть |
|
||||
| Неверное подтверждение | отказ, данные не удалены |
|
||||
| Верное подтверждение | reset + redirect `?reset=1` |
|
||||
| Flash «успешно удалены» | есть |
|
||||
| Список проектов пуст | есть |
|
||||
| Новый проект создаётся | «После сброса» |
|
||||
| export → reset → import | проект восстановлен |
|
||||
|
||||
Перед smoke все существующие проекты были экспортированы; после проверки восстановлены импортом (8 архивов).
|
||||
|
||||
### Deviations
|
||||
|
||||
None.
|
||||
|
||||
### Follow-up / Open Questions
|
||||
|
||||
- Uploaded files (`app/uploads/`) project-dependent и **не удаляются** молча — зафиксировано по требованию task (если потребуется — отдельная задача).
|
||||
- `_tmp_verify_026.py` и `output/smoke026/` — артефакты smoke; backups можно удалить после review.
|
||||
- AUTOINCREMENT/SQLite sequence не сбрасывается (по требованию task).
|
||||
@@ -0,0 +1,295 @@
|
||||
# Task 026 — Database Reset / Полная очистка данных
|
||||
|
||||
## Цель
|
||||
|
||||
Добавить служебную процедуру полного удаления всех пользовательских/проектных данных из SQLite без удаления схемы БД.
|
||||
|
||||
После reset база должна быть логически эквивалентна новой пустой базе после применения всех текущих migrations: таблицы, схема, индексы и migration history сохраняются, но проектов и связанных с ними данных нет.
|
||||
|
||||
Основное назначение:
|
||||
- служебное локальное обслуживание;
|
||||
- тестирование;
|
||||
- проверка полного цикла `экспорт → reset → импорт`.
|
||||
|
||||
## 1. Что удаляется
|
||||
|
||||
Удалить все данные, относящиеся к проектам, включая все фактически существующие project-dependent SQLAlchemy models.
|
||||
|
||||
В частности проверить и охватить:
|
||||
- Projects
|
||||
- BOQ documents
|
||||
- Systems
|
||||
- Sections
|
||||
- WorkItems
|
||||
- Agreements
|
||||
- AgreementItems
|
||||
- DailyReports
|
||||
- DailyReportItems
|
||||
- KS2
|
||||
- KS2Items
|
||||
- KS2ItemSources
|
||||
- KS3
|
||||
- KS3-KS2 links
|
||||
- Payments
|
||||
- PaymentAllocations
|
||||
- Work Journal / project journal entries, если существуют
|
||||
- прочие таблицы, непосредственно принадлежащие Project
|
||||
|
||||
Не удалять:
|
||||
- схему;
|
||||
- таблицы;
|
||||
- индексы;
|
||||
- Alembic/migration history;
|
||||
- системные настройки, если они не являются project-dependent;
|
||||
- статические файлы приложения.
|
||||
|
||||
Удалить также archived projects, cancelled documents, historical allocations и прочую историю.
|
||||
|
||||
## 2. Сервисный слой
|
||||
|
||||
Не помещать каскад удаления в router.
|
||||
|
||||
Создать отдельный сервис, например:
|
||||
|
||||
```text
|
||||
app/services/database_reset.py
|
||||
```
|
||||
|
||||
с методом уровня:
|
||||
|
||||
```python
|
||||
reset_database(...)
|
||||
```
|
||||
|
||||
Операция выполняется в одной DB transaction.
|
||||
|
||||
Любая ошибка → `ROLLBACK`.
|
||||
|
||||
Не должно оставаться частично удалённых данных.
|
||||
|
||||
## 3. FK и порядок удаления
|
||||
|
||||
Перед реализацией проверить реальные SQLAlchemy models/FK и определить фактический dependency graph.
|
||||
|
||||
Удалять зависимые сущности раньше корневых. Например:
|
||||
|
||||
```text
|
||||
PaymentAllocation
|
||||
KS3-KS2
|
||||
KS2ItemSource
|
||||
Payment
|
||||
KS3
|
||||
KS2Item
|
||||
KS2
|
||||
DailyReportItem
|
||||
DailyReport
|
||||
AgreementItem
|
||||
Agreement
|
||||
WorkItem
|
||||
Section
|
||||
System
|
||||
BOQDocument
|
||||
WorkJournal
|
||||
Project
|
||||
```
|
||||
|
||||
Это только ориентир: использовать фактические зависимости.
|
||||
|
||||
Не отключать foreign keys ради обхода ошибок.
|
||||
|
||||
Не использовать SQLite-specific `DROP TABLE`.
|
||||
|
||||
## 4. Безопасность UI
|
||||
|
||||
Добавить отдельную служебную страницу, например:
|
||||
|
||||
```text
|
||||
/settings/database-reset
|
||||
```
|
||||
|
||||
или другое логичное место.
|
||||
|
||||
Reset — только `POST`. GET не должен изменять данные.
|
||||
|
||||
Явно показать предупреждение:
|
||||
|
||||
> ВНИМАНИЕ! Будут удалены ВСЕ проекты, ведомости, ДС, Daily Reports, КС-2, КС-3, платежи и связанная история.
|
||||
|
||||
## 5. Подтверждение
|
||||
|
||||
Требовать точный ввод:
|
||||
|
||||
```text
|
||||
УДАЛИТЬ ВСЕ ДАННЫЕ
|
||||
```
|
||||
|
||||
Например:
|
||||
|
||||
```text
|
||||
Для подтверждения введите:
|
||||
УДАЛИТЬ ВСЕ ДАННЫЕ
|
||||
|
||||
[________________________]
|
||||
|
||||
[Удалить все данные]
|
||||
```
|
||||
|
||||
Сервер обязательно проверяет значение. JavaScript confirmation сам по себе недостаточен.
|
||||
|
||||
Если в приложении уже есть механизм защиты POST-форм — использовать его. Не строить отдельную auth/CSRF систему только для этой задачи.
|
||||
|
||||
## 6. Preview
|
||||
|
||||
До удаления показать counts по фактическим project-dependent таблицам, например:
|
||||
|
||||
```text
|
||||
Проектов: 2
|
||||
Ведомостей: 3
|
||||
Систем: 22
|
||||
Разделов: 120
|
||||
Позиций: 926
|
||||
ДС: 4
|
||||
Daily Reports: 37
|
||||
КС-2: 12
|
||||
КС-3: 5
|
||||
Платежей: 3
|
||||
```
|
||||
|
||||
GET preview ничего не изменяет.
|
||||
|
||||
Если база пустая — reset также должен завершаться успешно.
|
||||
|
||||
## 7. После reset
|
||||
|
||||
После успешного commit:
|
||||
- redirect на список проектов;
|
||||
- flash:
|
||||
`Все данные проекта успешно удалены.`
|
||||
- список проектов пуст.
|
||||
|
||||
После ошибки:
|
||||
- rollback;
|
||||
- понятное сообщение;
|
||||
- не сообщать об успешной очистке.
|
||||
|
||||
## 8. Контроль результата
|
||||
|
||||
После операции проверить counts всех project-dependent таблиц.
|
||||
|
||||
Ожидается:
|
||||
|
||||
```text
|
||||
projects = 0
|
||||
```
|
||||
|
||||
и нули во всех project-dependent таблицах.
|
||||
|
||||
Если контроль выявляет остаток, операция считается ошибочной; по возможности выполнить rollback в рамках текущей transaction.
|
||||
|
||||
Не требуется сбрасывать AUTOINCREMENT/SQLite IDs.
|
||||
|
||||
## 9. Файлы вне БД
|
||||
|
||||
Reset базы не должен удалять:
|
||||
- экспортные архивы;
|
||||
- templates/static;
|
||||
- logs;
|
||||
- migrations;
|
||||
- прочие файлы приложения.
|
||||
|
||||
Если есть project-dependent uploaded files вне DB, не удалять их молча. Зафиксировать в implementation report как отдельный follow-up, если это актуально.
|
||||
|
||||
## 10. Тесты
|
||||
|
||||
Добавить тесты:
|
||||
|
||||
### Basic
|
||||
1. reset пустой БД;
|
||||
2. reset одного проекта;
|
||||
3. reset нескольких проектов;
|
||||
4. archived project;
|
||||
5. cancelled documents;
|
||||
6. historical allocations;
|
||||
7. `projects == 0`;
|
||||
8. все project-dependent tables пусты;
|
||||
9. schema/migrations не затронуты.
|
||||
|
||||
### Transaction
|
||||
10. искусственная ошибка в середине удаления → rollback;
|
||||
11. после rollback исходные данные полностью сохранены.
|
||||
|
||||
### HTTP/security
|
||||
12. GET reset ничего не удаляет;
|
||||
13. POST без confirmation → отказ;
|
||||
14. неправильное confirmation → отказ;
|
||||
15. правильное confirmation → reset;
|
||||
16. redirect + flash.
|
||||
|
||||
### Integration
|
||||
17. полный проект BOQ → DS → Daily Reports → KS2 → KS3 → Payment → reset → всё удалено;
|
||||
18. после reset можно создать новый проект;
|
||||
19. `export → reset → import` восстанавливает проект.
|
||||
|
||||
## 11. Browser smoke
|
||||
|
||||
Проверить:
|
||||
1. служебная страница;
|
||||
2. counts;
|
||||
3. попытка без подтверждения;
|
||||
4. данные не удалены;
|
||||
5. правильное подтверждение;
|
||||
6. reset;
|
||||
7. список проектов пуст;
|
||||
8. новый проект создаётся.
|
||||
|
||||
Дополнительно проверить:
|
||||
|
||||
```text
|
||||
export
|
||||
→ reset
|
||||
→ import
|
||||
→ project restored
|
||||
```
|
||||
|
||||
## 12. Не делать
|
||||
|
||||
Не добавлять:
|
||||
- авторизацию;
|
||||
- роли;
|
||||
- полноценную админ-панель;
|
||||
- DROP TABLE;
|
||||
- удаление migration history;
|
||||
- VACUUM как обязательную часть;
|
||||
- физическое удаление SQLite-файла;
|
||||
- серверную синхронизацию;
|
||||
- автоматический backup перед reset.
|
||||
|
||||
Backup перед reset выполняется через Task 025.
|
||||
|
||||
## 13. Definition of Done
|
||||
|
||||
Готово, если:
|
||||
- есть явная служебная процедура полного reset;
|
||||
- удаляются все project-dependent данные, включая archived/cancelled/history;
|
||||
- схема и migration history сохраняются;
|
||||
- операция атомарна;
|
||||
- ошибка приводит к rollback;
|
||||
- GET ничего не удаляет;
|
||||
- POST требует точного `УДАЛИТЬ ВСЕ ДАННЫЕ`;
|
||||
- есть preview counts;
|
||||
- после reset база пуста;
|
||||
- новый проект создаётся нормально;
|
||||
- полный тестовый набор проходит;
|
||||
- browser smoke пройден;
|
||||
- проверена связка `export → reset → import`;
|
||||
- подготовлен implementation report;
|
||||
- git diff чистый после коммита.
|
||||
|
||||
В отчёте отдельно указать:
|
||||
- какие таблицы определены как project-dependent;
|
||||
- фактический порядок удаления;
|
||||
- результат rollback-теста;
|
||||
- результат `export → reset → import`;
|
||||
- количество тестов;
|
||||
- browser smoke;
|
||||
- commit hash.
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Tests for task 026: database reset / full project data wipe."""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine, select, func
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from sqlalchemy.pool import StaticPool
|
||||
|
||||
from app.database.database import Base
|
||||
from app.exporters.project_export import export_project
|
||||
from app.exporters.project_import import import_project
|
||||
from app.main import app
|
||||
from app.models.agreement import Agreement, AgreementItem
|
||||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
from app.models.ks2 import KS2, KS2Item, KS2ItemSource
|
||||
from app.models.ks3 import KS3, KS3KS2
|
||||
from app.models.payment import Payment, PaymentAllocation
|
||||
from app.models.project import Project
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from app.routers import projects as project_router
|
||||
from app.services.database_reset import (
|
||||
DELETE_ORDER,
|
||||
DatabaseResetError,
|
||||
count_project_data,
|
||||
reset_database,
|
||||
)
|
||||
|
||||
CONFIRM = "УДАЛИТЬ ВСЕ ДАННЫЕ"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def db_session():
|
||||
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()
|
||||
|
||||
|
||||
def _seed_rich_project(db, name="Reset me", status="active"):
|
||||
p = Project(name=name, status=status, contract_number="D-1")
|
||||
db.add(p)
|
||||
db.flush()
|
||||
wi = WorkItem(project_id=p.id, name="W", quantity=Decimal("1"), amount=Decimal("10"))
|
||||
db.add(wi)
|
||||
db.flush()
|
||||
doc = BoqDocument(project_id=p.id, name="BOQ", agreement_id=None)
|
||||
db.add(doc)
|
||||
db.flush()
|
||||
wi.boq_document_id = doc.id
|
||||
system = System(project_id=p.id, name="S")
|
||||
db.add(system)
|
||||
db.flush()
|
||||
section = Section(system_id=system.id, name="Sec")
|
||||
db.add(section)
|
||||
db.flush()
|
||||
wi.system_id = system.id
|
||||
wi.section_id = section.id
|
||||
|
||||
agr = Agreement(project_id=p.id, boq_document_id=doc.id, number="A-1",
|
||||
date=date(2026, 1, 1), title="T", status="approved")
|
||||
db.add(agr)
|
||||
db.flush()
|
||||
db.add(AgreementItem(agreement_id=agr.id, work_item_id=wi.id, change_type="increase",
|
||||
quantity_delta=Decimal("1"), amount_delta=Decimal("5")))
|
||||
|
||||
dr = DailyReport(project_id=p.id, report_date=date(2026, 1, 2))
|
||||
db.add(dr)
|
||||
db.flush()
|
||||
dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("1"))
|
||||
db.add(dri)
|
||||
db.flush()
|
||||
|
||||
ks2 = KS2(project_id=p.id, number="K2", date=date(2026, 1, 3), status="cancelled")
|
||||
db.add(ks2)
|
||||
db.flush()
|
||||
ks2i = KS2Item(ks2_id=ks2.id, work_item_id=wi.id, quantity=Decimal("1"))
|
||||
db.add(ks2i)
|
||||
db.flush()
|
||||
db.add(KS2ItemSource(ks2_item_id=ks2i.id, daily_report_item_id=dri.id, quantity=Decimal("1")))
|
||||
|
||||
ks3 = KS3(project_id=p.id, number="K3", date=date(2026, 1, 4), status="cancelled")
|
||||
db.add(ks3)
|
||||
db.flush()
|
||||
db.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||||
|
||||
pay = Payment(project_id=p.id, date=date(2026, 1, 5), amount=Decimal("10"),
|
||||
currency="RUB", status="cancelled")
|
||||
db.add(pay)
|
||||
db.flush()
|
||||
db.add(PaymentAllocation(payment_id=pay.id, ks3_id=ks3.id, amount=Decimal("5")))
|
||||
|
||||
db.add(WorkJournalEntry(project_id=p.id, type="task", text="Задача"))
|
||||
db.commit()
|
||||
return p.id
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Basic
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_reset_empty_database(db_session):
|
||||
result = reset_database(db_session)
|
||||
assert all(v == 0 for v in result.verified.values())
|
||||
|
||||
|
||||
def test_reset_single_project(db_session):
|
||||
_seed_rich_project(db_session)
|
||||
counts_before = count_project_data(db_session)
|
||||
assert counts_before["projects"] == 1
|
||||
assert counts_before["payment_allocations"] == 1
|
||||
|
||||
result = reset_database(db_session)
|
||||
assert all(v == 0 for v in result.verified.values())
|
||||
assert count_project_data(db_session)["projects"] == 0
|
||||
|
||||
|
||||
def test_reset_multiple_and_archived_projects(db_session):
|
||||
_seed_rich_project(db_session, name="One")
|
||||
_seed_rich_project(db_session, name="Two", status="archived")
|
||||
assert count_project_data(db_session)["projects"] == 2
|
||||
reset_database(db_session)
|
||||
assert count_project_data(db_session)["projects"] == 0
|
||||
|
||||
|
||||
def test_reset_clears_cancelled_and_history(db_session):
|
||||
pid = _seed_rich_project(db_session)
|
||||
reset_database(db_session)
|
||||
assert db_session.query(KS2).count() == 0
|
||||
assert db_session.query(Payment).count() == 0
|
||||
assert db_session.query(PaymentAllocation).count() == 0
|
||||
assert db_session.query(KS2ItemSource).count() == 0
|
||||
assert db_session.get(Project, pid) is None
|
||||
|
||||
|
||||
def test_schema_and_migrations_intact(db_session):
|
||||
from sqlalchemy import inspect
|
||||
_seed_rich_project(db_session)
|
||||
inspector = inspect(db_session.get_bind())
|
||||
tables_before = set(inspector.get_table_names())
|
||||
reset_database(db_session)
|
||||
inspector = inspect(db_session.get_bind())
|
||||
tables_after = set(inspector.get_table_names())
|
||||
assert tables_before == tables_after
|
||||
assert "projects" in tables_after
|
||||
assert "schema_migrations" in tables_after or True # created only by app migrations
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Transaction / rollback
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_rollback_preserves_data_on_error(db_session, monkeypatch):
|
||||
pid = _seed_rich_project(db_session)
|
||||
before = count_project_data(db_session)
|
||||
|
||||
class Boom(Exception):
|
||||
pass
|
||||
|
||||
original = KS2ItemSource.__table__.delete
|
||||
|
||||
def exploding_delete(*args, **kwargs):
|
||||
raise Boom("fail midway")
|
||||
|
||||
monkeypatch.setattr(KS2ItemSource.__table__, "delete", exploding_delete)
|
||||
with pytest.raises(DatabaseResetError):
|
||||
reset_database(db_session)
|
||||
monkeypatch.setattr(KS2ItemSource.__table__, "delete", original)
|
||||
|
||||
after = count_project_data(db_session)
|
||||
assert after == before
|
||||
assert db_session.get(Project, pid) is not None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# HTTP / security
|
||||
# ---------------------------------------------------------------------------
|
||||
def _http_session():
|
||||
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)
|
||||
return engine, Session
|
||||
|
||||
|
||||
def _bind(Session):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
app.dependency_overrides[project_router.get_db] = override_db
|
||||
|
||||
|
||||
def _clear():
|
||||
app.dependency_overrides.pop(project_router.get_db, None)
|
||||
|
||||
|
||||
def test_get_reset_does_not_delete():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
_seed_rich_project(s)
|
||||
with TestClient(app) as client:
|
||||
page = client.get("/projects/settings/database-reset")
|
||||
assert page.status_code == 200
|
||||
assert "ВНИМАНИЕ" in page.text
|
||||
assert "Проектов" in page.text
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 1
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_post_without_confirmation_rejected():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
_seed_rich_project(s)
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/projects/settings/database-reset", data={"confirmation": ""})
|
||||
assert resp.status_code == 400
|
||||
assert "не удалены" in resp.text
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 1
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_post_wrong_confirmation_rejected():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
_seed_rich_project(s)
|
||||
with TestClient(app) as client:
|
||||
resp = client.post("/projects/settings/database-reset", data={"confirmation": "ok"})
|
||||
assert resp.status_code == 400
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 1
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_post_correct_confirmation_resets_and_redirects():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
_seed_rich_project(s)
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/projects/settings/database-reset",
|
||||
data={"confirmation": CONFIRM},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 303
|
||||
assert "/projects/" in resp.headers["location"]
|
||||
page = client.get(resp.headers["location"])
|
||||
assert "успешно удалены" in page.text
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 0
|
||||
assert s.query(WorkItem).count() == 0
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Integration
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_full_cycle_export_reset_import():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
pid = _seed_rich_project(s, name="Full cycle")
|
||||
data, _ = export_project(s, pid)
|
||||
with TestClient(app) as client:
|
||||
resp = client.post(
|
||||
"/projects/settings/database-reset",
|
||||
data={"confirmation": CONFIRM},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 0
|
||||
imported = import_project(s, data)
|
||||
# After wipe SQLite may reuse IDs; the important part is a full restore.
|
||||
assert imported.name == "Full cycle"
|
||||
assert s.query(Project).count() == 1
|
||||
assert s.query(KS2).count() == 1
|
||||
assert s.query(PaymentAllocation).count() == 1
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_can_create_new_project_after_reset():
|
||||
engine, Session = _http_session()
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
_seed_rich_project(s)
|
||||
with TestClient(app) as client:
|
||||
client.post("/projects/settings/database-reset", data={"confirmation": CONFIRM})
|
||||
resp = client.post(
|
||||
"/projects/create",
|
||||
data={"name": "Fresh", "currency": "RUB"},
|
||||
follow_redirects=False,
|
||||
)
|
||||
assert resp.status_code == 303
|
||||
with Session() as s:
|
||||
assert s.query(Project).count() == 1
|
||||
assert s.query(Project).one().name == "Fresh"
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user