payment_tools.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. # app/services/agent/tools/builtin/payment_tools.py
  2. from typing import Optional, Dict, Any, List
  3. from sqlalchemy.ext.asyncio import AsyncSession
  4. from sqlalchemy import select, desc
  5. from app.models.user import VasUser
  6. from app.models.payment import VasPayment
  7. from app.services.agent.tools.registry import agent_tool
  8. from app.core.logger import logger
  9. ADMIN_CHECK_MSG = "Permission denied: This operation is restricted to system administrators (admin)"
  10. @agent_tool(
  11. name="list_payments",
  12. description="管理员查询支付流水记录,支持按支付状态(pending-待支付, succeeded-支付成功, failed-失败, refunded-已退款)、订单号、支付通道provider(creem, stripe, wechat等)筛选",
  13. )
  14. async def list_payments(
  15. status: Optional[str] = None,
  16. order_id: Optional[str] = None,
  17. provider: Optional[str] = None,
  18. limit: int = 15,
  19. offset: int = 0,
  20. *,
  21. db: AsyncSession,
  22. current_user: VasUser,
  23. ) -> Dict[str, Any]:
  24. """查询支付流水列表"""
  25. if current_user.role != "admin":
  26. return {"error": ADMIN_CHECK_MSG}
  27. limit = max(1, min(limit, 50))
  28. offset = max(0, offset)
  29. stmt = select(VasPayment)
  30. if status and status.strip():
  31. stmt = stmt.where(VasPayment.status == status.strip().lower())
  32. if order_id and order_id.strip():
  33. stmt = stmt.where(VasPayment.order_id == order_id.strip())
  34. if provider and provider.strip():
  35. stmt = stmt.where(VasPayment.provider.ilike(f"%{provider.strip()}%"))
  36. stmt = stmt.order_by(desc(VasPayment.created_at)).offset(offset).limit(limit)
  37. res = await db.execute(stmt)
  38. payments = res.scalars().all()
  39. items = []
  40. for p in payments:
  41. items.append({
  42. "payment_id": p.id,
  43. "order_id": p.order_id,
  44. "provider": p.provider,
  45. "amount": p.amount,
  46. "currency": p.currency,
  47. "status": p.status,
  48. "created_at": p.created_at.strftime("%Y-%m-%d %H:%M:%S") if p.created_at else None,
  49. "paid_at": p.paid_at.strftime("%Y-%m-%d %H:%M:%S") if getattr(p, "paid_at", None) else None,
  50. })
  51. return {
  52. "count": len(items),
  53. "payments": items,
  54. }