From 9f7031232e2a01eda199f0e27938280d9eed9162 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=90=D1=80=D1=81=D0=B5=D0=BD=D1=82=D1=8C=D0=B5=D0=B2=20?= =?UTF-8?q?=D0=90=D0=BB=D0=B5=D0=BA=D1=81=D0=B0=D0=BD=D0=B4=D1=80?= Date: Mon, 28 Sep 2026 22:07:48 +0300 Subject: [PATCH] test: cover agreement to daily report to KS-2 integration chain --- .../030-agreement-dr-ks2-integration-tests.md | 89 ++++ .../030-agreement-dr-ks2-integration-tests.md | 129 ++++++ ...st_task030_agreement_dr_ks2_integration.py | 426 ++++++++++++++++++ 3 files changed, 644 insertions(+) create mode 100644 docs/implementation/030-agreement-dr-ks2-integration-tests.md create mode 100644 docs/tasks/030-agreement-dr-ks2-integration-tests.md create mode 100644 tests/test_task030_agreement_dr_ks2_integration.py diff --git a/docs/implementation/030-agreement-dr-ks2-integration-tests.md b/docs/implementation/030-agreement-dr-ks2-integration-tests.md new file mode 100644 index 0000000..3f85aee --- /dev/null +++ b/docs/implementation/030-agreement-dr-ks2-integration-tests.md @@ -0,0 +1,89 @@ +# Implementation Report — 030-agreement-dr-ks2-integration-tests + +### Status + +DONE + +### Сквозные сценарии, которые проверены + +1. **Approved ДС → существующая позиция (increase) → Daily Report → КС-2** + - effective plan: 100 + 20 = 120; + - DR факт 50; + - КС-2 на 30 закрывает тот же `WorkItem`; + - `KS2ItemSource` → `DailyReportItem`, quantity 30; + - balances: actual 50, closed 30, available 20; + - у КС-2 нет прямой ссылки на ДС. + +2. **Approved ДС → `new_position` → Daily Report → КС-2** + - до approve позиция отсутствует в effective plan; + - после approve: quantity 8, amount 40; + - DR + КС-2 по новому `WorkItem`; + - `KS2ItemSource` корректен; available = 0 после полного закрытия. + +3. **Частичное закрытие двумя КС-2** + - ДР 100 → КС-2 60 → доступно 40 → КС-2 40 → closed 100; + - две строки `KS2ItemSource` на один `DailyReportItem` (60 + 40). + +4. **Отказ при перезакрытии (over-close)** + - `save_draft` отклоняет запрос сверх available (валидация на этапе черновика); + - лишние `KS2ItemSource` не создаются. + +5. **Draft ДС не даёт ложного доступа** + - `new_position` draft не в effective plan; + - после approve становится доступным; + - без DR-факта КС-2 создать нельзя (available = 0). + +6. **`KS2ItemSource` разбивается по нескольким DailyReportItem** + - ДР 25 + ДР 35 → КС-2 40 → sources: 25 (DR1) + 15 (DR2). + +7. **Rollback / атомарность** + - черновик КС-2 валиден на save; + - уменьшение DR-факта перед issue → `issue_ks2` отклоняет; + - sources не создаются, статус остаётся `draft`. + +8. **Decrease через ДС → DR → КС-2** + - effective: 100 − 30 = 70; + - DR 20 → КС-2 20; тот же WorkItem, sources корректны. + +### Тесты + +Файл: `tests/test_task030_agreement_dr_ks2_integration.py` — **9 тестов**. + +Покрытие требований task: +- approved DS → existing WorkItem → DR → KS-2 ✓ +- approved DS → new_position → DR → KS-2 ✓ +- draft new_position недоступна до approve ✓ +- partial closing ✓ +- over-close rejection ✓ +- корректность KS2ItemSource ✓ +- rollback/атомарность при неуспешном закрытии ✓ + +Использованы существующие сервисные API (`add_existing_item`, `add_new_item`, `approve_agreement`, `build_effective_plan`, `save_draft`, `issue_ks2`, `build_work_item_balances`); инфраструктура тестов не дублировалась сверх минимальных fixtures. + +Результат `pytest -q`: + +``` +315 passed, 284 warnings in 25.42s +``` + +(306 существующих + 9 новых.) + +Результат `git diff --check`: + +``` +(без ошибок) +``` + +### Обнаруженные дефекты + +Не обнаружено. Поведение цепочки ДС → DR → КС-2 соответствует ожидаемой бизнес-логике. + +Уточнение реализации (не дефект): валидация доступного объёма выполняется **дважды** — при `save_draft` и повторно при `issue_ks2`. Это осознанная защита от гонок; тесты это фиксируют. + +### Production-код + +**Не изменялся.** Только тесты + отчёт. + +### Deviations + +None. diff --git a/docs/tasks/030-agreement-dr-ks2-integration-tests.md b/docs/tasks/030-agreement-dr-ks2-integration-tests.md new file mode 100644 index 0000000..eb0a169 --- /dev/null +++ b/docs/tasks/030-agreement-dr-ks2-integration-tests.md @@ -0,0 +1,129 @@ +# Задача 030 — Интеграционные тесты ДС → Daily Report → КС-2 + +## Цель + +Проверить существующую сквозную бизнес-цепочку: + +`Дополнительное соглашение → Daily Report → КС-2` + +Задача **только на тестирование**. Бизнес-логика, модели, маршруты и UI без необходимости не изменяются. + +## Что проверить + +### 1. Утвержденное ДС для существующей позиции + +Сценарий: + +1. Создать проект с базовым WorkItem. +2. Создать ДС в статусе `draft`. +3. Добавить к нему изменение существующей позиции (`increase` или другой допустимый сценарий). +4. Утвердить ДС. +5. Убедиться, что измененная позиция входит в effective plan. +6. Создать Daily Report по этой позиции с фактическим количеством. +7. Создать КС-2 и закрыть часть или весь фактический объем. +8. Проверить: + - КС-2 использует тот же `WorkItem`; + - создается корректная `KS2ItemSource`; + - закрытый объем уменьшается из доступного; + - остаток рассчитывается как `actual - closed`; + - ДС не требуется как непосредственная ссылка из КС-2. + +### 2. Утвержденное ДС с новой позицией + +Сценарий: + +1. Создать ДС с `new_position`. +2. До утверждения убедиться, что новая позиция не доступна для Daily Report как рабочая позиция. +3. Утвердить ДС. +4. Убедиться, что новый WorkItem появился в effective plan. +5. Создать по нему Daily Report. +6. Создать КС-2. +7. Проверить корректное закрытие и `KS2ItemSource`. + +### 3. Частичное закрытие + +Для одной DailyReportItem: + +- фактический объем больше объема первого КС-2; +- первый КС-2 закрывает только часть; +- второй КС-2 закрывает остаток или следующую часть; +- итоговый `closed` не превышает `actual`; +- повторное закрытие сверх доступного отклоняется; +- связи `KS2ItemSource` сохраняются корректно. + +### 4. Draft ДС не должен давать ложного доступа + +Проверить отдельно: + +- draft ДС с новой позицией не попадает в рабочий набор позиций Daily Report; +- такая позиция не может быть закрыта в КС-2 до появления фактического Daily Report; +- после approve сценарий становится доступным согласно существующей бизнес-логике. + +## Ограничения + +Не менять: + +- модель БД; +- правила effective plan; +- правила Daily Report; +- правила КС-2; +- API/UI, кроме минимальных исправлений только если тесты обнаружат реальный дефект существующей реализации. + +Если тест обнаруживает дефект бизнес-логики — **не исправлять его автоматически**. Зафиксировать в отчете как отдельный дефект/follow-up. + +Не добавлять новые бизнес-правила. + +## Тесты + +Добавить отдельный файл: + +`tests/test_task030_agreement_dr_ks2_integration.py` + +Покрыть как минимум: + +- approved DS → existing WorkItem → DR → KS-2; +- approved DS → new_position → DR → KS-2; +- draft new_position недоступна до approve; +- partial closing; +- over-close rejection; +- корректность `KS2ItemSource`; +- rollback/атомарность при неуспешном закрытии. + +Использовать существующие fixtures/helpers проекта и не дублировать инфраструктуру без необходимости. + +## Отчет + +Создать: + +`docs/implementation/030-agreement-dr-ks2-integration-tests.md` + +В отчете указать: + +- какие сквозные сценарии проверены; +- какие тесты добавлены; +- результат `pytest -q`; +- обнаруженные дефекты, если есть; +- были ли изменения production-кода; +- `git diff --check`. + +## Критерии готовности + +Задача считается выполненной, если: + +1. Все перечисленные сценарии покрыты тестами. +2. Полный `pytest -q` проходит. +3. Если обнаружены дефекты — они явно зафиксированы и не замаскированы изменением тестов. +4. Production-логика не менялась без отдельного обоснования. +5. `git diff --check` чистый. +6. Отчет создан. +7. Commit/push не выполнять. + +## Команда после выполнения + +Сообщить: + +- сколько тестов добавлено; +- сколько всего тестов проходит; +- какие дефекты обнаружены; +- менялся ли production-код; +- результат `git diff --check`. diff --git a/tests/test_task030_agreement_dr_ks2_integration.py b/tests/test_task030_agreement_dr_ks2_integration.py new file mode 100644 index 0000000..204aa41 --- /dev/null +++ b/tests/test_task030_agreement_dr_ks2_integration.py @@ -0,0 +1,426 @@ +"""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")