397 lines
15 KiB
Python
397 lines
15 KiB
Python
"""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
|