"""Tests for task 025: project export / import.""" from __future__ import annotations import io import json import zipfile from datetime import date, datetime 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 ( FORMAT_NAME, FORMAT_VERSION, REQUIRED_FILES, ProjectExportError, export_project, serialize_project, collect_project, ) from app.exporters.project_import import ( ProjectImportError, import_project, validate_archive, ) 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 fastapi.testclient import TestClient from app.routers import projects as project_router @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 _full_project(db): """Build a rich project covering every exported entity, including cancelled docs.""" p = Project( name="Саудовская Аравия", contract_number="РД-07-2026/01", contract_date=date(2026, 1, 10), customer="АО «Ремстрой»", currency="RUB", start_date=date(2026, 1, 1), end_date=date(2028, 11, 1), status="active", ) db.add(p) db.flush() wi = WorkItem( project_id=p.id, source_number="1", name="Монтаж трубы", model="M-1", manufacturer="Завод", unit="м", quantity=Decimal("12.500000"), unit_price=Decimal("482.42168"), amount=Decimal("6030.270000"), ) db.add(wi) db.flush() doc = BoqDocument( project_id=p.id, name="BOQ Import - Ведомость ОВ", version="1.0", source_file="ov.xlsx", document_number="БО-1", document_date=date(2026, 1, 5), contract="РД-07", ) db.add(doc) db.flush() wi.boq_document_id = doc.id system = System(project_id=p.id, code="OV", name="Отопление", sort_order=1) db.add(system) db.flush() section = Section(system_id=system.id, name="Раздел 1", sort_order=1) 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, 2, 1), title="Доп. работы", description="Описание", status="approved", ) db.add(agr) db.flush() ai = AgreementItem( agreement_id=agr.id, work_item_id=wi.id, change_type="increase", quantity_delta=Decimal("5.0000"), amount_delta=Decimal("2500.00"), source_row=1, source_number="1", source_name="Монтаж трубы", source_model="M-1", source_manufacturer="Завод", source_unit="м", source_unit_price=Decimal("500.00"), source_boq_document_id=doc.id, source_system_id=system.id, source_section_id=section.id, ) db.add(ai) dr = DailyReport(project_id=p.id, system_id=system.id, report_date=date(2026, 3, 1), notes="Смена") db.add(dr) db.flush() dri = DailyReportItem(daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("3.5000")) db.add(dri) db.flush() ks2_draft = KS2(project_id=p.id, number="K2-1", date=date(2026, 3, 2), status="draft") ks2_issued = KS2( project_id=p.id, number="K2-2", date=date(2026, 3, 3), reporting_period_from=date(2026, 3, 1), reporting_period_to=date(2026, 3, 31), comment="Период", status="issued", ) ks2_cancelled = KS2(project_id=p.id, number="K2-3", date=date(2026, 3, 4), status="cancelled", comment="сторно") db.add_all([ks2_draft, ks2_issued, ks2_cancelled]) db.flush() ks2_item = KS2Item( ks2_id=ks2_issued.id, work_item_id=wi.id, quantity=Decimal("3.5000"), unit_price=Decimal("482.42168"), amount=Decimal("1688.47588"), ) db.add(ks2_item) db.flush() src = KS2ItemSource(ks2_item_id=ks2_item.id, daily_report_item_id=dri.id, quantity=Decimal("3.5000")) db.add(src) ks3_issued = KS3( project_id=p.id, number="K3-1", date=date(2026, 4, 1), reporting_period_from=date(2026, 3, 1), reporting_period_to=date(2026, 3, 31), status="issued", ) ks3_cancelled = KS3(project_id=p.id, number="K3-2", date=date(2026, 4, 2), status="cancelled") db.add_all([ks3_issued, ks3_cancelled]) db.flush() db.add(KS3KS2(ks3_id=ks3_issued.id, ks2_id=ks2_issued.id)) pay_active = Payment( project_id=p.id, date=date(2026, 5, 1), document_number="PL-1", amount=Decimal("25000.00"), currency="RUB", comment="Оплата", status="active", ) pay_cancelled = Payment( project_id=p.id, date=date(2026, 5, 2), document_number="PL-2", amount=Decimal("100.00"), currency="RUB", status="cancelled", ) db.add_all([pay_active, pay_cancelled]) db.flush() db.add(PaymentAllocation(payment_id=pay_active.id, ks3_id=ks3_issued.id, amount=Decimal("20000.00"))) db.add(PaymentAllocation(payment_id=pay_cancelled.id, ks3_id=ks3_issued.id, amount=Decimal("50.00"))) db.commit() return p.id # --------------------------------------------------------------------------- # Export # --------------------------------------------------------------------------- def test_export_zip_structure_manifest_checksums(db_session): pid = _full_project(db_session) data, filename = export_project(db_session, pid) assert filename.endswith(".wvt.zip") assert "Саудовская_Аравия" in filename or "Проект_" in filename zf = zipfile.ZipFile(io.BytesIO(data)) names = set(zf.namelist()) assert set(REQUIRED_FILES) <= names assert "work_tracker.db" not in names manifest = json.loads(zf.read("manifest.json").decode("utf-8")) assert manifest["format"] == FORMAT_NAME assert manifest["format_version"] == FORMAT_VERSION assert manifest["project_name"] == "Саудовская Аравия" assert manifest["counts"]["work_items"] == 1 assert manifest["counts"]["ks2"] == 3 assert manifest["counts"]["payments"] == 2 checksums = json.loads(zf.read("checksums.json").decode("utf-8")) import hashlib for name in REQUIRED_FILES: if name == "checksums.json": continue actual = hashlib.sha256(zf.read(name)).hexdigest() assert checksums[name] == actual def test_export_uses_export_id_links_and_decimal_strings(db_session): pid = _full_project(db_session) graph = collect_project(db_session, pid) files = serialize_project(graph) items = files["work_items.json"] assert items[0]["export_id"] == "work_item:00000001" # Numeric columns: quantity(15,4), unit_price/amount(18,12) — string Decimal, no float assert items[0]["quantity"] == "12.5" assert items[0]["unit_price"] == "482.42168" assert items[0]["amount"] == "6030.27" assert isinstance(items[0]["quantity"], str) assert items[0]["boq_document_export_id"] == "boq_document:00000001" src = files["ks2_item_sources.json"][0] assert src["ks2_item_export_id"].startswith("ks2_item:") assert src["daily_report_item_export_id"].startswith("daily_report_item:") assert src["quantity"] == "3.5" cancelled = {r["status"] for r in files["ks2.json"]} assert "cancelled" in cancelled assert {r["status"] for r in files["payments.json"]} == {"active", "cancelled"} def test_export_rejects_broken_references(db_session): pid = _full_project(db_session) # Break a reference wi = db_session.query(WorkItem).first() wi.system_id = 99999 db_session.commit() with pytest.raises(ProjectExportError): export_project(db_session, pid) # --------------------------------------------------------------------------- # Import happy path # --------------------------------------------------------------------------- def test_import_full_project_creates_new_ids_and_preserves_history(db_session): src_pid = _full_project(db_session) data, _ = export_project(db_session, src_pid) imported = import_project(db_session, data) assert imported.id != src_pid assert imported.name == "Саудовская Аравия" assert imported.contract_number == "РД-07-2026/01" assert imported.contract_date == date(2026, 1, 10) # All entity types restored assert db_session.query(BoqDocument).filter_by(project_id=imported.id).count() == 1 assert db_session.query(System).filter_by(project_id=imported.id).count() == 1 assert db_session.query(Section).count() >= 1 assert db_session.query(WorkItem).filter_by(project_id=imported.id).count() == 1 assert db_session.query(Agreement).filter_by(project_id=imported.id).count() == 1 assert db_session.query(AgreementItem).count() >= 1 assert db_session.query(DailyReport).filter_by(project_id=imported.id).count() == 1 assert db_session.query(DailyReportItem).count() >= 1 assert db_session.query(KS2).filter_by(project_id=imported.id).count() == 3 assert db_session.query(KS2Item).count() >= 1 assert db_session.query(KS2ItemSource).count() >= 1 assert db_session.query(KS3).filter_by(project_id=imported.id).count() == 2 assert db_session.query(KS3KS2).count() >= 1 assert db_session.query(Payment).filter_by(project_id=imported.id).count() == 2 assert db_session.query(PaymentAllocation).count() >= 2 # FKs remapped to new IDs wi = db_session.query(WorkItem).filter_by(project_id=imported.id).one() doc = db_session.query(BoqDocument).filter_by(project_id=imported.id).one() assert wi.boq_document_id == doc.id assert wi.system_id is not None assert wi.section_id is not None # Decimal preserved exactly assert wi.quantity == Decimal("12.5000") assert wi.unit_price == Decimal("482.42168") assert wi.amount == Decimal("6030.27") # Dates preserved assert doc.document_date == date(2026, 1, 5) # Cancelled statuses preserved ks2_statuses = {k.status for k in db_session.query(KS2).filter_by(project_id=imported.id).all()} assert "cancelled" in ks2_statuses and "issued" in ks2_statuses pay_statuses = {p.status for p in db_session.query(Payment).filter_by(project_id=imported.id).all()} assert pay_statuses == {"active", "cancelled"} # Payment allocations + KS2 sources preserved cancelled_pay = db_session.query(Payment).filter_by(project_id=imported.id, status="cancelled").one() assert cancelled_pay.allocations, "cancelled payment allocations must be kept" ks2_items = db_session.query(KS2Item).join(KS2).filter(KS2.project_id == imported.id).all() assert any(i.sources for i in ks2_items) # Re-export of imported project is valid data2, _ = export_project(db_session, imported.id) validate_archive(data2) def test_import_twice_creates_separate_projects(db_session): pid = _full_project(db_session) data, _ = export_project(db_session, pid) a = import_project(db_session, data) b = import_project(db_session, data) assert a.id != b.id != pid assert a.name == b.name # --------------------------------------------------------------------------- # Negative / validation # --------------------------------------------------------------------------- def _corrupt_zip(mutate) -> bytes: 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) s = Session() pid = _full_project(s) data, _ = export_project(s, pid) s.close() engine.dispose() zin = zipfile.ZipFile(io.BytesIO(data)) parts = {n: zin.read(n) for n in zin.namelist()} zin.close() mutate(parts) buf = io.BytesIO() with zipfile.ZipFile(buf, "w") as zout: for n, b in parts.items(): zout.writestr(n, b) return buf.getvalue() def test_import_rejects_bad_checksum(): def mutate(parts): parts["project.json"] = parts["project.json"].replace( "Саудовская".encode("utf-8"), "Другой".encode("utf-8") ) with pytest.raises(ProjectImportError, match="Контрольная сумма"): validate_archive(_corrupt_zip(mutate)) def test_import_rejects_broken_json(): def mutate(parts): import hashlib parts["work_items.json"] = b"{not json" # keep checksum matching so we hit JSON error... actually checksum will fail first. # Rebuild checksums to pass checksum check and fail JSON parse. checksums = {} for name, body in parts.items(): if name == "checksums.json": continue checksums[name] = hashlib.sha256(body).hexdigest() parts["checksums.json"] = json.dumps(checksums).encode("utf-8") with pytest.raises(ProjectImportError, match="JSON"): validate_archive(_corrupt_zip(mutate)) def test_import_rejects_unknown_format(): def mutate(parts): import hashlib manifest = json.loads(parts["manifest.json"].decode("utf-8")) manifest["format"] = "alien" parts["manifest.json"] = json.dumps(manifest).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") with pytest.raises(ProjectImportError, match="format"): validate_archive(_corrupt_zip(mutate)) def test_import_rejects_unsupported_format_version(): def mutate(parts): import hashlib manifest = json.loads(parts["manifest.json"].decode("utf-8")) manifest["format_version"] = 99 parts["manifest.json"] = json.dumps(manifest).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") with pytest.raises(ProjectImportError, match="format_version"): validate_archive(_corrupt_zip(mutate)) def test_import_rejects_missing_required_file(): def mutate(parts): del parts["payments.json"] with pytest.raises(ProjectImportError, match="отсутствуют"): validate_archive(_corrupt_zip(mutate)) def test_import_rejects_broken_internal_reference(): def mutate(parts): import hashlib items = json.loads(parts["work_items.json"].decode("utf-8")) items[0]["system_export_id"] = "system:99999999" parts["work_items.json"] = json.dumps(items, ensure_ascii=False).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") with pytest.raises(ProjectImportError, match="битая ссылка"): validate_archive(_corrupt_zip(mutate)) def test_import_rollback_on_midway_error(db_session): pid = _full_project(db_session) data, _ = export_project(db_session, pid) before = db_session.query(Project).count() # Make insert fail after project row would be created: duplicate agreement number # by patching archive so two agreements share a number (caught in validation), # and separately force an insert error with an invalid required FK target. def mutate(parts): import hashlib items = json.loads(parts["payment_allocations.json"].decode("utf-8")) # valid refs in archive but we'll instead break validation of unique numbers agreements = json.loads(parts["agreements.json"].decode("utf-8")) # add a second agreement with same number by cloning first clone = dict(agreements[0]) clone["export_id"] = "agreement:00000099" agreements.append(clone) parts["agreements.json"] = json.dumps(agreements, ensure_ascii=False).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") broken = _corrupt_zip(mutate) with pytest.raises(ProjectImportError): import_project(db_session, broken) assert db_session.query(Project).count() == before def test_import_rejects_invalid_status(): def mutate(parts): import hashlib ks2 = json.loads(parts["ks2.json"].decode("utf-8")) ks2[0]["status"] = "bogus" parts["ks2.json"] = json.dumps(ks2, ensure_ascii=False).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") with pytest.raises(ProjectImportError, match="status"): validate_archive(_corrupt_zip(mutate)) # --------------------------------------------------------------------------- # HTTP smoke # --------------------------------------------------------------------------- def test_http_export_and_import_roundtrip(tmp_path): from tests.test_task024_payment_stornation import _ui_session # reuse helper if present 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() pid = _full_project(session) def override_db(): s = Session() try: yield s finally: s.close() app.dependency_overrides[project_router.get_db] = override_db try: with TestClient(app) as client: resp = client.get(f"/projects/{pid}/export/project") assert resp.status_code == 200 assert resp.headers["content-type"] == "application/zip" assert ".wvt.zip" in resp.headers["content-disposition"] archive = resp.content form = client.get("/projects/import") assert form.status_code == 200 and "Импорт проекта" in form.text up = client.post( "/projects/import/upload", files={"file": ("proj.wvt.zip", archive, "application/zip")}, ) assert up.status_code == 200 assert "Файл проверен" in up.text assert "Саудовская Аравия" in up.text # extract token import re m = re.search(r'name="token" value="([^"]+)"', up.text) assert m token = m.group(1) conf = client.post("/projects/import/confirm", data={"token": token}, follow_redirects=False) assert conf.status_code == 303 loc = conf.headers["location"] assert "/projects/" in loc and "imported=1" in loc new_id = int(loc.split("/projects/")[1].split("?")[0]) assert new_id != pid page = client.get(f"/projects/{new_id}?imported=1") assert "успешно импортирован" in page.text finally: app.dependency_overrides.pop(project_router.get_db, None) session.close() engine.dispose()