feat: add payment stornation with history-preserving allocations and card layout fixes
This commit is contained in:
@@ -86,20 +86,23 @@ def test_payments_actions_are_nowrap_inline(tmp_path):
|
||||
s.add(p)
|
||||
s.flush()
|
||||
s.add(Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("10"),
|
||||
currency="RUB", status="active"))
|
||||
s.add(Payment(project_id=p.id, date=date(2026, 1, 2), amount=Decimal("10"),
|
||||
currency="RUB", status="cancelled"))
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
html = client.get(f"/projects/{pid}/payments").text
|
||||
# Actions cell keeps all three actions on one line
|
||||
# Actions cell keeps actions on one line
|
||||
assert "payments-actions" in html
|
||||
assert "text-nowrap" in html
|
||||
assert "d-inline-flex" in html
|
||||
# Column width reserved
|
||||
assert re.search(r'<col style="width: 17rem">', html)
|
||||
# Three actions + storno badge + row-click preserved
|
||||
# Active payment: three actions; cancelled: view only + status
|
||||
assert "Просмотр" in html and "Редактировать" in html and "Удалить" in html
|
||||
assert "Сторнирован" in html
|
||||
assert "Действия недоступны" in html
|
||||
assert "clickable-row" in html
|
||||
finally:
|
||||
_clear()
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
"""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()
|
||||
@@ -0,0 +1,114 @@
|
||||
"""Layout tests for task 024-FIX: payment card adaptive layout."""
|
||||
import re
|
||||
import shutil
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from app.database.database import Base, DATABASE_PATH
|
||||
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
|
||||
|
||||
|
||||
def _make_session(tmp_path):
|
||||
db_path = tmp_path / "t024fix.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(bind=engine)
|
||||
return engine, sessionmaker(bind=engine, autoflush=False, autocommit=False)
|
||||
|
||||
|
||||
def _bind(Session):
|
||||
def override_db():
|
||||
s = Session()
|
||||
try:
|
||||
yield s
|
||||
finally:
|
||||
s.close()
|
||||
app.dependency_overrides[payments_router.get_db] = override_db
|
||||
|
||||
|
||||
def _clear():
|
||||
app.dependency_overrides.pop(payments_router.get_db, None)
|
||||
|
||||
|
||||
def test_cancelled_payment_card_layout(tmp_path):
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Fix layout")
|
||||
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
|
||||
# Alert wraps and cannot overflow
|
||||
assert "payment-storno-alert" in html
|
||||
assert "overflow-wrap: anywhere" in html
|
||||
assert "white-space: normal" in html
|
||||
# Requisites use adaptive Bootstrap grid
|
||||
assert re.search(r'class="col-12 col-sm-6 col-lg-4"', html)
|
||||
assert "text-break" in html
|
||||
# Labels as separate blocks
|
||||
for label in ("Сумма", "Распределено", "Не распределено"):
|
||||
assert f'>{label}</div>' in html
|
||||
# History table unchanged
|
||||
assert "Исторические распределения по КС-3" in html
|
||||
# Back button is FIRST in the actions row (left-aligned)
|
||||
actions = re.search(r'class="d-flex flex-wrap gap-2 payment-actions"(.*?)</div>', html, re.S)
|
||||
assert actions, "payment-actions block missing"
|
||||
block = actions.group(1)
|
||||
assert "Назад к списку" in block
|
||||
assert block.index("Назад к списку") < block.index("недоступны")
|
||||
assert "justify-content-between" not in block
|
||||
assert "justify-content: flex-start" in html or "justify-content-flex-start" in html
|
||||
# Alert structure: paragraphs + container constraints
|
||||
assert "payment-storno-alert" in html
|
||||
assert "min-width: 0" in html
|
||||
assert "max-width: 100%" in html
|
||||
assert "white-space: normal" in html
|
||||
assert 'class="payment-view"' in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_active_payment_card_uses_same_layout(tmp_path):
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
engine, Session = _make_session(tmp_path)
|
||||
_bind(Session)
|
||||
try:
|
||||
with Session() as s:
|
||||
p = Project(name="Active layout")
|
||||
s.add(p)
|
||||
s.flush()
|
||||
s.add(Payment(project_id=p.id, date=date(2026, 1, 1), amount=Decimal("100"),
|
||||
currency="RUB", status="active"))
|
||||
s.commit()
|
||||
pid = p.id
|
||||
with TestClient(app) as client:
|
||||
rows = client.get(f"/projects/{pid}/payments").text
|
||||
# find payment id from DB
|
||||
with Session() as s:
|
||||
pay_id = s.query(Payment).filter_by(project_id=pid).one().id
|
||||
html = client.get(f"/projects/{pid}/payments/{pay_id}").text
|
||||
assert re.search(r'class="col-12 col-sm-6 col-lg-4"', html)
|
||||
assert "Сторнировать платёж" in html
|
||||
assert "Редактировать" in html
|
||||
assert "Назад к списку" in html
|
||||
finally:
|
||||
_clear()
|
||||
engine.dispose()
|
||||
Reference in New Issue
Block a user