"""Integration tests for task 030: Agreement → Daily Report → KS-2 chain. Test-only: no production code changes. """ 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.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.project import Project from app.services.agreement_items import add_existing_item, add_new_item from app.services.effective_plan import approve_agreement, build_effective_plan from app.services.ks2_service import ( KS2ValidationError, build_work_item_balances, issue_ks2, save_draft, ) 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() @pytest.fixture def base_project(db_session): """Project with one base BOQ WorkItem (qty 100, price 10).""" p = Project(name="AGR-DR-KS2") db_session.add(p) db_session.flush() doc = BoqDocument(project_id=p.id, name="Base BOQ") db_session.add(doc) db_session.flush() system = System(project_id=p.id, name="System A", sort_order=1) db_session.add(system) db_session.flush() section = Section(system_id=system.id, name="Section A", sort_order=1) db_session.add(section) db_session.flush() item = WorkItem( project_id=p.id, boq_document_id=doc.id, system_id=system.id, section_id=section.id, source_number="1", name="Existing item", unit="pcs", quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"), ) db_session.add(item) db_session.commit() return { "project_id": p.id, "doc_id": doc.id, "system_id": system.id, "section_id": section.id, "item_id": item.id, } def _draft_agreement(db, project_id, number="A-1", boq_document_id=None): a = Agreement( project_id=project_id, number=number, date=date(2026, 1, 1), title=f"Agreement {number}", status="draft", boq_document_id=boq_document_id, ) db.add(a) db.commit() return a def _add_dr(db, project_id, work_item_id, qty, system_id=None): dr = DailyReport( project_id=project_id, system_id=system_id, report_date=date(2026, 2, 1) ) db.add(dr) db.flush() dri = DailyReportItem( daily_report_id=dr.id, work_item_id=work_item_id, completed_quantity=qty ) db.add(dri) db.commit() return dr, dri def _ks2(db, project_id, number, work_item_id, qty): draft = save_draft( db, project_id, number, date(2026, 3, 1), None, [(work_item_id, qty)], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) return issue_ks2(db, project_id, draft.id) # --------------------------------------------------------------------------- # 1. Approved DS → existing WorkItem → DR → KS-2 # --------------------------------------------------------------------------- def test_approved_increase_existing_item_dr_ks2_chain(db_session, base_project): pid = base_project["project_id"] item_id = base_project["item_id"] agreement = _draft_agreement(db_session, pid, "A-INC", base_project["doc_id"]) line = add_existing_item(db_session, agreement, item_id, Decimal("20")) db_session.commit() assert line.change_type == "increase" approve_agreement(db_session, agreement.id) plan = build_effective_plan(db_session, pid) plan_row = next(r for r in plan["items"] if r.item.id == item_id) assert plan_row.quantity == Decimal("120.0000") # 100 + 20 # Daily Report fact on the same canonical WorkItem dr, dri = _add_dr(db_session, pid, item_id, Decimal("50"), base_project["system_id"]) ks2 = _ks2(db_session, pid, "K2-1", item_id, Decimal("30")) assert ks2.status == "issued" # KS-2 uses the same WorkItem (not a separate agreement copy) ks2_item = db_session.query(KS2Item).filter_by(ks2_id=ks2.id).one() assert ks2_item.work_item_id == item_id # KS2ItemSource points at the DailyReportItem sources = db_session.query(KS2ItemSource).filter_by(ks2_item_id=ks2_item.id).all() assert len(sources) == 1 assert sources[0].daily_report_item_id == dri.id assert sources[0].quantity == Decimal("30") # available = actual - closed balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} b = balances[item_id] assert b.actual_quantity == Decimal("50") assert b.closed_quantity == Decimal("30") assert b.available_quantity == Decimal("20") # Agreement is not referenced from KS-2 assert not hasattr(ks2, "agreement_id") # --------------------------------------------------------------------------- # 2. Approved DS → new_position → DR → KS-2 # --------------------------------------------------------------------------- def test_approved_new_position_dr_ks2_chain(db_session, base_project): pid = base_project["project_id"] agreement = _draft_agreement(db_session, pid, "A-NEW", base_project["doc_id"]) line = add_new_item( db_session, agreement, name="New from agreement", model=None, manufacturer=None, unit="pcs", quantity_delta=Decimal("8"), unit_price=Decimal("5"), system_id=base_project["system_id"], source_boq_document_id=base_project["doc_id"], ) db_session.commit() new_item_id = line.work_item_id # Before approve: not in effective plan draft_plan_ids = {r.item.id for r in build_effective_plan(db_session, pid)["items"]} assert new_item_id not in draft_plan_ids approve_agreement(db_session, agreement.id) plan = build_effective_plan(db_session, pid) plan_row = next(r for r in plan["items"] if r.item.id == new_item_id) assert plan_row.quantity == Decimal("8.0000") assert plan_row.amount == Decimal("40.000000000000") # DR fact on the new item dr, dri = _add_dr(db_session, pid, new_item_id, Decimal("4"), base_project["system_id"]) ks2 = _ks2(db_session, pid, "K2-NEW", new_item_id, Decimal("4")) ks2_item = db_session.query(KS2Item).filter_by(ks2_id=ks2.id).one() assert ks2_item.work_item_id == new_item_id sources = db_session.query(KS2ItemSource).filter_by(ks2_item_id=ks2_item.id).all() assert len(sources) == 1 assert sources[0].daily_report_item_id == dri.id assert sources[0].quantity == Decimal("4") balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} assert balances[new_item_id].available_quantity == ZERO # --------------------------------------------------------------------------- # 3. Partial closing with two KS-2 # --------------------------------------------------------------------------- def test_partial_close_two_ks2(db_session, base_project): pid = base_project["project_id"] item_id = base_project["item_id"] _add_dr(db_session, pid, item_id, Decimal("100"), base_project["system_id"]) ks2_a = _ks2(db_session, pid, "K2-A", item_id, Decimal("60")) balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} assert balances[item_id].closed_quantity == Decimal("60") assert balances[item_id].available_quantity == Decimal("40") ks2_b = _ks2(db_session, pid, "K2-B", item_id, Decimal("40")) balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} assert balances[item_id].closed_quantity == Decimal("100") assert balances[item_id].available_quantity == ZERO # Both KS-2 keep their own KS2ItemSource rows total_source = sum( s.quantity for s in db_session.query(KS2ItemSource).all() ) assert total_source == Decimal("100") src_a = ( db_session.query(KS2ItemSource) .join(KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id) .filter(KS2Item.ks2_id == ks2_a.id) .one() ) src_b = ( db_session.query(KS2ItemSource) .join(KS2Item, KS2Item.id == KS2ItemSource.ks2_item_id) .filter(KS2Item.ks2_id == ks2_b.id) .one() ) assert src_a.daily_report_item_id == src_b.daily_report_item_id assert src_a.quantity == Decimal("60") assert src_b.quantity == Decimal("40") def test_overclose_rejected(db_session, base_project): pid = base_project["project_id"] item_id = base_project["item_id"] _add_dr(db_session, pid, item_id, Decimal("50"), base_project["system_id"]) _ks2(db_session, pid, "K2-1", item_id, Decimal("50")) # Over-close is rejected when saving the draft (available is already 0) with pytest.raises(KS2ValidationError, match="доступно|available"): save_draft( db_session, pid, "K2-OVER", date(2026, 3, 2), None, [(item_id, Decimal("1"))], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) # No extra sources created; only the first KS-2 source remains assert db_session.query(KS2ItemSource).count() == 1 # --------------------------------------------------------------------------- # 4. Draft DS gives no false access # --------------------------------------------------------------------------- def test_draft_new_position_hidden_from_daily_report(db_session, base_project): pid = base_project["project_id"] agreement = _draft_agreement(db_session, pid, "A-DRAFT", base_project["doc_id"]) line = add_new_item( db_session, agreement, name="Hidden until approve", model=None, manufacturer=None, unit="pcs", quantity_delta=Decimal("3"), unit_price=Decimal("7"), system_id=base_project["system_id"], source_boq_document_id=base_project["doc_id"], ) db_session.commit() new_item_id = line.work_item_id plan = build_effective_plan(db_session, pid) plan_ids = {r.item.id for r in plan["items"]} assert new_item_id not in plan_ids # Cannot create KS-2 for an item that has no DR fact and is not in plan balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} assert new_item_id not in balances # After approve it becomes available approve_agreement(db_session, agreement.id) plan = build_effective_plan(db_session, pid) assert new_item_id in {r.item.id for r in plan["items"]} def test_draft_item_cannot_be_closed_without_daily_report(db_session, base_project): """Even after approve, KS-2 needs a DR fact to allocate sources.""" pid = base_project["project_id"] item_id = base_project["item_id"] agreement = _draft_agreement(db_session, pid, "A-NOFACT", base_project["doc_id"]) add_existing_item(db_session, agreement, item_id, Decimal("10")) db_session.commit() approve_agreement(db_session, agreement.id) # No Daily Report yet → available is 0 (actual 0) balances = {b.item.id: b for b in build_work_item_balances(db_session, pid)} assert balances[item_id].actual_quantity == ZERO assert balances[item_id].available_quantity == ZERO with pytest.raises(KS2ValidationError, match="доступно|available"): save_draft( db_session, pid, "K2-NOFACT", date(2026, 3, 3), None, [(item_id, Decimal("1"))], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) # --------------------------------------------------------------------------- # 5. KS2ItemSource correctness + atomicity # --------------------------------------------------------------------------- def test_ks2_item_sources_split_across_daily_reports(db_session, base_project): pid = base_project["project_id"] item_id = base_project["item_id"] _, dri1 = _add_dr(db_session, pid, item_id, Decimal("25"), base_project["system_id"]) # second report same item dr2 = DailyReport( project_id=pid, system_id=base_project["system_id"], report_date=date(2026, 2, 5) ) db_session.add(dr2) db_session.flush() dri2 = DailyReportItem( daily_report_id=dr2.id, work_item_id=item_id, completed_quantity=Decimal("35") ) db_session.add(dri2) db_session.commit() ks2 = _ks2(db_session, pid, "K2-SPLIT", item_id, Decimal("40")) ks2_item = db_session.query(KS2Item).filter_by(ks2_id=ks2.id).one() sources = ( db_session.query(KS2ItemSource) .filter_by(ks2_item_id=ks2_item.id) .order_by(KS2ItemSource.id) .all() ) assert len(sources) == 2 assert sources[0].daily_report_item_id == dri1.id assert sources[0].quantity == Decimal("25") assert sources[1].daily_report_item_id == dri2.id assert sources[1].quantity == Decimal("15") assert sum(s.quantity for s in sources) == Decimal("40") def test_failed_issue_rolls_back_sources(db_session, base_project): pid = base_project["project_id"] item_id = base_project["item_id"] dr, dri = _add_dr(db_session, pid, item_id, Decimal("30"), base_project["system_id"]) sources_before = db_session.query(KS2ItemSource).count() # Draft is valid at save time (available 30) draft = save_draft( db_session, pid, "K2-ROLLBACK", date(2026, 3, 4), None, [(item_id, Decimal("30"))], reporting_period_from=date(2026, 2, 1), reporting_period_to=date(2026, 2, 28), ) # Shrink DR fact before issue → revalidation must fail dri.completed_quantity = Decimal("10") db_session.commit() with pytest.raises(KS2ValidationError, match="доступно|available|измен"): issue_ks2(db_session, pid, draft.id) assert db_session.query(KS2ItemSource).count() == sources_before assert db_session.get(KS2, draft.id).status == "draft" def test_decrease_via_agreement_then_dr_and_ks2(db_session, base_project): """Decrease changes planned qty; actual DR fact and KS-2 still use the same WorkItem.""" pid = base_project["project_id"] item_id = base_project["item_id"] agreement = _draft_agreement(db_session, pid, "A-DEC", base_project["doc_id"]) add_existing_item(db_session, agreement, item_id, Decimal("-30")) db_session.commit() approve_agreement(db_session, agreement.id) plan = build_effective_plan(db_session, pid) plan_row = next(r for r in plan["items"] if r.item.id == item_id) assert plan_row.quantity == Decimal("70.0000") # 100 - 30 _add_dr(db_session, pid, item_id, Decimal("20"), base_project["system_id"]) ks2 = _ks2(db_session, pid, "K2-DEC", item_id, Decimal("20")) ks2_item = db_session.query(KS2Item).filter_by(ks2_id=ks2.id).one() assert ks2_item.work_item_id == item_id sources = db_session.query(KS2ItemSource).filter_by(ks2_item_id=ks2_item.id).all() assert sum(s.quantity for s in sources) == Decimal("20")