feat: add KS-3/payments, tech debt fixes, UI polish, and KS-2 Excel/Word export
Tasks 008-016: KS-6a journal, KS-3 documents, payments with allocations, tech debt cleanup, financial privacy, document tree, storno mechanism, row-click UI, BOQ collapse/sticky header, and KS-2 export to Excel/Word via shared DTO architecture.
This commit is contained in:
@@ -0,0 +1,176 @@
|
||||
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, available_ks3_for_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 = Decimal(v.strip().replace(",", "."))
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
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)
|
||||
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 = Decimal(v.strip().replace(",", "."))
|
||||
if alloc_amount > 0:
|
||||
allocations.append({"ks3_id": ks3_id, "amount": alloc_amount})
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
try:
|
||||
parsed_date = date.fromisoformat(payment_date)
|
||||
parsed_amount = Decimal(amount.strip().replace(",", "."))
|
||||
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)):
|
||||
from app.models.payment import Payment
|
||||
doc = db.query(Payment).filter(Payment.id == payment_id, Payment.project_id == project_id).first()
|
||||
if doc is None:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
if doc.status == "cancelled":
|
||||
raise HTTPException(status_code=400, detail="Payment already cancelled")
|
||||
doc.status = "cancelled"
|
||||
db.commit()
|
||||
return RedirectResponse(f"/projects/{project_id}/payments/{payment_id}", status_code=303)
|
||||
Reference in New Issue
Block a user