test: cover agreement export/reset/import round-trip and backward compatibility

This commit is contained in:
Арсентьев Александр
2026-09-28 22:22:04 +03:00
parent 9f7031232e
commit 11758a33e9
3 changed files with 671 additions and 0 deletions
@@ -0,0 +1,72 @@
# Implementation Report — 031-agreement-export-import
### Status
DONE
### Покрытые сценарии
1. **Полный цикл Export → Reset → Import** с тремя ДС:
- project-wide **draft** (increase);
- project-wide **approved** (decrease);
- scoped на ведомость **approved** (new_position + increase).
2. **Scope ДС:** `boq_document_id = NULL` и `!= NULL` — восстановление scope на сущности нового проекта.
3. **Lifecycle:** draft остаётся `draft`, approved остаётся `approved`, approved immutable (`_require_draft`).
4. **Типы изменений:** `increase` / `decrease` / `new_position` — все три в архиве и после импорта.
5. **new_position:** AgreementItem + WorkItem (qty 0, `boq_document_id=None`), `source_boq_document_id` remapped, связь AgreementItem → WorkItem восстановлена.
6. **Effective plan до/после:** quantities и amounts идентичны (A=80, B=65, new=5/35).
7. **Export ID:** `export_id` как архивные ключи (`agreement:…`, `work_item:…`), `source_id` только диагностика; внутренние ссылки строковые.
8. **Полный reset:** agreements/items/work_items удалены; импорт создаёт новый проект с полным графом.
9. **Обратная совместимость 025:** архив без `work_journal_entries.json` импортируется (с count 0).
### Тесты
Файл: `tests/test_task031_agreement_export_import.py` — **7 тестов**:
- `test_export_reset_import_agreements_full_cycle`
- `test_export_ids_are_archive_local`
- `test_scoped_and_project_wide_both_apply`
- `test_draft_stays_draft_and_does_not_affect_plan_after_import`
- `test_approved_remains_immutable_after_import`
- `test_old_archive_without_work_journal_still_imports`
- `test_reset_clears_agreements_and_items`
Результат `pytest -q`:
```
322 passed, 284 warnings in 26.91s
```
(315 существующих + 7 новых.)
Результат `git diff --check`:
```
(без ошибок)
```
### Export → Reset → Import
| Шаг | Результат |
|---|---|
| Export: 3 agreements, 4 items (increase/decrease/new_position) | ✓ |
| Scope: project-wide NULL, scoped → boq_document_export_id | ✓ |
| Statuses draft/approved в архиве | ✓ |
| Reset: 0 agreements/items/work_items/projects | ✓ |
| Import: 3 agreements с верными status/scope | ✓ |
| Remapping WorkItem / BoqDocument / source_boq | ✓ |
| Effective plan: A 80 / B 65 / new 5 (amount 35) | ✓ |
| Backward compat без work_journal_entries | ✓ |
### Обнаруженные дефекты
Не обнаружено.
Замечание (не дефект): после Reset SQLite может переиспользовать числовые ID (1, 2, 3…). Тесты корректно проверяют принадлежность сущностей импортированному проекту и разрешение ссылок внутри проекта, а не неравенство старых/новых ID.
### Production-код
**Не изменялся.** Только тесты + отчёт.
### Deviations
None.
+203
View File
@@ -0,0 +1,203 @@
# Задача 031 — Export/Reset/Import Additional Agreements
## Цель
Добавить интеграционные тесты для проверки полного цикла:
`Export проекта → Database Reset → Import проекта`
с особым вниманием к Additional Agreements (ДС).
Задача **только на тестирование**. Production-логику не менять без отдельного обоснования.
## Что проверить
### 1. Scope ДС
Проверить экспорт/импорт обоих вариантов:
- project-wide Agreement (`boq_document_id = NULL`);
- Agreement, привязанный к конкретной ведомости (`boq_document_id != NULL`).
После импорта связи должны указывать на новые сущности импортированного проекта, а не на старые DB ID.
### 2. Lifecycle
В одном проекте проверить наличие:
- draft Agreement;
- approved Agreement.
Оба должны корректно попасть в архив и восстановиться.
### 3. Типы изменений
Покрыть:
- `increase`;
- `decrease`;
- `new_position`.
Для `new_position` проверить одновременно:
- AgreementItem;
- созданный WorkItem;
- source/scope-поля;
- отсутствие старых DB ID после импорта;
- корректное восстановление связи AgreementItem → WorkItem.
### 4. Effective plan
До экспорта зафиксировать effective plan проекта.
После:
1. Export;
2. Database Reset;
3. Import;
проверить, что effective plan нового проекта соответствует исходному.
Важно проверить не только наличие записей, но и итоговые quantities/amounts.
### 5. Связи с BOQ
Для scoped Agreement проверить:
- `Agreement.boq_document_id`;
- `AgreementItem.source_boq_document_id`;
- `WorkItem.boq_document_id`.
После импорта все связи должны быть remapped на новые сущности.
### 6. Export IDs
Проверить, что:
- export_id сохраняются как идентификаторы архива;
- реальные DB ID нового проекта отличаются от исходных там, где это возможно;
- внутренние ссылки после импорта разрешаются через export_id;
- старые DB ID не используются как внешние ссылки.
### 7. Draft и approved
После импорта:
- draft остаётся `draft`;
- approved остаётся `approved`;
- approved Agreement остаётся immutable;
- effective plan учитывает только approved ДС;
- draft не начинает влиять на effective plan после импорта.
### 8. Полный reset
Использовать существующий Database Reset, не обходить его прямым удалением отдельных таблиц.
Проверить:
- после reset исходных проектов/ДС нет;
- после import создан новый проект;
- все Agreement/AgreementItem/WorkItem связи восстановлены.
## Тестовый сценарий
Рекомендуемый fixture:
1. Создать проект.
2. Создать основную BOQ.
3. Создать минимум одну дополнительную ведомость/контекст, если это требуется существующей моделью scoped DS.
4. Создать project-wide draft DS.
5. Создать approved project-wide DS.
6. Создать scoped approved DS.
7. Добавить `increase`, `decrease`, `new_position`.
8. Зафиксировать исходные:
- counts;
- statuses;
- scope;
- effective plan;
- ключевые связи.
9. Выполнить export.
10. Выполнить Database Reset.
11. Импортировать архив.
12. Найти новый Project.
13. Сравнить исходное состояние с восстановленным.
## Обратная совместимость
Добавить тест для уже существующего архива формата 025:
- архив без новых полей/сценариев ДС, насколько это возможно на существующей версии формата;
- импорт должен продолжать работать;
- отсутствие необязательных данных не должно ломать импорт.
Если для такого теста нет готового fixture — использовать минимальный существующий архив проекта и не создавать искусственно новый формат.
## Ограничения
Не менять:
- модель БД;
- формат экспорта;
- import service;
- effective plan;
- lifecycle Agreement;
- UI.
Если тест выявляет дефект — **не исправлять его в рамках 031**. Зафиксировать:
- воспроизводимый сценарий;
- ожидаемое поведение;
- фактическое поведение;
- возможную область дефекта.
## Файл тестов
Создать:
`tests/test_task031_agreement_export_import.py`
Использовать существующие fixtures/helpers проекта.
Не дублировать инфраструктуру Export/Reset/Import.
## Отчет
Создать:
`docs/implementation/031-agreement-export-import.md`
Указать:
- покрытые сценарии;
- количество новых тестов;
- результат полного `pytest -q`;
- результаты Export → Reset → Import;
- обнаруженные дефекты;
- изменения production-кода;
- `git diff --check`.
## Критерии готовности
1. Проверены project-wide и scoped DS.
2. Проверены draft и approved.
3. Проверены increase/decrease/new_position.
4. Проверен remapping всех ключевых связей.
5. Проверен effective plan до/после.
6. Проверены export_id и отсутствие зависимости от старых DB ID.
7. Проверен полный Export → Reset → Import.
8. Проверена обратная совместимость существующего формата 025.
9. Полный `pytest -q` проходит.
10. `git diff --check` чистый.
11. Production-код не менялся без отдельного обоснования.
12. Commit/push не выполнять.
## Команда после выполнения
Сообщить:
- сколько тестов добавлено;
- сколько всего проходит;
- какие сценарии покрыты;
- обнаружены ли дефекты;
- менялся ли production-код;
- результат `git diff --check`.
@@ -0,0 +1,396 @@
"""Integration tests for task 031: Agreement export/reset/import.
Test-only: no production code changes.
"""
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.database.database import Base
from app.exporters.project_export import export_project, serialize_project, collect_project
from app.exporters.project_import import ProjectImportError, import_project, validate_archive
from app.models.agreement import Agreement, AgreementItem
from app.models.boq import BoqDocument, Section, System, WorkItem
from app.models.project import Project
from app.services.agreement_items import add_existing_item, add_new_item
from app.services.database_reset import reset_database
from app.services.effective_plan import approve_agreement, build_effective_plan
ZERO = Decimal("0")
@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 _build_rich_project(db):
"""
Project with:
- base BOQ + two base work items;
- project-wide draft DS (increase on item A);
- project-wide approved DS (decrease on item A);
- scoped approved DS (new_position + increase on item B).
"""
p = Project(name="AGR export", contract_number="C-1", status="active")
db.add(p)
db.flush()
doc_a = BoqDocument(project_id=p.id, name="Ведомость А")
doc_b = BoqDocument(project_id=p.id, name="Ведомость Б")
db.add_all([doc_a, doc_b])
db.flush()
system = System(project_id=p.id, name="Система", sort_order=1)
db.add(system)
db.flush()
section = Section(system_id=system.id, name="Раздел", sort_order=1)
db.add(section)
db.flush()
item_a = WorkItem(
project_id=p.id, boq_document_id=doc_a.id, system_id=system.id,
section_id=section.id, source_number="1", name="Позиция А",
unit="шт", quantity=Decimal("100"), unit_price=Decimal("10"),
amount=Decimal("1000"),
)
item_b = WorkItem(
project_id=p.id, boq_document_id=doc_b.id, system_id=system.id,
section_id=section.id, source_number="2", name="Позиция Б",
unit="м", quantity=Decimal("50"), unit_price=Decimal("20"),
amount=Decimal("1000"),
)
db.add_all([item_a, item_b])
db.commit()
# project-wide draft: increase on A
draft_pw = Agreement(
project_id=p.id, number="D-PW-DRAFT", date=date(2026, 1, 1),
title="Черновик проектный", status="draft", boq_document_id=None,
)
db.add(draft_pw)
db.commit()
add_existing_item(db, draft_pw, item_a.id, Decimal("10"))
db.commit()
# project-wide approved: decrease on A
appr_pw = Agreement(
project_id=p.id, number="A-PW", date=date(2026, 1, 2),
title="Утверждённый проектный", status="draft", boq_document_id=None,
)
db.add(appr_pw)
db.commit()
add_existing_item(db, appr_pw, item_a.id, Decimal("-20"))
db.commit()
approve_agreement(db, appr_pw.id)
# scoped approved on doc_b: new_position + increase on B
appr_scoped = Agreement(
project_id=p.id, number="A-SCOPED", date=date(2026, 1, 3),
title="Утверждённый ведомостный", status="draft", boq_document_id=doc_b.id,
)
db.add(appr_scoped)
db.commit()
new_line = add_new_item(
db, appr_scoped,
name="Новая из ДС", model="M-1", manufacturer="Завод", unit="шт",
quantity_delta=Decimal("5"), unit_price=Decimal("7"),
system_id=system.id, source_boq_document_id=doc_b.id,
)
db.commit()
add_existing_item(db, appr_scoped, item_b.id, Decimal("15"))
db.commit()
approve_agreement(db, appr_scoped.id)
return {
"project_id": p.id,
"doc_a": doc_a.id,
"doc_b": doc_b.id,
"item_a": item_a.id,
"item_b": item_b.id,
"new_item": new_line.work_item_id,
"draft_pw": draft_pw.id,
"appr_pw": appr_pw.id,
"appr_scoped": appr_scoped.id,
}
def _plan_snapshot(db, project_id):
plan = build_effective_plan(db, project_id)
return {
row.item.id: (row.quantity, row.amount) for row in plan["items"]
}
def _plan_by_name(db, project_id):
plan = build_effective_plan(db, project_id)
return {
row.item.name: (row.quantity, row.amount) for row in plan["items"]
}
# ---------------------------------------------------------------------------
# Full Export → Reset → Import
# ---------------------------------------------------------------------------
def test_export_reset_import_agreements_full_cycle(db_session):
src = _build_rich_project(db_session)
plan_before = _plan_snapshot(db_session, src["project_id"])
plan_names_before = _plan_by_name(db_session, src["project_id"])
# --- Export ---
data, filename = export_project(db_session, src["project_id"])
assert filename.endswith(".wvt.zip")
zf = zipfile.ZipFile(io.BytesIO(data))
agr_json = json.loads(zf.read("agreements.json").decode("utf-8"))
itm_json = json.loads(zf.read("agreement_items.json").decode("utf-8"))
wi_json = json.loads(zf.read("work_items.json").decode("utf-8"))
assert len(agr_json) == 3
assert len(itm_json) == 4
# export_id style, not raw DB ids as primary keys
for row in agr_json:
assert row["export_id"].startswith("agreement:")
assert "source_id" in row
change_types = {r["change_type"] for r in itm_json}
assert change_types == {"increase", "decrease", "new_position"}
# new_position references a work_item with quantity 0 in archive
new_rows = [r for r in itm_json if r["change_type"] == "new_position"]
assert len(new_rows) == 1
new_wi_export_id = new_rows[0]["work_item_export_id"]
new_wi_row = next(r for r in wi_json if r["export_id"] == new_wi_export_id)
assert new_wi_row["quantity"] in ("0", "0.0", "0.0000", None) or Decimal(str(new_wi_row["quantity"])) == ZERO
# scoped agreement has boq_document_export_id
scoped_row = next(r for r in agr_json if r["number"] == "A-SCOPED")
assert scoped_row["boq_document_export_id"].startswith("boq_document:")
pw_row = next(r for r in agr_json if r["number"] == "A-PW")
assert pw_row["boq_document_export_id"] is None
# statuses preserved in archive
statuses = {r["number"]: r["status"] for r in agr_json}
assert statuses["D-PW-DRAFT"] == "draft"
assert statuses["A-PW"] == "approved"
assert statuses["A-SCOPED"] == "approved"
# --- Reset ---
reset_database(db_session)
assert db_session.query(Agreement).count() == 0
assert db_session.query(AgreementItem).count() == 0
assert db_session.query(WorkItem).count() == 0
assert db_session.query(Project).count() == 0
# --- Import ---
imported = import_project(db_session, data)
# SQLite may reuse numeric ids after reset; content is what matters
assert imported.name == "AGR export"
assert imported.contract_number == "C-1"
# Agreements restored with correct statuses and scope
new_agrs = {
a.number: a for a in db_session.query(Agreement).filter_by(project_id=imported.id)
}
assert set(new_agrs) == {"D-PW-DRAFT", "A-PW", "A-SCOPED"}
assert new_agrs["D-PW-DRAFT"].status == "draft"
assert new_agrs["A-PW"].status == "approved"
assert new_agrs["A-SCOPED"].status == "approved"
assert new_agrs["A-PW"].boq_document_id is None
assert new_agrs["A-SCOPED"].boq_document_id is not None
# Scope remapped to a BoqDocument of the imported project
new_scoped_doc_id = new_agrs["A-SCOPED"].boq_document_id
new_doc = db_session.get(BoqDocument, new_scoped_doc_id)
assert new_doc is not None
assert new_doc.project_id == imported.id
assert new_doc.name == "Ведомость Б"
# AgreementItems restored with remapped WorkItem links
all_new_items = (
db_session.query(AgreementItem)
.filter(AgreementItem.agreement_id.in_([a.id for a in new_agrs.values()]))
.all()
)
assert len(all_new_items) == 4
for line in all_new_items:
wi = db_session.get(WorkItem, line.work_item_id)
assert wi is not None
assert wi.project_id == imported.id
new_line_by_type = {}
for l in all_new_items:
new_line_by_type.setdefault(l.change_type, []).append(l)
assert set(new_line_by_type) == {"increase", "decrease", "new_position"}
assert len(new_line_by_type["new_position"]) == 1
# new_position WorkItem: qty 0, no boq_document_id, remapped source BOQ
new_pos_line = new_line_by_type["new_position"][0]
new_wi = db_session.get(WorkItem, new_pos_line.work_item_id)
assert Decimal(str(new_wi.quantity)) == ZERO
assert new_wi.boq_document_id is None
assert new_wi.name == "Новая из ДС"
assert new_pos_line.source_boq_document_id == new_scoped_doc_id
assert db_session.get(BoqDocument, new_pos_line.source_boq_document_id).project_id == imported.id
# Effective plan matches the source project (by name)
plan_after = _plan_snapshot(db_session, imported.id)
plan_names_after = _plan_by_name(db_session, imported.id)
assert plan_names_after == plan_names_before
# Quantities/amounts identical
assert sorted(plan_after.values()) == sorted(plan_before.values())
def test_export_ids_are_archive_local(db_session):
src = _build_rich_project(db_session)
data, _ = export_project(db_session, src["project_id"])
zf = zipfile.ZipFile(io.BytesIO(data))
itm_json = json.loads(zf.read("agreement_items.json").decode("utf-8"))
wi_json = json.loads(zf.read("work_items.json").decode("utf-8"))
# Internal links use export_id strings, never raw ints as FKs
for row in itm_json:
assert isinstance(row["work_item_export_id"], str)
assert row["work_item_export_id"].startswith("work_item:")
assert isinstance(row["agreement_export_id"], str)
# source_id is diagnostic only
assert all("source_id" in r for r in itm_json)
reset_database(db_session)
imported = import_project(db_session, data)
# New rows belong to the imported project (SQLite may reuse numeric ids)
new_agrs = db_session.query(Agreement).filter_by(project_id=imported.id).all()
assert len(new_agrs) == 3
assert all(a.project_id == imported.id for a in new_agrs)
new_wi = db_session.query(WorkItem).filter_by(project_id=imported.id).all()
assert all(w.project_id == imported.id for w in new_wi)
# Links resolve inside the imported project only
for line in db_session.query(AgreementItem).all():
assert line.agreement_id in {a.id for a in new_agrs}
# ---------------------------------------------------------------------------
# Effective plan / scope details
# ---------------------------------------------------------------------------
def test_scoped_and_project_wide_both_apply(db_session):
src = _build_rich_project(db_session)
plan_before = _plan_by_name(db_session, src["project_id"])
# Item A: 100 (base) - 20 (approved project-wide decrease) = 80
# (draft +10 is excluded)
assert plan_before["Позиция А"][0] == Decimal("80.0000")
# Item B: 50 + 15 (scoped increase) = 65
assert plan_before["Позиция Б"][0] == Decimal("65.0000")
# New position: 0 + 5 = 5
assert plan_before["Новая из ДС"][0] == Decimal("5.0000")
data, _ = export_project(db_session, src["project_id"])
reset_database(db_session)
imported = import_project(db_session, data)
plan_after = _plan_by_name(db_session, imported.id)
assert plan_after["Позиция А"][0] == Decimal("80.0000")
assert plan_after["Позиция Б"][0] == Decimal("65.0000")
assert plan_after["Новая из ДС"][0] == Decimal("5.0000")
assert plan_after["Новая из ДС"][1] == Decimal("35.000000000000")
def test_draft_stays_draft_and_does_not_affect_plan_after_import(db_session):
src = _build_rich_project(db_session)
data, _ = export_project(db_session, src["project_id"])
reset_database(db_session)
imported = import_project(db_session, data)
draft = db_session.query(Agreement).filter_by(
project_id=imported.id, number="D-PW-DRAFT"
).one()
assert draft.status == "draft"
# Draft still has its item
assert db_session.query(AgreementItem).filter_by(agreement_id=draft.id).count() == 1
# Effective plan excludes draft (same as source)
plan = build_effective_plan(db_session, imported.id)
# Only 3 plan rows: A, B, new_position
assert len(plan["items"]) == 3
def test_approved_remains_immutable_after_import(db_session):
src = _build_rich_project(db_session)
data, _ = export_project(db_session, src["project_id"])
reset_database(db_session)
imported = import_project(db_session, data)
approved = db_session.query(Agreement).filter_by(
project_id=imported.id, number="A-SCOPED"
).one()
assert approved.status == "approved"
# update endpoint should reject
from app.services.agreement_items import _require_draft
with pytest.raises(ValueError, match="draft"):
_require_draft(approved)
# ---------------------------------------------------------------------------
# Backward compatibility with 025 archive
# ---------------------------------------------------------------------------
def test_old_archive_without_work_journal_still_imports(db_session):
src = _build_rich_project(db_session)
data, _ = export_project(db_session, src["project_id"])
# Strip work_journal_entries like a Task 025 archive
zin = zipfile.ZipFile(io.BytesIO(data))
parts = {n: zin.read(n) for n in zin.namelist() if n != "work_journal_entries.json"}
zin.close()
checksums = json.loads(parts["checksums.json"].decode("utf-8"))
checksums.pop("work_journal_entries.json", None)
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"]["work_journal_entries"] == 0
reset_database(db_session)
imported = import_project(db_session, old)
agrs = db_session.query(Agreement).filter_by(project_id=imported.id).all()
assert len(agrs) == 3
plan = _plan_by_name(db_session, imported.id)
assert plan["Позиция А"][0] == Decimal("80.0000")
# ---------------------------------------------------------------------------
# Reset removes everything
# ---------------------------------------------------------------------------
def test_reset_clears_agreements_and_items(db_session):
src = _build_rich_project(db_session)
data, _ = export_project(db_session, src["project_id"])
reset_database(db_session)
assert db_session.query(Agreement).count() == 0
assert db_session.query(AgreementItem).count() == 0
assert db_session.query(WorkItem).count() == 0
# Import restores
import_project(db_session, data)
assert db_session.query(Agreement).count() == 3
assert db_session.query(AgreementItem).count() == 4