"""Regression tests for AGR-02-FIX: free-to-close semantics on agreement cancellation.""" from __future__ import annotations 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.models import ( # noqa: F401 agreement, boq, daily_report, document_artifact, ks2, ks3, payment, project, work_journal, ) from app.models.agreement import Agreement, AgreementItem from app.models.boq import BoqDocument, System, WorkItem from app.models.daily_report import DailyReport, DailyReportItem from app.models.project import Project from app.services.agreement_items import ( add_existing_item, agreement_cancel_block_reason, cancel_agreement, ) from app.services.effective_plan import approve_agreement, build_effective_plan from app.services.ks2_service import issue_ks2, save_draft as save_ks2_draft @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 _make_project(db): p = Project(name="AGR-02-FIX") db.add(p) db.flush() doc = BoqDocument(project_id=p.id, name="BOQ") db.add(doc) db.flush() system = System(project_id=p.id, name="Система", sort_order=1) db.add(system) db.flush() return p, doc, system def _make_work_item(db, p, doc, system, qty, price="10"): wi = WorkItem( project_id=p.id, boq_document_id=doc.id, system_id=system.id, source_number="1", name="Позиция", model="М", manufacturer="П", unit="шт", quantity=Decimal(qty), unit_price=Decimal(price), amount=Decimal(qty) * Decimal(price), ) db.add(wi) db.flush() return wi def _make_agreement(db, p, number, doc=None): a = Agreement( project_id=p.id, number=number, date=date(2026, 1, 1), title=f"ДС {number}", status="draft", boq_document_id=doc.id if doc else None, ) db.add(a) db.flush() return a def _close_via_ks2(db, p, wi, qty, number="K2"): """Create DR + KS-2 that closes *qty* of *wi*, then issue it.""" 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(qty), )) db.commit() draft = save_ks2_draft( db, p.id, number, date(2026, 3, 1), None, [(wi.id, Decimal(qty))], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) db.commit() issue_ks2(db, p.id, draft.id) db.commit() # =========================================================================== # Single increase: base 3350, DS +20 # =========================================================================== def test_single_increase_closed_zero_can_cancel(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) assert agreement_cancel_block_reason(db_session, a) is None def test_single_increase_closed_3350_can_cancel(db_session): """Base fully closed, DS volume still free.""" p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3350") assert agreement_cancel_block_reason(db_session, a) is None def test_single_increase_closed_3351_cannot_cancel(db_session): """1 unit of DS volume used.""" p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3351") reason = agreement_cancel_block_reason(db_session, a) assert reason is not None assert "КС-2" in reason def test_single_increase_closed_3360_cannot_cancel(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3360") assert agreement_cancel_block_reason(db_session, a) is not None def test_single_increase_closed_3370_cannot_cancel(db_session): """Entire DS volume used.""" p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3370") assert agreement_cancel_block_reason(db_session, a) is not None # =========================================================================== # Multiple DS on one WorkItem: base 3350, DS1 +20, DS2 +30 # =========================================================================== def _make_two_agreements(db, p, doc, sys): wi = _make_work_item(db, p, doc, sys, "3350") a1 = _make_agreement(db, p, "DS-1", doc) add_existing_item(db, a1, wi.id, Decimal("20")) db.commit() approve_agreement(db, a1.id) a2 = _make_agreement(db, p, "DS-2", doc) add_existing_item(db, a2, wi.id, Decimal("30")) db.commit() approve_agreement(db, a2.id) return wi, a1, a2 def test_multi_ds_closed_3350_both_can_cancel(db_session): p, doc, sys = _make_project(db_session) wi, a1, a2 = _make_two_agreements(db_session, p, doc, sys) _close_via_ks2(db_session, p, wi, "3350") assert agreement_cancel_block_reason(db_session, a1) is None assert agreement_cancel_block_reason(db_session, a2) is None def test_multi_ds_closed_3360_ds1_cannot_ds2_can(db_session): """DS1 fully used (20), DS2 untouched.""" p, doc, sys = _make_project(db_session) wi, a1, a2 = _make_two_agreements(db_session, p, doc, sys) _close_via_ks2(db_session, p, wi, "3360") assert agreement_cancel_block_reason(db_session, a1) is not None # DS1 used assert agreement_cancel_block_reason(db_session, a2) is None # DS2 free def test_multi_ds_closed_3380_both_cannot_cancel(db_session): """DS1 fully used (20), DS2 partially used (10).""" p, doc, sys = _make_project(db_session) wi, a1, a2 = _make_two_agreements(db_session, p, doc, sys) _close_via_ks2(db_session, p, wi, "3380") assert agreement_cancel_block_reason(db_session, a1) is not None assert agreement_cancel_block_reason(db_session, a2) is not None # =========================================================================== # New position # =========================================================================== def test_new_position_closed_zero_can_cancel(db_session): p, doc, sys = _make_project(db_session) # New position: WorkItem with zero base qty wi = _make_work_item(db_session, p, doc, sys, "0") a = _make_agreement(db_session, p, "DS-NP", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) assert agreement_cancel_block_reason(db_session, a) is None def test_new_position_closed_10_cannot_cancel(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "0") a = _make_agreement(db_session, p, "DS-NP", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "10") assert agreement_cancel_block_reason(db_session, a) is not None def test_new_position_closed_20_cannot_cancel(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "0") a = _make_agreement(db_session, p, "DS-NP", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "20") assert agreement_cancel_block_reason(db_session, a) is not None # =========================================================================== # Cancelled KS-2 does not block # =========================================================================== def test_cancelled_ks2_does_not_block(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) # Create KS-2, issue it, then cancel it dr = DailyReport(project_id=p.id, report_date=date(2026, 2, 1)) db_session.add(dr) db_session.flush() db_session.add(DailyReportItem( daily_report_id=dr.id, work_item_id=wi.id, completed_quantity=Decimal("3360"), )) db_session.commit() draft = save_ks2_draft( db_session, p.id, "K2-C", date(2026, 3, 1), None, [(wi.id, Decimal("3360"))], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) db_session.commit() issue_ks2(db_session, p.id, draft.id) db_session.commit() # Cancel the KS-2 from app.services.ks2_service import cancel_ks2 cancel_ks2(db_session, p.id, draft.id) db_session.commit() # Cancelled KS-2 does not block DS cancellation assert agreement_cancel_block_reason(db_session, a) is None # =========================================================================== # Decrease — existing conservative semantics (any closed volume blocks) # =========================================================================== def test_decrease_with_closed_volume_blocked(db_session): """Existing semantics for decrease: any closed volume on WorkItem blocks.""" p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "100") a = _make_agreement(db_session, p, "DS-DEC", doc) add_existing_item(db_session, a, wi.id, Decimal("-20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "50") # Conservative: decrease blocked when any closed volume exists assert agreement_cancel_block_reason(db_session, a) is not None def test_decrease_without_closed_volume_can_cancel(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "100") a = _make_agreement(db_session, p, "DS-DEC", doc) add_existing_item(db_session, a, wi.id, Decimal("-20")) db_session.commit() approve_agreement(db_session, a.id) assert agreement_cancel_block_reason(db_session, a) is None # =========================================================================== # Atomicity # =========================================================================== def test_blocked_cancel_leaves_state_unchanged(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3360") with pytest.raises(ValueError, match="КС-2"): cancel_agreement(db_session, a) db_session.refresh(a) assert a.status == "approved" assert len(a.items) == 1 # no items deleted plan = build_effective_plan(db_session, p.id) wi_row = next(r for r in plan["items"] if r.item.id == wi.id) assert wi_row.quantity == Decimal("3370.0000") # base 3350 + DS 20 def test_successful_cancel_updates_plan(db_session): p, doc, sys = _make_project(db_session) wi = _make_work_item(db_session, p, doc, sys, "3350") a = _make_agreement(db_session, p, "DS-1", doc) add_existing_item(db_session, a, wi.id, Decimal("20")) db_session.commit() approve_agreement(db_session, a.id) _close_via_ks2(db_session, p, wi, "3350") cancel_agreement(db_session, a) db_session.refresh(a) assert a.status == "cancelled" plan = build_effective_plan(db_session, p.id) wi_row = next(r for r in plan["items"] if r.item.id == wi.id) assert wi_row.quantity == Decimal("3350.0000") # back to base