order_tools.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. # app/services/agent/tools/builtin/order_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.order import VasOrder
  6. from app.models.user import VasUser
  7. from app.services.order_service import OrderService
  8. from app.services.agent.tools.registry import agent_tool
  9. from app.core.logger import logger
  10. @agent_tool(
  11. name="query_user_orders",
  12. description="查询当前登录用户的订单列表,可按订单状态筛选(pending-待支付, paid-已支付, completed-已完成, closed-已关闭)",
  13. )
  14. async def query_user_orders(
  15. status: Optional[str] = None,
  16. limit: int = 10,
  17. offset: int = 0,
  18. *,
  19. db: AsyncSession,
  20. current_user: VasUser,
  21. ) -> Dict[str, Any]:
  22. """查询用户的订单列表"""
  23. limit = max(1, min(limit, 50))
  24. offset = max(0, offset)
  25. stmt = select(VasOrder).where(VasOrder.user_id == current_user.id)
  26. if status and status.strip():
  27. stmt = stmt.where(VasOrder.status == status.strip().lower())
  28. stmt = stmt.order_by(desc(VasOrder.created_at)).offset(offset).limit(limit)
  29. res = await db.execute(stmt)
  30. orders = res.scalars().all()
  31. items = []
  32. for o in orders:
  33. items.append({
  34. "order_id": o.id,
  35. "product_name": o.product_name,
  36. "final_amount": o.final_amount,
  37. "currency": o.base_currency,
  38. "status": o.status,
  39. "created_at": o.created_at.strftime("%Y-%m-%d %H:%M:%S") if o.created_at else None,
  40. })
  41. return {
  42. "count": len(items),
  43. "orders": items,
  44. }
  45. @agent_tool(
  46. name="get_order_detail",
  47. description="获取指定订单ID的详细信息,包含产品信息、金额、状态及填写的数据",
  48. )
  49. async def get_order_detail(
  50. order_id: str,
  51. *,
  52. db: AsyncSession,
  53. current_user: VasUser,
  54. ) -> Dict[str, Any]:
  55. """获取指定订单详情"""
  56. stmt = select(VasOrder).where(VasOrder.id == order_id.strip())
  57. res = await db.execute(stmt)
  58. order = res.scalar_one_or_none()
  59. if not order:
  60. return {"error": f"订单 {order_id} 不存在"}
  61. # 数据权限校验:非管理员只能查看自己的订单
  62. if order.user_id != current_user.id and current_user.role != "admin":
  63. return {"error": f"无权查看该订单 {order_id}"}
  64. return {
  65. "order_id": order.id,
  66. "product_id": order.product_id,
  67. "product_name": order.product_name,
  68. "base_amount": order.base_amount,
  69. "final_amount": order.final_amount,
  70. "currency": order.base_currency,
  71. "status": order.status,
  72. "user_inputs": order.user_inputs,
  73. "created_at": order.created_at.strftime("%Y-%m-%d %H:%M:%S") if order.created_at else None,
  74. "updated_at": order.updated_at.strftime("%Y-%m-%d %H:%M:%S") if order.updated_at else None,
  75. }
  76. @agent_tool(
  77. name="cancel_user_order",
  78. description="取消指定的订单(仅未完成/未关闭的订单可取消)",
  79. is_dangerous=True,
  80. )
  81. async def cancel_user_order(
  82. order_id: str,
  83. reason: Optional[str] = None,
  84. *,
  85. db: AsyncSession,
  86. current_user: VasUser,
  87. ) -> Dict[str, Any]:
  88. """取消用户自己的订单"""
  89. order_id_clean = order_id.strip()
  90. stmt = select(VasOrder).where(VasOrder.id == order_id_clean)
  91. res = await db.execute(stmt)
  92. order = res.scalar_one_or_none()
  93. if not order:
  94. return {"error": f"订单 {order_id_clean} 不存在"}
  95. if order.user_id != current_user.id and current_user.role != "admin":
  96. return {"error": f"无权取消订单 {order_id_clean}"}
  97. if order.status == "closed":
  98. return {"message": f"订单 {order_id_clean} 已经处于已关闭状态,无需重复取消"}
  99. if order.status == "completed":
  100. return {"error": f"订单 {order_id_clean} 已履约完成,无法取消"}
  101. try:
  102. cancelled = await OrderService.cancel(db, order_id_clean)
  103. logger.info(f"Agent cancelled order {order_id_clean} on behalf of user {current_user.id}, reason={reason}")
  104. return {
  105. "success": True,
  106. "order_id": cancelled.id,
  107. "status": cancelled.status,
  108. "message": f"订单 {order_id_clean} 已成功取消",
  109. }
  110. except Exception as e:
  111. return {"error": f"取消订单失败: {str(e)}"}