Files
work-volume-tracker/app/routers/payments.py
T
Арсентьев Александр 1af2a70406 fix: payments validation and in-place allocation edits
Close the KS-2 -> KS-3 -> Payment -> allocation -> aggregates chain for V1.
Two real defects fixed:

- NaN/Infinity payment or allocation amounts raised InvalidOperation (500)
  or were silently stored; they are now finite-value validation errors (400)
  via _parse_money / is_finite checks.
- Editing an allocation to the same KS-3 hit uq_payment_ks3 because
  clear() deferred the DELETE past the new INSERT; allocations are now
  updated in place.

Financial semantics unchanged: full active payment counts as received,
storno keeps historical allocations while excluding the payment from
active aggregates. Decimal arithmetic preserved.
2026-10-08 20:24:48 +03:00

178 lines
7.6 KiB
Python

from datetime import date
from decimal import Decimal
from pathlib import Path
from fastapi import APIRouter, Depends, Form, HTTPException, Request
from fastapi.responses import RedirectResponse
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm import Session, joinedload
from app.database.database import get_db
from app.models.project import Project
from app.models.payment import Payment, PaymentAllocation
from app.services.payment_service import (
PaymentValidationError, _parse_money, available_ks3_for_payment, cancel_payment,
delete_payment, project_payments, save_payment,
)
from app.utils.formatters import format_money
def _quantity2(value):
try:
return f"{Decimal(str(value if value is not None else 0)):.2f}"
except Exception:
return "0.00"
router = APIRouter()
templates = Jinja2Templates(directory=Path(__file__).resolve().parents[1] / "templates")
templates.env.filters["money"] = format_money
templates.env.filters["quantity2"] = _quantity2
def _project(db, project_id):
obj = db.query(Project).filter(Project.id == project_id).first()
if obj is None:
raise HTTPException(status_code=404, detail="Проект не найден")
return obj
def _payment(db, project_id, payment_id):
p = db.query(Payment).options(
joinedload(Payment.allocations).joinedload(PaymentAllocation.ks3)
).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
if p is None:
raise HTTPException(status_code=404, detail="Платёж не найден")
return p
def _render_form(request, db, project, payment=None, error=None, status_code=200):
available = available_ks3_for_payment(db, project.id, exclude_payment_id=payment.id if payment else None)
current_allocs = {a.ks3_id: Decimal(str(a.amount)) for a in payment.allocations} if payment else {}
return templates.TemplateResponse(name="payments/form.html", context={
"request": request, "project": project, "payment": payment,
"available_ks3": available, "current_allocs": current_allocs, "error": error,
}, status_code=status_code)
@router.get("/{project_id}/payments")
async def payment_list(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
rows = project_payments(db, project_id)
return templates.TemplateResponse(name="payments/list.html", context={
"request": request, "project": project, "rows": rows,
})
@router.get("/{project_id}/payments/new")
async def payment_new(request: Request, project_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
return _render_form(request, db, project)
@router.post("/{project_id}/payments")
async def payment_create(request: Request, project_id: int,
payment_date: str = Form(...),
document_number: str = Form(""),
amount: str = Form(...), currency: str = Form("RUB"),
comment: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
allocations = []
for k, v in form.multi_items():
if k.startswith("alloc_") and v.strip():
try:
ks3_id = int(k.removeprefix("alloc_"))
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
if alloc_amount > 0:
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
except PaymentValidationError:
raise
except (ValueError, TypeError):
pass
try:
parsed_date = date.fromisoformat(payment_date)
parsed_amount = _parse_money(amount, "Сумма платежа")
payment = save_payment(
db, project_id, parsed_date, parsed_amount, currency, comment,
allocations, document_number=document_number or None,
)
except ValueError as exc:
return _render_form(request, db, project, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
@router.get("/{project_id}/payments/{payment_id}")
async def payment_view(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
payment = _payment(db, project_id, payment_id)
allocated = sum(Decimal(str(a.amount)) for a in payment.allocations)
unallocated = max(Decimal(str(payment.amount)) - allocated, Decimal("0"))
return templates.TemplateResponse(name="payments/view.html", context={
"request": request, "project": project, "payment": payment,
"allocated": allocated, "unallocated": unallocated,
})
@router.get("/{project_id}/payments/{payment_id}/edit")
async def payment_edit(request: Request, project_id: int, payment_id: int, db: Session = Depends(get_db)):
project = _project(db, project_id)
payment = _payment(db, project_id, payment_id)
if payment.status == "cancelled":
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
return _render_form(request, db, project, payment)
@router.post("/{project_id}/payments/{payment_id}/edit")
async def payment_update(request: Request, project_id: int, payment_id: int,
payment_date: str = Form(...),
document_number: str = Form(""),
amount: str = Form(...), currency: str = Form("RUB"),
comment: str = Form(""),
db: Session = Depends(get_db)):
project = _project(db, project_id)
form = await request.form()
allocations = []
for k, v in form.multi_items():
if k.startswith("alloc_") and v.strip():
try:
ks3_id = int(k.removeprefix("alloc_"))
alloc_amount = _parse_money(v, f"Распределение КС-3 {ks3_id}")
if alloc_amount > 0:
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
except PaymentValidationError:
raise
except (ValueError, TypeError):
pass
try:
parsed_date = date.fromisoformat(payment_date)
parsed_amount = _parse_money(amount, "Сумма платежа")
payment = save_payment(
db, project_id, parsed_date, parsed_amount, currency, comment,
allocations, document_number=document_number or None,
payment_id=payment_id,
)
except ValueError as exc:
db.expire_all()
payment = _payment(db, project_id, payment_id)
return _render_form(request, db, project, payment=payment, error=str(exc), status_code=400)
return RedirectResponse(f"/projects/{project_id}/payments/{payment.id}", status_code=303)
@router.post("/{project_id}/payments/{payment_id}/delete")
async def payment_delete(project_id: int, payment_id: int, db: Session = Depends(get_db)):
try:
delete_payment(db, project_id, payment_id)
except PaymentValidationError as exc:
raise HTTPException(status_code=409, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/payments", status_code=303)
@router.post("/{project_id}/payments/{payment_id}/cancel")
async def payment_cancel(project_id: int, payment_id: int, db: Session = Depends(get_db)):
try:
cancel_payment(db, project_id, payment_id)
except PaymentValidationError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)