Files
work-volume-tracker/docs/implementation/DOC-B1-document-artifacts.md
T
2026-09-29 15:29:45 +03:00

103 lines
4.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Implementation Report — DOC-B1-document-artifacts
### Status
DONE
### Изменения
| Файл | Что |
|---|---|
| `app/models/document_artifact.py` | модель `DocumentArtifact` |
| `app/config.py` | `DOCUMENT_STORAGE_ROOT` / `document_storage_root()` |
| `app/database/migrations.py` | миграция `20260928_document_artifacts` |
| `app/main.py` | регистрация модели |
| `tests/test_doc_b1_document_artifacts.py` | 13 тестов |
### Модель
`app/models/document_artifact.py` → таблица `document_artifacts`.
Поля: `id`, `project_id` (FK→projects), `document_type`, `document_id`, `format`, `storage_key`, `template_type`, `template_version`, `content_hash` VARCHAR(64), `input_hash` VARCHAR(64), `is_current` BOOLEAN default true, `generated_at`, `created_at`, `updated_at`.
Связь с KS-2/KS-3 полиморфная (`document_type` + `document_id`), FK на ks2/ks3 отсутствует. `project_id` — обычный FK.
### Migration
`DOCUMENT_ARTIFACTS_MIGRATION = "20260928_document_artifacts"` в `app/database/migrations.py` (существующий механизм проекта):
- `CREATE TABLE document_artifacts` (полный набор колонок);
- индексы: `ix_document_artifacts_id`, `ix_document_artifacts_project_id`, `ix_document_artifacts_type_doc`, `ix_document_artifacts_current`;
- partial unique index `uq_document_artifact_current`;
- downgrade: drop таблицы + индексов + версии в `schema_migrations`.
### Индексы
1. `(document_type, document_id)`
2. `(project_id)`
3. `(document_type, document_id, is_current)`
### Partial unique index
Реализован, т.к. SQLite поддерживает:
```sql
CREATE UNIQUE INDEX uq_document_artifact_current
ON document_artifacts (document_type, document_id, format)
WHERE is_current = 1
```
В SQLAlchemy — `Index(..., unique=True, sqlite_where=text("is_current = 1"))`.
Исторические записи (`is_current = 0`) могут повторяться свободно.
### Storage root config
`app/config.py`:
- env `DOCUMENT_STORAGE_ROOT` (override);
- default = `<app>/../storage`, anchored через `Path(__file__).resolve()`, не зависит от cwd;
- **не создаёт каталоги** — только возвращает `Path`.
### Тесты
`tests/test_doc_b1_document_artifacts.py` (13):
1. создание `DocumentArtifact`;
2. обязательные поля (NOT NULL);
3. `is_current=True` по умолчанию;
4. FK на Project;
5. несколько historical artifacts допускаются;
6. два current одного `(type, id, format)` → IntegrityError;
7. current для разных format разрешены;
8. migration upgrade создаёт таблицу + индексы + версию;
9. downgrade удаляет таблицу;
10. существующие данные не повреждены;
11. default storage root не зависит от cwd;
12. custom `DOCUMENT_STORAGE_ROOT` из env;
13. config не создаёт каталог при импорте/вызове.
Результат `pytest -q`:
```
335 passed, 284 warnings in 26.20s
```
(322 существующих + 13 новых.)
Результат `git diff --check`:
```
(без ошибок)
```
Запуск приложения: `app.ok Work Volume Tracker` — модель зарегистрирована, миграция проходит.
### Deviations
None.
### Follow-up для DOC-B2
- Реализовать `document_artifact_service`: persist / resolve / invalidate / hash (content_hash, input_hash).
- Создание каталогов `storage/projects/<project_id>/documents/...` при записи artifact.
- Canonical DTO hash (Decimal→str, date→ISO, sort_keys).
- Правило «не более одного current» дополнительно обеспечить в сервисе (partial index — защитный уровень).
- Не добавлять `document_artifacts` в `database_reset.DELETE_ORDER` до DOC-B8 (безопасное удаление файлов).