fix: agreement cancellation FIFO semantics, modal rendering, and list status badges

This commit is contained in:
Арсентьев Александр
2026-09-30 22:50:11 +03:00
parent 39adbf32e2
commit bc69e52174
16 changed files with 2056 additions and 16 deletions
+8 -6
View File
@@ -254,8 +254,9 @@ def test_cancel_rejected_when_work_item_closed_in_ks2(db_session, project_id):
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("50"))
_ks2_close(db_session, project_id, wi.id, Decimal("10"))
# base=100, DS=+10. Close 105 → 5 of DS volume used → block
_add_dr(db_session, project_id, wi.id, Decimal("105"))
_ks2_close(db_session, project_id, wi.id, Decimal("105"))
reason = agreement_cancel_block_reason(db_session, a)
assert reason is not None
@@ -334,8 +335,9 @@ def test_rollback_preserves_approved_status(db_session, project_id):
db_session.commit()
approve_agreement(db_session, a.id)
_add_dr(db_session, project_id, wi.id, Decimal("50"))
_ks2_close(db_session, project_id, wi.id, Decimal("10"))
# base=100, DS=+10. Close 105 → DS volume used → cancel must fail
_add_dr(db_session, project_id, wi.id, Decimal("105"))
_ks2_close(db_session, project_id, wi.id, Decimal("105"))
# cancel fails → rollback → still approved
with pytest.raises(ValueError):
@@ -397,8 +399,8 @@ def test_ui_cancelled_shows_otpmeneno(db_session, project_id):
page = client.get(f"/projects/{project_id}/agreements/{a.id}")
assert page.status_code == 200
assert "ОТМЕНЕНО" in page.text
assert "Отменить ДС" not in page.text
assert "Удалить ДС" not in page.text
assert 'data-bs-target="#cancelAgreementModal"' not in page.text
assert 'data-bs-target="#deleteAgreementModal"' not in page.text
finally:
app.dependency_overrides.clear()
+376
View File
@@ -0,0 +1,376 @@
"""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
+1 -2
View File
@@ -205,8 +205,7 @@ def test_http_no_delete_button_for_approved(db_session):
with TestClient(app) as client:
page = client.get(f"/projects/{pid}/agreements/{a.id}")
assert page.status_code == 200
assert "Удалить ДС" not in page.text
assert "deleteAgreementModal" not in page.text
assert 'data-bs-target="#deleteAgreementModal"' not in page.text
finally:
_clear()
+351
View File
@@ -0,0 +1,351 @@
"""Tests for UI-034: Additional Agreements interface fixes."""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
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.project import Project
from app.routers import agreements as agr_router, projects as project_router
from app.services.agreement_items import (
add_existing_item,
add_new_item,
cancel_agreement,
agreement_cancel_block_reason,
)
from app.services.effective_plan import approve_agreement, build_effective_plan
@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 ctx(db_session):
p = Project(name="UI-034")
db_session.add(p)
db_session.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db_session.add(doc)
db_session.flush()
system = System(project_id=p.id, name="Система А", sort_order=1)
db_session.add(system)
db_session.flush()
wi = WorkItem(
project_id=p.id, boq_document_id=doc.id, system_id=system.id,
source_number="1", name="Позиция", model="Модель",
manufacturer="Производитель", unit="шт",
quantity=Decimal("100"), unit_price=Decimal("10"), amount=Decimal("1000"),
)
db_session.add(wi)
db_session.commit()
return {"pid": p.id, "doc_id": doc.id, "sys_id": system.id, "wi_id": wi.id}
def _clear():
app.dependency_overrides.clear()
def _make_draft(db, ctx, number="A-1"):
a = Agreement(project_id=ctx["pid"], number=number, date=date(2026, 1, 1),
title="ДС", status="draft", boq_document_id=ctx["doc_id"])
db.add(a)
db.commit()
return a
# ---------------------------------------------------------------------------
# UI-034-01: Delete modal has only delete elements
# ---------------------------------------------------------------------------
def test_delete_modal_only_delete_elements(db_session, ctx):
a = _make_draft(db_session, ctx)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
# Delete modal exists
assert "deleteAgreementModal" in html
# Cancel modal is NOT nested inside delete modal button
# Find delete modal block
dm_start = html.find('id="deleteAgreementModal"')
cm_start = html.find('id="cancelAgreementModal"')
assert dm_start > 0
assert cm_start > 0
# Cancel modal should be AFTER delete modal, not inside its button
dm_end = html.find("</form></div></div></div>", dm_start)
assert cm_start > dm_end, "cancelAgreementModal must not be inside deleteAgreementModal"
# Delete modal has correct title
assert "Удалить черновик ДС" in html
# Delete modal has Удалить ДС button (not Отменить)
dm_block = html[dm_start:cm_start]
assert "Удалить ДС" in dm_block
assert "Отменить ДС" not in dm_block
finally:
_clear()
# ---------------------------------------------------------------------------
# UI-034-02: No duplicate delete button
# ---------------------------------------------------------------------------
def test_no_duplicate_delete_button(db_session, ctx):
a = _make_draft(db_session, ctx)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
# Count delete trigger buttons (outside modals)
import re
# Header delete button
header_btns = re.findall(r'data-bs-target="#deleteAgreementModal"', html)
assert len(header_btns) == 1, f"Expected 1 delete trigger, found {len(header_btns)}"
finally:
_clear()
# ---------------------------------------------------------------------------
# UI-034-03: Terminology
# ---------------------------------------------------------------------------
def test_draft_shows_delete_approved_shows_cancel(db_session, ctx):
a = _make_draft(db_session, ctx)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
# Draft: Удалить ДС
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
assert 'data-bs-target="#deleteAgreementModal"' in html
assert 'data-bs-target="#cancelAgreementModal"' not in html
# Approve
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
# Approved: Отменить ДС
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
assert 'data-bs-target="#cancelAgreementModal"' in html
assert 'data-bs-target="#deleteAgreementModal"' not in html
finally:
_clear()
def test_cancelled_shows_no_action(db_session, ctx):
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
assert "ОТМЕНЕНО" in html or "Отменено" in html
assert 'data-bs-target="#deleteAgreementModal"' not in html
assert 'data-bs-target="#cancelAgreementModal"' not in html
finally:
_clear()
# ---------------------------------------------------------------------------
# UI-034-04: No unexpected ? in position display
# ---------------------------------------------------------------------------
def test_positions_display_without_question_marks(db_session, ctx):
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
# data-label should use · not ?
import re
labels = re.findall(r'data-label="([^"]*)"', html)
for label in labels:
# No bare ? used as separator (allow ? in legitimate text)
assert " ? " not in label, f"Unexpected ? separator in: {label[:80]}"
# Position name displayed without ?
assert "Позиция" in html
assert "Модель" in html
finally:
_clear()
# ---------------------------------------------------------------------------
# UI-034-05: Cancel works for approved DS
# ---------------------------------------------------------------------------
def test_cancel_approved_ds_without_ks2(db_session, ctx):
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
assert a.status == "approved"
# Cancel should work
result = cancel_agreement(db_session, a)
assert result.status == "cancelled"
# Effective plan no longer includes it
plan = build_effective_plan(db_session, ctx["pid"])
wi_row = next(r for r in plan["items"] if r.item.id == ctx["wi_id"])
assert wi_row.quantity == Decimal("100.0000") # base only, no +10
# Double cancel impossible
with pytest.raises(ValueError, match="уже отменено"):
cancel_agreement(db_session, a)
def test_cancel_rejected_when_ks2_closed(db_session, ctx):
from app.services.ks2_service import issue_ks2, save_draft as save_ks2_draft
from app.models.daily_report import DailyReport, DailyReportItem
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
# Create DR + KS2 to close volume beyond base (base=100, DS=+10, close 105)
dr = DailyReport(project_id=ctx["pid"], 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=ctx["wi_id"], completed_quantity=Decimal("105")))
db_session.commit()
draft = save_ks2_draft(db_session, ctx["pid"], "K2-1", date(2026, 3, 1), None,
[(ctx["wi_id"], Decimal("105"))],
reporting_period_from=date(2026, 2, 1),
reporting_period_to=date(2026, 2, 28))
db_session.commit()
issue_ks2(db_session, ctx["pid"], draft.id)
# Cancel should be blocked
reason = agreement_cancel_block_reason(db_session, a)
assert reason is not None
assert "КС-2" in reason
with pytest.raises(ValueError, match="КС-2"):
cancel_agreement(db_session, a)
# Status unchanged
assert db_session.get(Agreement, a.id).status == "approved"
def test_cancel_http_endpoint(db_session, ctx):
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
resp = client.post(
f"/projects/{ctx['pid']}/agreements/{a.id}/cancel",
follow_redirects=False,
)
assert resp.status_code == 303
assert db_session.get(Agreement, a.id).status == "cancelled"
finally:
_clear()
# ---------------------------------------------------------------------------
# UI-034-FIX: regression — modal HTML must exist for approved status
# ---------------------------------------------------------------------------
def test_approved_shows_cancel_modal_html(db_session, ctx):
"""Cancel modal must be in the DOM when status=approved (not just the button)."""
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
# Button exists
assert 'data-bs-target="#cancelAgreementModal"' in html
# Modal HTML element must also exist
assert 'id="cancelAgreementModal"' in html
# Modal form action must be correct
assert f'action="/projects/{ctx["pid"]}/agreements/{a.id}/cancel"' in html
finally:
_clear()
def test_draft_shows_delete_modal_html(db_session, ctx):
"""Delete modal must be in the DOM when status=draft."""
a = _make_draft(db_session, ctx)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
assert 'data-bs-target="#deleteAgreementModal"' in html
assert 'id="deleteAgreementModal"' in html
finally:
_clear()
def test_cancelled_shows_no_modal_buttons(db_session, ctx):
"""Cancelled status: no cancel/delete modal triggers."""
a = _make_draft(db_session, ctx)
add_existing_item(db_session, a, ctx["wi_id"], Decimal("10"))
db_session.commit()
approve_agreement(db_session, a.id)
cancel_agreement(db_session, a)
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements/{a.id}").text
assert 'data-bs-target="#cancelAgreementModal"' not in html
assert 'data-bs-target="#deleteAgreementModal"' not in html
finally:
_clear()
+184
View File
@@ -0,0 +1,184 @@
"""Tests for UI-035: cancelled agreement status in list view."""
from __future__ import annotations
from datetime import date
from decimal import Decimal
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.database.database import Base
from app.main import app
from app.models import ( # noqa: F401
agreement, boq, daily_report, document_artifact,
ks2, ks3, payment, project, work_journal,
)
from app.models.agreement import Agreement
from app.models.boq import BoqDocument, System, WorkItem
from app.models.project import Project
from app.routers import agreements as agr_router, projects as project_router
from app.services.agreement_items import add_existing_item, cancel_agreement
from app.services.effective_plan import approve_agreement
@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 ctx(db_session):
p = Project(name="UI-035")
db_session.add(p)
db_session.flush()
doc = BoqDocument(project_id=p.id, name="BOQ")
db_session.add(doc)
db_session.flush()
system = System(project_id=p.id, name="S", sort_order=1)
db_session.add(system)
db_session.flush()
wi = WorkItem(
project_id=p.id, boq_document_id=doc.id, system_id=system.id,
source_number="1", name="Позиция", model="М", manufacturer="П",
unit="шт", quantity=Decimal("100"), unit_price=Decimal("10"),
amount=Decimal("1000"),
)
db_session.add(wi)
db_session.flush()
# Draft
a_draft = Agreement(
project_id=p.id, number="DS-D", date=date(2026, 1, 1),
title="Черновик", status="draft", boq_document_id=doc.id,
)
db_session.add(a_draft)
db_session.flush()
# Approved
a_approved = Agreement(
project_id=p.id, number="DS-A", date=date(2026, 1, 2),
title="Утверждённый", status="draft", boq_document_id=doc.id,
)
db_session.add(a_approved)
db_session.flush()
add_existing_item(db_session, a_approved, wi.id, Decimal("10"))
db_session.commit()
approve_agreement(db_session, a_approved.id)
# Cancelled
a_cancelled = Agreement(
project_id=p.id, number="DS-C", date=date(2026, 1, 3),
title="Отменённый", status="draft", boq_document_id=doc.id,
)
db_session.add(a_cancelled)
db_session.flush()
add_existing_item(db_session, a_cancelled, wi.id, Decimal("5"))
db_session.commit()
approve_agreement(db_session, a_cancelled.id)
cancel_agreement(db_session, a_cancelled)
db_session.commit()
return {
"pid": p.id,
"draft_id": a_draft.id,
"approved_id": a_approved.id,
"cancelled_id": a_cancelled.id,
}
def _override(db_session):
def override():
yield db_session
app.dependency_overrides[agr_router.get_db] = override
app.dependency_overrides[project_router.get_db] = override
def _clear():
app.dependency_overrides.clear()
def test_list_shows_correct_status_badges(db_session, ctx):
_override(db_session)
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements").text
# Draft → Черновик
assert "Черновик" in html
# Approved → Утверждено
assert "Утверждено" in html
# Cancelled → Отменено
assert "Отменено" in html
# All three badges present with correct styling
assert "text-bg-secondary" in html # Черновик
assert "text-bg-success" in html # Утверждено
assert "text-bg-danger" in html # Отменено
finally:
_clear()
def test_cancelled_row_has_no_draft_actions(db_session, ctx):
_override(db_session)
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements").text
# List should NOT have delete/approve/cancel action buttons
# (list only shows "Открыть" for all rows)
assert "Удалить" not in html
assert "Утвердить" not in html
assert 'data-bs-target="#deleteAgreementModal"' not in html
assert 'data-bs-target="#cancelAgreementModal"' not in html
finally:
_clear()
def test_cancelled_accessible_for_viewing(db_session, ctx):
_override(db_session)
try:
client = TestClient(app)
# Cancelled DS detail page loads
resp = client.get(f"/projects/{ctx['pid']}/agreements/{ctx['cancelled_id']}")
assert resp.status_code == 200
assert "ОТМЕНЕНО" in resp.text
# Cancelled DS list entry has "Открыть" link
html = client.get(f"/projects/{ctx['pid']}/agreements").text
assert f"/projects/{ctx['pid']}/agreements/{ctx['cancelled_id']}" in html
finally:
_clear()
def test_draft_still_shows_chernovik(db_session, ctx):
_override(db_session)
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements").text
# Draft badge present
assert '<span class="badge text-bg-secondary">Черновик</span>' in html
finally:
_clear()
def test_approved_still_shows_utverzhdeno(db_session, ctx):
_override(db_session)
try:
client = TestClient(app)
html = client.get(f"/projects/{ctx['pid']}/agreements").text
assert '<span class="badge text-bg-success">Утверждено</span>' in html
finally:
_clear()