311 lines
12 KiB
Python
311 lines
12 KiB
Python
"""Tests for task 024: payment stornation."""
|
||
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.project import Project
|
||
from app.models.payment import Payment, PaymentAllocation
|
||
from app.routers import payments as payments_router
|
||
from app.services.payment_service import (
|
||
PaymentValidationError,
|
||
available_ks3_for_payment,
|
||
cancel_payment,
|
||
delete_payment,
|
||
ks3_payment_summary,
|
||
project_payments,
|
||
save_payment,
|
||
)
|
||
|
||
|
||
@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 project(db_session):
|
||
p = Project(name="Payment storno", status="active")
|
||
db_session.add(p)
|
||
db_session.commit()
|
||
return p
|
||
|
||
|
||
def _make_issued_ks3(db_session, project, number="K3-1", total=Decimal("1000")):
|
||
"""Minimal issued KS-3 whose total equals `total` via one KS-2 item."""
|
||
from app.models.ks2 import KS2, KS2Item
|
||
from app.models.ks3 import KS3, KS3KS2
|
||
|
||
ks2 = KS2(project_id=project.id, number=f"K2-{number}", date=date(2026, 1, 1), status="issued")
|
||
db_session.add(ks2)
|
||
db_session.flush()
|
||
db_session.add(KS2Item(ks2_id=ks2.id, work_item_id=_work_item(db_session, project).id,
|
||
quantity=Decimal("1"), unit_price=total, amount=total))
|
||
ks3 = KS3(project_id=project.id, number=number, date=date(2026, 1, 2), status="issued")
|
||
db_session.add(ks3)
|
||
db_session.flush()
|
||
db_session.add(KS3KS2(ks3_id=ks3.id, ks2_id=ks2.id))
|
||
db_session.commit()
|
||
return ks3
|
||
|
||
|
||
def _work_item(db_session, project):
|
||
from app.models.boq import WorkItem
|
||
wi = WorkItem(project_id=project.id, name="W", quantity=Decimal("1"))
|
||
db_session.add(wi)
|
||
db_session.flush()
|
||
return wi
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 1–7. Full cycle: create → allocate → dashboard → storno → aggregates
|
||
# ---------------------------------------------------------------------------
|
||
def test_payment_storno_excludes_from_dashboard_but_keeps_history(db_session, project):
|
||
ks3 = _make_issued_ks3(db_session, project, total=Decimal("1000"))
|
||
|
||
# 1–2. Active payment allocated to KS-3
|
||
payment = save_payment(
|
||
db_session, project.id, date(2026, 2, 1), Decimal("1000"), "RUB", None,
|
||
[{"ks3_id": ks3.id, "amount": Decimal("800")}],
|
||
)
|
||
assert payment.status == "active"
|
||
assert len(payment.allocations) == 1
|
||
|
||
# 3. Dashboard reflects payment
|
||
summary = ks3_payment_summary(db_session, project.id)
|
||
assert summary["received"] == Decimal("1000")
|
||
assert summary["distributed"] == Decimal("800")
|
||
assert summary["unallocated"] == Decimal("200")
|
||
assert summary["outstanding"] == Decimal("200")
|
||
|
||
# 4. Storno
|
||
cancelled = cancel_payment(db_session, project.id, payment.id)
|
||
assert cancelled.status == "cancelled"
|
||
|
||
# 5–6. Payment + allocations preserved
|
||
db_session.expire_all()
|
||
stored = db_session.get(Payment, payment.id)
|
||
assert stored.status == "cancelled"
|
||
allocs = db_session.query(PaymentAllocation).filter_by(payment_id=payment.id).all()
|
||
assert len(allocs) == 1
|
||
assert allocs[0].amount == Decimal("800")
|
||
assert allocs[0].ks3_id == ks3.id
|
||
|
||
# 7. Excluded from active aggregates
|
||
summary = ks3_payment_summary(db_session, project.id)
|
||
assert summary["received"] == Decimal("0")
|
||
assert summary["distributed"] == Decimal("0")
|
||
assert summary["unallocated"] == Decimal("0")
|
||
|
||
# 8. Outstanding restored
|
||
assert summary["outstanding"] == Decimal("1000")
|
||
|
||
|
||
def test_payment_without_allocations_storno(db_session, project):
|
||
payment = save_payment(db_session, project.id, date(2026, 2, 1), Decimal("500"), "RUB", None, [])
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
summary = ks3_payment_summary(db_session, project.id)
|
||
assert summary["received"] == Decimal("0")
|
||
assert summary["unallocated"] == Decimal("0")
|
||
|
||
|
||
def test_double_storno_impossible(db_session, project):
|
||
payment = save_payment(db_session, project.id, date(2026, 2, 1), Decimal("100"), "RUB", None, [])
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
with pytest.raises(PaymentValidationError, match="уже сторнирован"):
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
|
||
|
||
def test_edit_cancelled_payment_blocked(db_session, project):
|
||
payment = save_payment(db_session, project.id, date(2026, 2, 1), Decimal("100"), "RUB", None, [])
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
with pytest.raises(PaymentValidationError, match="нельзя изменить"):
|
||
save_payment(
|
||
db_session, project.id, date(2026, 2, 2), Decimal("999"), "RUB", "hack",
|
||
[], payment_id=payment.id,
|
||
)
|
||
|
||
|
||
def test_delete_cancelled_payment_blocked(db_session, project):
|
||
payment = save_payment(db_session, project.id, date(2026, 2, 1), Decimal("100"), "RUB", None, [])
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
with pytest.raises(PaymentValidationError, match="нельзя удалить"):
|
||
delete_payment(db_session, project.id, payment.id)
|
||
assert db_session.get(Payment, payment.id) is not None
|
||
|
||
|
||
def test_cancel_nonexistent_payment(db_session, project):
|
||
with pytest.raises(PaymentValidationError, match="не найден"):
|
||
cancel_payment(db_session, project.id, 99999)
|
||
|
||
|
||
def test_storno_transactional(db_session, project):
|
||
"""Failed cancel leaves status unchanged (rollback path)."""
|
||
payment = save_payment(db_session, project.id, date(2026, 2, 1), Decimal("100"), "RUB", None, [])
|
||
with pytest.raises(PaymentValidationError):
|
||
cancel_payment(db_session, project.id, 99999)
|
||
assert db_session.get(Payment, payment.id).status == "active"
|
||
|
||
|
||
def test_ks3_outstanding_restored_after_payment_storno(db_session, project):
|
||
ks3 = _make_issued_ks3(db_session, project, total=Decimal("1000"))
|
||
payment = save_payment(
|
||
db_session, project.id, date(2026, 2, 1), Decimal("1000"), "RUB", None,
|
||
[{"ks3_id": ks3.id, "amount": Decimal("1000")}],
|
||
)
|
||
avail = available_ks3_for_payment(db_session, project.id)
|
||
assert avail[0]["outstanding"] == Decimal("0")
|
||
|
||
cancel_payment(db_session, project.id, payment.id)
|
||
avail = available_ks3_for_payment(db_session, project.id)
|
||
assert avail[0]["outstanding"] == Decimal("1000")
|
||
assert avail[0]["paid"] == Decimal("0")
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# 9–10. List + card UI
|
||
# ---------------------------------------------------------------------------
|
||
def _ui_session(tmp_path):
|
||
from pathlib import Path
|
||
import shutil
|
||
from app.database.database import DATABASE_PATH
|
||
|
||
db_path = tmp_path / "t024.db"
|
||
shutil.copy2(DATABASE_PATH, db_path)
|
||
engine = create_engine(f"sqlite:///{db_path.as_posix()}", connect_args={"check_same_thread": False})
|
||
Base.metadata.create_all(engine)
|
||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||
|
||
|
||
DEPS = (payments_router.get_db,)
|
||
|
||
|
||
def _bind(Session):
|
||
def override_db():
|
||
s = Session()
|
||
try:
|
||
yield s
|
||
finally:
|
||
s.close()
|
||
for dep in DEPS:
|
||
app.dependency_overrides[dep] = override_db
|
||
|
||
|
||
def _clear():
|
||
for dep in DEPS:
|
||
app.dependency_overrides.pop(dep, None)
|
||
|
||
|
||
def test_payment_list_shows_storno_and_blocks_actions(tmp_path):
|
||
engine, Session = _ui_session(tmp_path)
|
||
_bind(Session)
|
||
try:
|
||
with Session() as s:
|
||
p = Project(name="List")
|
||
s.add(p)
|
||
s.flush()
|
||
s.add(Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("10"), currency="RUB", status="cancelled"))
|
||
s.add(Payment(project_id=p.id, date=date(2026, 1, 2), amount=Decimal("10"), currency="RUB", status="active"))
|
||
s.commit()
|
||
pid = p.id
|
||
with TestClient(app) as client:
|
||
html = client.get(f"/projects/{pid}/payments").text
|
||
assert "Сторнирован" in html
|
||
assert "Активный" in html
|
||
assert "Действия недоступны" in html
|
||
assert "clickable-row" in html
|
||
# Active row still has edit/delete
|
||
assert "Редактировать" in html and "Удалить" in html
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_cancelled_payment_card_shows_history_and_blocks_changes(tmp_path):
|
||
engine, Session = _ui_session(tmp_path)
|
||
_bind(Session)
|
||
try:
|
||
with Session() as s:
|
||
p = Project(name="Card")
|
||
s.add(p)
|
||
s.flush()
|
||
pay = Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("100"),
|
||
currency="RUB", status="cancelled")
|
||
s.add(pay)
|
||
s.flush()
|
||
s.add(PaymentAllocation(payment_id=pay.id, ks3_id=1, amount=Decimal("40")))
|
||
s.commit()
|
||
pid, pay_id = p.id, pay.id
|
||
with TestClient(app) as client:
|
||
html = client.get(f"/projects/{pid}/payments/{pay_id}").text
|
||
assert "Сторнирован" in html
|
||
assert "Исторические распределения" in html
|
||
assert "Недоступны" in html or "недоступны" in html
|
||
# No edit/cancel/delete buttons
|
||
assert "Сторнировать платёж" not in html
|
||
assert f"/payments/{pay_id}/edit" not in html or "Редактирование" in html
|
||
# Historical allocation amount visible
|
||
assert "40" in html or "40,00" in html
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_edit_redirects_cancelled_payment(tmp_path):
|
||
engine, Session = _ui_session(tmp_path)
|
||
_bind(Session)
|
||
try:
|
||
with Session() as s:
|
||
p = Project(name="Edit block")
|
||
s.add(p)
|
||
s.flush()
|
||
pay = Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("10"),
|
||
currency="RUB", status="cancelled")
|
||
s.add(pay)
|
||
s.commit()
|
||
pid, pay_id = p.id, pay.id
|
||
with TestClient(app) as client:
|
||
resp = client.get(f"/projects/{pid}/payments/{pay_id}/edit", follow_redirects=False)
|
||
assert resp.status_code == 303
|
||
assert resp.headers["location"].endswith(f"/payments/{pay_id}")
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|
||
|
||
|
||
def test_cancel_endpoint_blocks_double_cancel(tmp_path):
|
||
engine, Session = _ui_session(tmp_path)
|
||
_bind(Session)
|
||
try:
|
||
with Session() as s:
|
||
p = Project(name="Cancel api")
|
||
s.add(p)
|
||
s.flush()
|
||
pay = Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("10"),
|
||
currency="RUB", status="active")
|
||
s.add(pay)
|
||
s.commit()
|
||
pid, pay_id = p.id, pay.id
|
||
with TestClient(app) as client:
|
||
first = client.post(f"/projects/{pid}/payments/{pay_id}/cancel", follow_redirects=False)
|
||
assert first.status_code == 303
|
||
second = client.post(f"/projects/{pid}/payments/{pay_id}/cancel", follow_redirects=False)
|
||
assert second.status_code == 400
|
||
finally:
|
||
_clear()
|
||
engine.dispose()
|