feat: include document artifacts in project export/import round-trip

This commit is contained in:
Арсентьев Александр
2026-09-30 12:24:49 +03:00
parent bc0e04a482
commit 8302250325
6 changed files with 1482 additions and 4 deletions
+95 -3
View File
@@ -20,6 +20,7 @@ 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.models.document_artifact import DocumentArtifact
FORMAT_NAME = "work_volume_tracker"
FORMAT_VERSION = 1
@@ -46,7 +47,7 @@ REQUIRED_FILES = (
)
# Old Task 025 archives may lack this file; import treats it as an empty journal.
OPTIONAL_FILES = ("work_journal_entries.json",)
OPTIONAL_FILES = ("work_journal_entries.json", "document_artifacts.json")
EXPORT_FILES = REQUIRED_FILES[:-1] + OPTIONAL_FILES + ("checksums.json",)
@@ -184,6 +185,19 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
.order_by(WorkJournalEntry.id)
.all()
)
# Official artifacts for issued/cancelled KS-2 and KS-3 only.
ks2_statuses = {k.id: k.status for k in ks2_docs}
ks3_statuses = {k.id: k.status for k in ks3_docs}
eligible_doc_ids = {
"KS2": {kid for kid, st in ks2_statuses.items() if st in ("issued", "cancelled")},
"KS3": {kid for kid, st in ks3_statuses.items() if st in ("issued", "cancelled")},
}
document_artifacts = (
db.query(DocumentArtifact)
.filter(DocumentArtifact.project_id == project_id)
.order_by(DocumentArtifact.id)
.all()
)
return {
"project": project,
@@ -203,6 +217,8 @@ def collect_project(db: Session, project_id: int) -> dict[str, Any]:
"payments": payments,
"payment_allocations": payment_allocations,
"work_journal_entries": work_journal_entries,
"document_artifacts": document_artifacts,
"eligible_doc_ids": eligible_doc_ids,
}
@@ -616,6 +632,65 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
for e in graph.get("work_journal_entries", [])
]
# Official artifacts (issued/cancelled KS-2/KS-3 only)
from app.services.document_artifact_service import compute_content_hash
from app.config import document_storage_root
eligible = graph.get("eligible_doc_ids", {})
ks2_map = keys["ks2"]
ks3_map = keys["ks3"]
document_artifacts_records = []
artifact_blobs: dict[str, bytes] = {}
storage_root = document_storage_root()
for art in graph.get("document_artifacts", []):
if art.document_type == "KS2":
eligible_ids = eligible.get("KS2", set())
doc_export_id = ks2_map.get(art.document_id)
elif art.document_type == "KS3":
eligible_ids = eligible.get("KS3", set())
doc_export_id = ks3_map.get(art.document_id)
else:
continue
# Only issued/cancelled documents
if art.document_id not in eligible_ids:
continue
if doc_export_id is None:
raise ProjectExportError(
f"Artifact {art.id} references unknown document {art.document_type}:{art.document_id}"
)
# Physical file must exist and match content_hash
from app.services.document_artifact_service import resolve_storage_path
file_path = resolve_storage_path(art.storage_key)
if not file_path.is_file():
raise ProjectExportError(
f"Artifact file not found for {art.document_type}:{art.document_id} ({art.format})"
)
file_bytes = file_path.read_bytes()
actual_hash = compute_content_hash(file_bytes)
if actual_hash != art.content_hash:
raise ProjectExportError(
f"Artifact file hash mismatch for {art.document_type}:{art.document_id}"
)
ext = "xlsx" if art.format == "xlsx" else "docx" if art.format == "docx" else art.format
archive_path = f"artifacts/{art.document_type.lower()}/{art.id}.{ext}"
artifact_blobs[archive_path] = file_bytes
document_artifacts_records.append({
"export_id": f"document_artifact:{art.id:08d}",
"source_id": art.id,
"document_type": art.document_type,
"document_export_id": doc_export_id,
"format": art.format,
"template_type": art.template_type,
"template_version": art.template_version,
"content_hash": art.content_hash,
"input_hash": art.input_hash,
"is_current": bool(art.is_current),
"generated_at": _iso(art.generated_at),
"archive_path": archive_path,
})
counts = {
"boq_documents": len(boq_documents),
"systems": len(systems),
@@ -633,6 +708,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"payments": len(payments),
"payment_allocations": len(payment_allocations),
"work_journal_entries": len(work_journal_entries),
"document_artifacts": len(document_artifacts_records),
}
manifest = {
"format": FORMAT_NAME,
@@ -643,7 +719,7 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"counts": counts,
}
return {
files = {
"manifest.json": manifest,
"project.json": project_record,
"boq_documents.json": boq_documents,
@@ -662,12 +738,25 @@ def serialize_project(graph: dict[str, Any]) -> dict[str, list | dict]:
"payments.json": payments,
"payment_allocations.json": payment_allocations,
"work_journal_entries.json": work_journal_entries,
"document_artifacts.json": document_artifacts_records,
}
return {**files, "__artifact_blobs__": artifact_blobs}
def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
"""Serialize payload dict to a ZIP with checksums. Returns (zip_bytes, filename)."""
parts: dict[str, bytes] = {name: _dumps(payload) for name, payload in files.items()}
artifact_blobs = files.pop("__artifact_blobs__", {}) if "__artifact_blobs__" in files else {}
parts: dict[str, bytes] = {}
for name, payload in files.items():
if name == "__artifact_blobs__":
continue
if isinstance(payload, bytes):
parts[name] = payload
else:
parts[name] = _dumps(payload)
# Physical artifact files
for path, data in artifact_blobs.items():
parts[path] = data
checksums = {name: _sha256(data) for name, data in parts.items()}
parts["checksums.json"] = _dumps(checksums)
@@ -677,6 +766,9 @@ def build_archive(files: dict[str, Any]) -> tuple[bytes, str]:
if name not in parts:
raise ProjectExportError(f"В архиве отсутствует обязательный файл {name}")
zf.writestr(name, parts[name])
# Physical artifacts (always present if collected)
for path in sorted(artifact_blobs.keys()):
zf.writestr(path, artifact_blobs[path])
project_name = files.get("manifest.json", {}).get("project_name", "проект")
return buf.getvalue(), _safe_archive_filename(project_name)
+137 -1
View File
@@ -19,6 +19,7 @@ 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.models.document_artifact import DocumentArtifact
from app.exporters.project_export import (
FORMAT_NAME,
FORMAT_VERSION,
@@ -49,6 +50,7 @@ _LIST_FILES = (
"payments.json",
"payment_allocations.json",
"work_journal_entries.json",
"document_artifacts.json",
)
_ALLOWED_AGREEMENT_STATUS = {"draft", "approved"}
@@ -75,6 +77,7 @@ _REQUIRED_FIELDS: dict[str, tuple[str, ...]] = {
"payments.json": ("export_id", "date", "amount", "currency", "status"),
"payment_allocations.json": ("export_id", "payment_export_id", "ks3_export_id", "amount"),
"work_journal_entries.json": ("export_id", "type", "text"),
"document_artifacts.json": ("export_id", "document_type", "document_export_id", "format", "content_hash", "archive_path"),
}
@@ -140,6 +143,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
wanted = [n for n in REQUIRED_FILES] + [n for n in OPTIONAL_FILES if n in names]
raw: dict[str, bytes] = {n: zf.read(n) for n in wanted}
# Physical artifact files (any path under artifacts/)
artifact_files: dict[str, bytes] = {}
for name in names:
if name.startswith("artifacts/") and not name.endswith("/"):
artifact_files[name] = zf.read(name)
try:
checksums = json.loads(raw["checksums.json"].decode("utf-8"))
@@ -156,6 +164,13 @@ def _read_archive(data: bytes) -> dict[str, Any]:
if expected != actual:
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
# Validate artifact file checksums too
for name, body in artifact_files.items():
expected = checksums.get(name)
actual = _sha256(body)
if expected != actual:
raise ProjectImportError(f"Контрольная сумма не совпадает для {name}")
payload: dict[str, Any] = {}
for name, body in raw.items():
if name == "checksums.json":
@@ -171,6 +186,11 @@ def _read_archive(data: bytes) -> dict[str, Any]:
payload["work_journal_entries.json"] = []
missing_optional.add("work_journal_entries.json")
# Backward compatibility: old archives have no document artifacts.
if "document_artifacts.json" not in payload:
payload["document_artifacts.json"] = []
missing_optional.add("document_artifacts.json")
manifest = payload.get("manifest.json")
if not isinstance(manifest, dict):
raise ProjectImportError("manifest.json: ожидается объект")
@@ -187,7 +207,8 @@ def _read_archive(data: bytes) -> dict[str, Any]:
if not isinstance(payload.get(name), list):
raise ProjectImportError(f"{name}: ожидается массив")
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional}
return {"payload": payload, "manifest": manifest, "missing_optional": missing_optional,
"artifact_files": artifact_files}
def _validate_records(
@@ -299,6 +320,48 @@ def _validate_records(
if _parse_decimal(row.get("amount"), "amount", required=True) <= 0:
raise ProjectImportError("payment_allocations: amount должен быть > 0")
# Validate document_artifacts.json
ks2_ids = {r["export_id"] for r in payload["ks2.json"]}
ks3_ids = {r["export_id"] for r in payload["ks3.json"]}
ks2_status = {r["export_id"]: r["status"] for r in payload["ks2.json"]}
ks3_status = {r["export_id"]: r["status"] for r in payload["ks3.json"]}
allowed_doc_ids = ks2_ids | ks3_ids
allowed_statuses = {"issued", "cancelled"}
art_required = ("export_id", "document_type", "document_export_id", "format",
"template_type", "template_version", "content_hash", "input_hash",
"archive_path")
for idx, row in enumerate(payload.get("document_artifacts.json", []), start=1):
for field in art_required:
if field not in row:
raise ProjectImportError(f"document_artifacts[{idx}]: нет поля {field}")
if row["document_type"] not in ("KS2", "KS3"):
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый document_type")
if row["format"] not in ("xlsx", "docx"):
raise ProjectImportError(f"document_artifacts[{idx}]: недопустимый format")
if not isinstance(row["template_version"], int):
raise ProjectImportError(f"document_artifacts[{idx}]: template_version должен быть числом")
for hf in ("content_hash", "input_hash"):
h = row[hf]
if not isinstance(h, str) or len(h) != 64:
raise ProjectImportError(f"document_artifacts[{idx}]: {hf} должен быть SHA-256 (64 символа)")
# document_export_id must reference issued/cancelled KS-2/KS-3
deid = row["document_export_id"]
if deid not in allowed_doc_ids:
raise ProjectImportError(f"document_artifacts[{idx}]: неизвестный document_export_id {deid!r}")
status = ks2_status.get(deid) or ks3_status.get(deid)
if status not in allowed_statuses:
raise ProjectImportError(
f"document_artifacts[{idx}]: artifact может относиться только к issued/cancelled документу"
)
# archive_path must be safe and under artifacts/
ap = row["archive_path"].replace("\\", "/")
if not ap.startswith("artifacts/") or ".." in ap.split("/") or ap.startswith("/"):
raise ProjectImportError(f"document_artifacts[{idx}]: небезопасный archive_path")
if row["format"] == "xlsx" and not ap.endswith(".xlsx"):
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
if row["format"] == "docx" and not ap.endswith(".docx"):
raise ProjectImportError(f"document_artifacts[{idx}]: расширение не соответствует format")
# Internal export_id references
def has(name: str, eid: str) -> bool:
return eid in export_ids.get(name, set())
@@ -376,18 +439,41 @@ def validate_archive(data: bytes) -> dict[str, Any]:
result = _read_archive(data)
payload = result["payload"]
manifest = result["manifest"]
artifact_files = result.get("artifact_files", {})
_validate_records(payload, manifest, result.get("missing_optional"))
# Validate artifact files against document_artifacts.json
art_rows = payload.get("document_artifacts.json", [])
art_paths = {r["archive_path"] for r in art_rows}
for row in art_rows:
ap = row["archive_path"]
if ap not in artifact_files:
raise ProjectImportError(f"Artifact file missing in archive: {ap}")
from app.services.document_artifact_service import compute_content_hash
actual = compute_content_hash(artifact_files[ap])
if actual != row["content_hash"]:
raise ProjectImportError(f"Artifact hash mismatch for {ap}")
# No orphan artifact references
for ap in artifact_files:
if ap not in art_paths:
raise ProjectImportError(f"Orphan artifact file in archive: {ap}")
counts = dict(manifest.get("counts") or {})
if "work_journal_entries.json" in result.get("missing_optional", set()):
counts["work_journal_entries"] = 0
else:
counts.setdefault("work_journal_entries", len(payload.get("work_journal_entries.json", [])))
if "document_artifacts.json" in result.get("missing_optional", set()):
counts["document_artifacts"] = 0
else:
counts.setdefault("document_artifacts", len(art_rows))
return {
"manifest": manifest,
"project_name": payload["project.json"].get("name"),
"project": payload["project.json"],
"counts": counts,
"payload": payload,
"artifact_files": artifact_files,
}
@@ -645,6 +731,55 @@ def _import_entities(db: Session, payload: dict[str, Any]) -> Project:
db.flush()
ids[row["export_id"]] = obj.id
# Restore document artifacts (official issued/cancelled files)
created_artifact_paths: list = []
try:
from app.services.document_artifact_service import build_storage_key, resolve_storage_path
from app.config import document_storage_root
artifact_files = payload.get("__artifact_files__", {})
for row in payload.get("document_artifacts.json", []):
doc_type = row["document_type"]
new_doc_id = _require_mapping(row["document_export_id"], ids, "document_export_id")
ext = row["format"]
storage_key = build_storage_key(
project.id, doc_type, new_doc_id,
row["template_type"], row["template_version"], ext,
)
file_bytes = artifact_files.get(row["archive_path"])
if file_bytes is None:
raise ProjectImportError(f"Artifact file missing in archive: {row['archive_path']}")
dest = resolve_storage_path(storage_key)
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(file_bytes)
created_artifact_paths.append(dest)
art = DocumentArtifact(
project_id=project.id,
document_type=doc_type,
document_id=new_doc_id,
format=ext,
storage_key=storage_key,
template_type=row["template_type"],
template_version=int(row["template_version"]),
content_hash=row["content_hash"],
input_hash=row["input_hash"],
is_current=bool(row.get("is_current", True)),
generated_at=_parse_datetime(row.get("generated_at"), "generated_at"),
)
db.add(art)
db.flush()
ids[row["export_id"]] = art.id
except Exception:
# Compensating cleanup: remove files created by this attempt
for p in created_artifact_paths:
try:
if p.is_file():
p.unlink()
except OSError:
pass
raise
db.flush()
return project
@@ -653,6 +788,7 @@ def import_project(db: Session, data: bytes) -> Project:
"""Validate archive then create a new project atomically."""
preview = validate_archive(data)
payload = preview["payload"]
payload["__artifact_files__"] = preview.get("artifact_files", {})
try:
project = _import_entities(db, payload)
db.commit()
+2
View File
@@ -14,6 +14,7 @@ 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.models.document_artifact import DocumentArtifact
class DatabaseResetError(RuntimeError):
@@ -40,6 +41,7 @@ DELETE_ORDER = (
("systems", System),
("boq_documents", BoqDocument),
("work_journal_entries", WorkJournalEntry),
("document_artifacts", DocumentArtifact),
("projects", Project),
)
@@ -0,0 +1,137 @@
# Implementation Report — DOC-B7-export-import-artifacts
### Status
DONE
### Changed files
| Файл | Что |
|---|---|
| `app/exporters/project_export.py` | сбор артефактов, `document_artifacts.json`, physical files в ZIP |
| `app/exporters/project_import.py` | валидация артефактов, remap, запись файлов |
| `app/services/database_reset.py` | `document_artifacts` в `DELETE_ORDER` (необходимо для round-trip) |
| `tests/test_doc_b7_export_import_artifacts.py` | 17 тестов |
### Итоговая структура `.wvt.zip`
```
manifest.json
project.json
boq_documents.json
... (существующие JSON)
work_journal_entries.json
document_artifacts.json ← новый
checksums.json
artifacts/
ks2/
<artifact_id>.xlsx ← физические файлы
ks3/
<artifact_id>.docx
```
### Формат document_artifacts.json
```json
{
"export_id": "document_artifact:00000001",
"source_id": 123,
"document_type": "KS2",
"document_export_id": "ks2:00000001",
"format": "xlsx",
"template_type": "ks2",
"template_version": 1,
"content_hash": "…",
"input_hash": "…",
"is_current": true,
"generated_at": "2026-09-30T10:00:00",
"archive_path": "artifacts/ks2/123.xlsx"
}
```
`source_id` — диагностический. Remap через `document_export_id` → `ks2.json`/`ks3.json` `export_id`.
### Правила export
- Только issued/cancelled KS-2/KS-3;
- draft artifacts не экспортируются;
- `content_hash` сверяется с SHA-256 файла;
- отсутствующий/повреждённый файл → `ProjectExportError`;
- checksums включают physical files.
### Правила import
Валидация до DB mutation:
- `document_artifacts.json` существует (или count=0 для старых архивов);
- все заявленные файлы есть в архиве;
- SHA-256 файла == `content_hash`;
- `document_export_id` существует среди KS-2/KS-3 export IDs;
- статус документа issued/cancelled (draft → reject);
- `archive_path` безопасен (`artifacts/`, без `..`, расширение = format);
- manifest count = количество записей;
- orphan artifact references → reject.
### Remap strategy
```
document_export_id → ks2.json/ks3.json export_id → new DB id
→ new DocumentArtifact.document_id
```
`storage_key` строится через `build_storage_key(new_project_id, type, new_doc_id, …)`.
### Checksum/hash verification
Export: `SHA-256(file) == content_hash` → иначе ошибка.
Import: `archive checksum == SHA-256(file) == content_hash` → иначе reject.
### Rollback/cleanup
`_import_entities` при ошибке удаляет созданные файлы (`unlink`), затем `import_project` делает `db.rollback()`.
### Backward compatibility
Старые архивы без `document_artifacts.json`/`artifacts/` импортируются нормально (count=0).
### Round-trip
`Export → Reset → Import → Export` протестирован:
- артефакты KS-2 + KS-3 восстанавливаются;
- bytes/content_hash/input_hash совпадают;
- `is_current` сохраняется;
- cancelled artifact не заменяется;
- второй export содержит те же артефакты.
### Тесты (17)
Export (6): issued KS-2/KS-3, cancelled, draft skip, manifest count, checksums.
Import (7): restore, hashes/template, cancelled, old archive, unknown export_id, draft reject, checksum mismatch, path traversal.
Round-trip (2): полный цикл, cancelled preservation.
Rollback (1): ошибочный импорт не создаёт artifact rows.
Регрессия: полный suite.
Результат `pytest -q`:
```
447 passed, 704 warnings in 36.45s
```
(430 существующих + 17 новых.)
Результат `git diff --check`:
```
(без ошибок)
```
### Browser/manual checks
Round-trip проверен через Python API (export → reset → import → verify). UI не менялся — используется существующий Project Export/Import.
### Deviations
- `document_artifacts` добавлен в `database_reset.DELETE_ORDER` — минимальное изменение, необходимое для round-trip (иначе reset оставляет orphan rows и import падает на unique constraint). По задаче «database reset changes» были out of scope, но без этого интеграция невозможна.
### Recommended next task
**DOC-B8** — Database Reset: удаление физических файлов проекта из `storage/` (сейчас reset чистит только DB rows).
@@ -0,0 +1,691 @@
# DOC-B7 — Export/Import DocumentArtifact
## Цель
Включить официальные артефакты документов KS-2/KS-3 в существующий механизм Project Export/Import `.wvt.zip`.
После задачи полный перенос проекта должен сохранять не только DB-состояние документов, но и их официальные физические файлы.
Ключевой принцип:
```text
Project Export
↓
.wvt.zip
├── существующие JSON
├── manifest/checksums
└── artifacts/
└── issued/cancelled files
↓
Project Import
↓
новый project_id
↓
remap document IDs
↓
восстановление artifact metadata + файлов
```
### Что переносим
Только артефакты документов, которые относятся к:
- issued KS-2;
- cancelled KS-2;
- issued KS-3;
- cancelled KS-3.
### Что НЕ переносим
Draft artifacts не являются частью переносимого официального комплекта.
Их можно восстановить/перегенерировать после импорта обычными механизмами.
---
# 1. Изучить перед изменением
Прочитать:
- существующий Project Export/Import;
- `app/exporters/`;
- код `project_export` / `project_import`;
- `manifest.json`;
- `checksums.json`;
- текущие JSON-файлы archive;
- `DocumentArtifact`;
- `document_artifact_service`;
- KS-2/KS-3 модели;
- tests для Task 025;
- tests для DOC-B1/B2/B5/B6;
- Database Reset, если в нём уже есть работа с project storage.
Не создавать второй механизм Project Export/Import.
Расширить существующий формат.
---
# 2. Формат архива
Сохранить существующий `.wvt.zip`.
Добавить каталог:
```text
artifacts/
```
Рекомендуемая структура:
```text
artifacts/
ks2/
<artifact_export_id>.xlsx
ks3/
<artifact_export_id>.docx
```
И JSON:
```text
document_artifacts.json
```
Metadata хранится отдельно от физических файлов.
---
# 3. document_artifacts.json
Для каждого переносимого artifact сохранить как минимум:
```json
{
"export_id": "uuid",
"source_id": 123,
"document_type": "KS2",
"document_export_id": "uuid-of-exported-ks2",
"format": "xlsx",
"template_type": "ks2_ru_v1",
"template_version": 1,
"content_hash": "...",
"input_hash": "...",
"is_current": true,
"generated_at": "2026-09-30T10:00:00",
"archive_path": "artifacts/ks2/a1b2c3.xlsx"
}
```
`source_id` — только диагностический.
Связь при import должна идти через `export_id`.
Для KS-2:
```text
document_type = KS2
document_export_id → ks2.json export_id
```
Для KS-3:
```text
document_type = KS3
document_export_id → ks3.json export_id
```
---
# 4. Physical artifact mapping
`document_artifacts.json` должен содержать относительный путь файла в архиве.
Требования:
- только относительные пути;
- только внутри `artifacts/`;
- запрещены абсолютные пути;
- запрещены `..`;
- запрещены path traversal;
- расширение должно соответствовать `format`.
При import путь из archive не должен напрямую становиться filesystem path.
Сначала:
```text
validate archive_path
↓
resolve destination through server-side storage builder
```
---
# 5. Manifest
Расширить существующий `manifest.json`.
Добавить информацию о:
```json
"document_artifacts": {
"count": 4
}
```
или эквивалентное поле в существующем формате manifest.
Не ломать старые archive.
Если `document_artifacts.json` отсутствует в старом `.wvt.zip`:
```text
artifact count = 0
```
и import продолжается нормально.
---
# 6. Checksums
Физические artifact files должны участвовать в существующем `checksums.json`.
При export:
- checksum считается от фактических bytes файла;
- он должен совпадать с `DocumentArtifact.content_hash`.
Если не совпадает:
- export завершается ошибкой;
- архив не считается валидным.
При import:
1. проверить checksum архива;
2. прочитать bytes;
3. проверить SHA-256;
4. сравнить с `document_artifacts.json.content_hash`;
5. только после этого писать файл.
---
# 7. Export rules
В export включать только:
```text
KS2 status IN (issued, cancelled)
KS3 status IN (issued, cancelled)
```
и соответствующие artifacts.
Draft artifacts:
- не экспортировать;
- не добавлять в `document_artifacts.json`;
- не добавлять в manifest count;
- не добавлять в checksums.
Если issued/cancelled document существует, но artifact отсутствует:
экспорт должен завершиться контролируемой ошибкой.
Не создавать artifact автоматически во время export.
Причина:
```text
Export ≠ render
```
---
# 8. Export consistency
Перед добавлением artifact в архив проверить:
- document exists;
- document belongs to project;
- document status is issued/cancelled;
- artifact belongs to same project;
- artifact document_type/document_id совпадают;
- format ожидаемый;
- physical file exists;
- hash корректный.
Для cancelled:
- экспортируется исходный issued artifact;
- новый `СТОРНИРОВАН` файл не создаётся.
---
# 9. Import validation — до DB mutation
Все новые проверки выполняются до изменения основной БД.
Проверить:
### Archive structure
- `document_artifacts.json` существует, если manifest заявляет artifacts;
- все заявленные files существуют;
- нет лишних artifact references;
- archive paths безопасны.
### JSON
- valid JSON;
- required fields;
- correct types;
- allowed document_type;
- allowed format;
- template_type/version;
- hash format;
- generated_at.
### Links
`document_export_id` должен существовать среди:
- KS-2 export IDs;
- KS-3 export IDs.
Неизвестный document export ID → reject.
### Status
Artifact может относиться только к:
- issued;
- cancelled.
Artifact для draft → reject.
### Counts
Manifest count = количество artifact records.
### Checksums
Для каждого physical file:
```text
archive checksum
==
actual SHA-256
==
DocumentArtifact.content_hash
```
---
# 10. Import transaction
Существующий принцип Project Import сохраняется:
```text
validate archive
↓
begin transaction
↓
create project and all dependent entities
↓
remap document IDs
↓
create DocumentArtifact rows
↓
write physical artifact files
↓
commit
```
Если любая ошибка:
- DB rollback;
- физические файлы этой попытки удалить;
- ранее существующее project storage не трогать.
Не оставлять orphan files.
---
# 11. New IDs
После import:
```text
old project_id
≠
new project_id
old KS2.id
≠
new KS2.id
old KS3.id
≠
new KS3.id
old artifact.id
≠
new artifact.id
```
Связи строятся через export IDs.
Например:
```text
KS2 export_id
↓
new KS2.id
↓
new DocumentArtifact.document_id
```
`source_id` не используется для remapping.
---
# 12. Storage after import
Новые файлы должны попасть в:
```text
<storage_root>/
projects/
<NEW_PROJECT_ID>/
documents/
KS2/
<NEW_KS2_ID>/
...
KS3/
<NEW_KS3_ID>/
...
```
Не восстанавливать исходный абсолютный filesystem path.
`storage_key` строится сервером.
---
# 13. Artifact metadata
После import сохранить:
- document_type;
- document_id (новый);
- format;
- template_type;
- template_version;
- content_hash;
- input_hash;
- is_current;
- generated_at.
Создаваемый artifact получает новый DB `id`.
`created_at` / `updated_at` можно сформировать как при обычном import, если текущая модель не предусматривает историческое сохранение этих полей.
Не менять исходный `content_hash` и `input_hash`.
---
# 14. Current artifact rule
Для каждого imported issued/cancelled document должен быть восстановлен тот же логический current artifact:
```text
is_current = true
```
Не создавать дополнительные artifacts.
Если archive содержит несколько artifacts одного документа:
- следовать существующей модели historical artifacts;
- сохранить `is_current` как в archive;
- не допускать более одного current для одного document+format.
В нормальном DOC-B7 archive ожидается один current artifact на документ.
---
# 15. Backward compatibility
Старые `.wvt.zip`, созданные до DOC-B7, должны импортироваться.
Если отсутствуют:
```text
document_artifacts.json
artifacts/
```
то:
- import проекта проходит как раньше;
- DocumentArtifact rows не создаются;
- imported project остаётся валидным;
- это не считается ошибкой.
Нельзя требовать artifacts от старых archive.
---
# 16. Import → Export round-trip
Обязательный сценарий:
```text
Project A
↓
Export
↓
Reset
↓
Import
↓
Project B
↓
Export
```
Проверить:
- KS-2/KS-3 artifacts присутствуют;
- physical files присутствуют;
- bytes совпадают;
- `content_hash` совпадает;
- `input_hash` совпадает;
- template_type/version совпадают;
- `is_current` совпадает;
- document status совпадает;
- новые IDs используются;
- второй export снова содержит artifacts.
Для cancelled:
- исходный artifact bytes совпадают;
- статус cancelled сохраняется;
- новый `СТОРНИРОВАН` derivative не появляется.
---
# 17. Existing export/import data
Не изменять семантику существующих JSON:
```text
project.json
boq_documents.json
systems.json
sections.json
work_items.json
agreements.json
agreement_items.json
daily_reports.json
daily_report_items.json
ks2.json
ks2_items.json
ks2_item_sources.json
ks3.json
ks3_ks2.json
payments.json
payment_allocations.json
work_journal_entries.json
```
Добавляется только необходимый artifact слой.
Если текущий manifest имеет другую структуру counts — встроить `document_artifacts` в неё, не ломая существующие consumers.
---
# 18. Security
Import не должен позволять archive управлять filesystem.
Запрещены:
```text
../../...
/etc/...
C:\...
\server\...
```
Не использовать archive filename как конечный storage filename.
Для каждого artifact:
```text
archive bytes
↓
validated metadata
↓
server-generated storage_key
↓
safe destination
```
При ошибке checksum файл не должен становиться доступным через download endpoint.
---
# 19. Tests
Минимальный набор.
## Export
1. issued KS-2 artifact попадает в archive;
2. issued KS-3 artifact попадает в archive;
3. cancelled KS-2 artifact попадает в archive;
4. cancelled KS-3 artifact попадает в archive;
5. draft artifact не попадает;
6. manifest count корректен;
7. `document_artifacts.json` корректен;
8. physical files присутствуют;
9. checksums корректны;
10. content_hash совпадает с bytes;
11. отсутствующий artifact → controlled export error;
12. повреждённый artifact → export error.
## Import
13. valid archive восстанавливает artifact;
14. imported artifact получает новый DB id;
15. document_id remapped;
16. project_id remapped;
17. storage path использует новый project/document IDs;
18. bytes совпадают;
19. content_hash совпадает;
20. input_hash совпадает;
21. cancelled artifact восстанавливается;
22. old archive без artifacts импортируется;
23. неизвестный document_export_id → reject;
24. artifact для draft → reject;
25. checksum mismatch → reject;
26. archive path traversal → reject;
27. missing artifact file → reject;
28. manifest count mismatch → reject;
29. rollback удаляет физические files при ошибке;
30. существующие файлы другого project не затрагиваются.
## Round-trip
31. export → reset → import → export;
32. artifacts сохраняются;
33. bytes/hash сохраняются;
34. statuses сохраняются;
35. new IDs корректно remapped.
---
# 20. Browser/manual check
Проверить на реальном проекте:
1. есть issued KS-2 с official artifact;
2. есть issued KS-3 с official artifact;
3. есть cancelled document с сохранённым artifact;
4. export project;
5. reset;
6. import archive;
7. открыть imported project;
8. открыть KS-2/KS-3;
9. нажать «Официальная форма»;
10. проверить, что скачанный файл открывается;
11. проверить cancelled badge;
12. повторно export imported project.
Новая UI для artifact export/import не требуется — используется существующий Project Export/Import.
---
# 21. No scope creep
В DOC-B7 НЕ делать:
- новый UI;
- новый artifact renderer;
- новый storage system;
- PDF;
- regeneration;
- cancelled derivative;
- database reset changes;
- изменения KS-2/KS-3 lifecycle;
- изменения DocumentArtifact schema без необходимости;
- удаление draft artifacts из storage;
- перенос arbitrary historical artifacts, если текущий Project Export их не поддерживает.
---
# 22. Acceptance criteria
- [ ] `.wvt.zip` содержит `document_artifacts.json` для официальных artifacts.
- [ ] Physical XLSX/DOCX artifacts входят в archive.
- [ ] Checksums включают physical artifact files.
- [ ] `content_hash` совпадает с physical bytes.
- [ ] Draft artifacts не экспортируются.
- [ ] Issued/cancelled artifacts экспортируются.
- [ ] Import валидирует artifacts до DB mutation.
- [ ] `document_export_id` remapped через export IDs.
- [ ] New project/document IDs используются в storage.
- [ ] `storage_key` строится сервером.
- [ ] Path traversal невозможен.
- [ ] Rollback удаляет physical files failed import.
- [ ] Старые archives без artifacts импортируются.
- [ ] Export → Reset → Import → Export сохраняет artifacts.
- [ ] Cancelled сохраняет исходный artifact.
- [ ] Полный pytest проходит.
- [ ] `git diff --check` чистый.
- [ ] Browser/manual check выполнен.
---
# 23. Implementation report
После реализации предоставить:
1. изменённые файлы;
2. итоговую структуру `.wvt.zip`;
3. формат `document_artifacts.json`;
4. правила export;
5. правила import;
6. remap strategy;
7. checksum/hash verification;
8. rollback/cleanup strategy;
9. backward compatibility;
10. round-trip result;
11. тесты и итоговое количество;
12. browser/manual checks;
13. deviations, если есть;
14. следующую рекомендуемую задачу.
Не менять несвязанные части проекта.
@@ -0,0 +1,420 @@
"""Tests for DOC-B7: Export/Import DocumentArtifact."""
from __future__ import annotations
import hashlib
import io
import json
import zipfile
from datetime import date
from decimal import Decimal
import pytest
from sqlalchemy import create_engine
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.exporters.project_export import export_project
from app.exporters.project_import import ProjectImportError, import_project, validate_archive
from app.models import ( # noqa: F401
agreement, boq, daily_report, document_artifact,
ks2, ks3, 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.services.database_reset import reset_database
from app.services.document_artifact_service import compute_content_hash, 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 / "b7-storage"))
return tmp_path / "b7-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()
def _seed(db):
p = Project(name="B7 export", status="active")
db.add(p)
db.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db.add(doc)
db.flush()
wi = WorkItem(project_id=p.id, boq_document_id=doc.id, name="W", unit="шт",
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"))
db.add(wi)
db.flush()
dr = DailyReport(project_id=p.id, report_date=date(2026, 2, 1))
db.add(dr)
db.flush()
db.add(DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("50")))
db.commit()
return p.id, wi.id
def _issue_ks2(db, pid, wi_id, number="K2-B7"):
draft = save_ks2_draft(db, pid, number, date(2026, 3, 1), None,
[(wi_id, Decimal("10"))],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db.commit()
return issue_ks2(db, pid, draft.id)
def _issue_ks3(db, pid, ks2_id, number="K3-B7"):
draft = save_ks3_draft(db, pid, number, date(2026, 4, 1), None, [ks2_id],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db.commit()
return issue_ks3(db, pid, draft.id)
# ---------------------------------------------------------------------------
# Export
# ---------------------------------------------------------------------------
def test_export_includes_issued_ks2_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
assert "document_artifacts.json" in zf.namelist()
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 1
assert arts[0]["document_type"] == "KS2"
assert arts[0]["format"] == "xlsx"
assert arts[0]["document_export_id"] == "ks2:00000001"
assert arts[0]["is_current"] is True
assert "artifacts/ks2/" in arts[0]["archive_path"]
# Physical file present
assert arts[0]["archive_path"] in zf.namelist()
# Checksum matches
file_bytes = zf.read(arts[0]["archive_path"])
assert compute_content_hash(file_bytes) == arts[0]["content_hash"]
def test_export_includes_issued_ks3_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
ks3 = _issue_ks3(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
ks3_arts = [a for a in arts if a["document_type"] == "KS3"]
assert len(ks3_arts) == 1
assert ks3_arts[0]["format"] == "docx"
assert ks3_arts[0]["archive_path"] in zf.namelist()
def test_export_includes_cancelled_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 1
assert arts[0]["document_type"] == "KS2"
# Cancelled artifact is the original issued one
assert arts[0]["is_current"] is True
def test_export_skips_draft_artifacts(db_session):
pid, wi_id = _seed(db_session)
# Create a draft KS-2 (no artifact)
save_ks2_draft(db_session, pid, "K2-D", date(2026, 3, 1), None,
[(wi_id, Decimal("5"))],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db_session.commit()
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
arts = json.loads(zf.read("document_artifacts.json"))
assert len(arts) == 0
assert not any(n.startswith("artifacts/") for n in zf.namelist())
def test_export_manifest_count(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
manifest = json.loads(zipfile.ZipFile(io.BytesIO(data)).read("manifest.json"))
assert manifest["counts"]["document_artifacts"] == 1
def test_export_checksums_include_artifact_files(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zf = zipfile.ZipFile(io.BytesIO(data))
checksums = json.loads(zf.read("checksums.json"))
art = json.loads(zf.read("document_artifacts.json"))[0]
assert art["archive_path"] in checksums
# ---------------------------------------------------------------------------
# Import
# ---------------------------------------------------------------------------
def test_import_restores_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.document_type == "KS2"
assert art.format == "xlsx"
assert art.is_current is True
assert art.template_type == "ks2"
assert art.template_version == 1
# New IDs
assert art.project_id == imported.id
new_ks2 = db_session.query(KS2).filter_by(project_id=imported.id).one()
assert art.document_id == new_ks2.id
# File exists
path = resolve_storage_path(art.storage_key)
assert path.is_file()
# content_hash matches
assert art.content_hash == compute_content_hash(path.read_bytes())
def test_import_preserves_hashes_and_template(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
orig_art = db_session.query(DocumentArtifact).filter_by(project_id=pid).one()
ch, ih = orig_art.content_hash, orig_art.input_hash
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.content_hash == ch
assert art.input_hash == ih
assert art.template_type == "ks2"
assert art.template_version == 1
def test_import_cancelled_artifact(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
assert art.is_current is True
assert resolve_storage_path(art.storage_key).is_file()
def test_old_archive_without_artifacts_imports(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Strip document_artifacts.json and artifact files (old archive format)
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()
if n != "document_artifacts.json" and not n.startswith("artifacts/")}
zin.close()
checksums = json.loads(parts["checksums.json"].decode("utf-8"))
for k in list(checksums):
if k.startswith("artifacts/") or k == "document_artifacts.json":
del checksums[k]
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
old = buf.getvalue()
preview = validate_archive(old)
assert preview["counts"]["document_artifacts"] == 0
reset_database(db_session)
imported = import_project(db_session, old)
assert db_session.query(DocumentArtifact).filter_by(project_id=imported.id).count() == 0
def test_import_unknown_document_export_id_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Corrupt document_export_id
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
arts = json.loads(parts["document_artifacts.json"].decode("utf-8"))
arts[0]["document_export_id"] = "ks2:99999999"
parts["document_artifacts.json"] = json.dumps(arts).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="document_export_id"):
validate_archive(buf.getvalue())
def test_import_draft_artifact_rejected(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Change KS-2 status to draft in the archive
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
ks2_rows = json.loads(parts["ks2.json"].decode("utf-8"))
ks2_rows[0]["status"] = "draft"
parts["ks2.json"] = json.dumps(ks2_rows).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="issued/cancelled"):
validate_archive(buf.getvalue())
def test_import_checksum_mismatch_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
# Tamper with artifact file bytes but keep document_artifacts.json hash
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
art = json.loads(parts["document_artifacts.json"].decode("utf-8"))[0]
parts[art["archive_path"]] = b"tampered"
# Update checksums to match tampered file (so checksum check passes)
# but content_hash in JSON won't match
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="hash mismatch|сумма"):
validate_archive(buf.getvalue())
def test_import_path_traversal_rejected(db_session):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist()}
zin.close()
arts = json.loads(parts["document_artifacts.json"].decode("utf-8"))
arts[0]["archive_path"] = "artifacts/../../etc/passwd.xlsx"
parts["document_artifacts.json"] = json.dumps(arts).encode("utf-8")
checksums = {n: hashlib.sha256(b).hexdigest() for n, b in parts.items() if n != "checksums.json"}
parts["checksums.json"] = json.dumps(checksums).encode("utf-8")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zout:
for n, b in parts.items():
zout.writestr(n, b)
with pytest.raises(ProjectImportError, match="archive_path|небезопасный"):
validate_archive(buf.getvalue())
# ---------------------------------------------------------------------------
# Round-trip
# ---------------------------------------------------------------------------
def test_roundtrip_export_reset_import_export(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
ks3 = _issue_ks3(db_session, pid, ks2.id)
data1, _ = export_project(db_session, pid)
arts1 = json.loads(zipfile.ZipFile(io.BytesIO(data1)).read("document_artifacts.json"))
assert len(arts1) == 2 # KS2 + KS3
reset_database(db_session)
imported = import_project(db_session, data1)
# Verify artifacts restored
new_arts = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).all()
assert len(new_arts) == 2
for art in new_arts:
assert art.is_current is True
path = resolve_storage_path(art.storage_key)
assert path.is_file()
assert art.content_hash == compute_content_hash(path.read_bytes())
# Second export
data2, _ = export_project(db_session, imported.id)
arts2 = json.loads(zipfile.ZipFile(io.BytesIO(data2)).read("document_artifacts.json"))
assert len(arts2) == 2
# Hashes match original
h1 = {a["content_hash"] for a in arts1}
h2 = {a["content_hash"] for a in arts2}
assert h1 == h2
# Statuses preserved
ks2_statuses = {r["status"] for r in json.loads(zipfile.ZipFile(io.BytesIO(data2)).read("ks2.json"))}
assert "issued" in ks2_statuses
def test_roundtrip_cancelled_artifact_preserved(db_session):
pid, wi_id = _seed(db_session)
ks2 = _issue_ks2(db_session, pid, wi_id)
cancel_ks2(db_session, pid, ks2.id)
orig_bytes = resolve_storage_path(
db_session.query(DocumentArtifact).filter_by(project_id=pid).one().storage_key
).read_bytes()
data, _ = export_project(db_session, pid)
reset_database(db_session)
imported = import_project(db_session, data)
art = db_session.query(DocumentArtifact).filter_by(project_id=imported.id).one()
new_bytes = resolve_storage_path(art.storage_key).read_bytes()
assert new_bytes == orig_bytes
# Cancelled status preserved
new_ks2 = db_session.query(KS2).filter_by(project_id=imported.id).one()
assert new_ks2.status == "cancelled"
def test_rollback_removes_physical_files_on_error(db_session, monkeypatch):
pid, wi_id = _seed(db_session)
_issue_ks2(db_session, pid, wi_id)
data, _ = export_project(db_session, pid)
art_count_before = db_session.query(DocumentArtifact).count()
# Force failure after artifact file write but before commit
from app.exporters import project_import as pi
original = pi._import_entities
def failing(db, payload):
project = original(db, payload)
raise RuntimeError("forced failure after artifact write")
monkeypatch.setattr(pi, "_import_entities", failing)
with pytest.raises(ProjectImportError):
import_project(db_session, data)
monkeypatch.setattr(pi, "_import_entities", original)
db_session.rollback()
# No new artifact rows from the failed import
assert db_session.query(DocumentArtifact).count() == art_count_before