order_tools.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  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 {order_id} does not exist"}
  61. # 数据权限校验:非管理员只能查看自己的订单
  62. if order.user_id != current_user.id and current_user.role != "admin":
  63. return {"error": f"Permission denied: You cannot view order {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 {order_id_clean} does not exist"}
  95. if order.user_id != current_user.id and current_user.role != "admin":
  96. return {"error": f"Permission denied: You cannot cancel order {order_id_clean}"}
  97. if order.status == "closed":
  98. return {"message": f"Order {order_id_clean} is already closed, no need to cancel again"}
  99. if order.status == "completed":
  100. return {"error": f"Order {order_id_clean} has already been fulfilled and cannot be cancelled"}
  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 {order_id_clean} was successfully cancelled",
  109. }
  110. except Exception as e:
  111. return {"error": f"Failed to cancel order: {str(e)}"}
  112. @agent_tool(
  113. name="admin_list_all_orders",
  114. description="管理员全景查询全站订单列表,支持按订单状态(pending-待支付, paid-已支付, completed-已完成, closed-已关闭)、特定用户ID、产品名称关键词或订单号筛选",
  115. )
  116. async def admin_list_all_orders(
  117. status: Optional[str] = None,
  118. user_id: Optional[str] = None,
  119. keyword: Optional[str] = None,
  120. limit: int = 15,
  121. offset: int = 0,
  122. *,
  123. db: AsyncSession,
  124. current_user: VasUser,
  125. ) -> Dict[str, Any]:
  126. """管理员全景查询全站订单列表"""
  127. if current_user.role != "admin":
  128. return {"error": "Permission denied: This operation is restricted to system administrators (admin)"}
  129. limit = max(1, min(limit, 50))
  130. offset = max(0, offset)
  131. stmt = select(VasOrder)
  132. if status and status.strip():
  133. stmt = stmt.where(VasOrder.status == status.strip().lower())
  134. if user_id and user_id.strip():
  135. stmt = stmt.where(VasOrder.user_id == user_id.strip())
  136. if keyword and keyword.strip():
  137. kw = f"%{keyword.strip()}%"
  138. stmt = stmt.where(
  139. or_(
  140. VasOrder.id.ilike(kw),
  141. VasOrder.product_name.ilike(kw),
  142. )
  143. )
  144. stmt = stmt.order_by(desc(VasOrder.created_at)).offset(offset).limit(limit)
  145. res = await db.execute(stmt)
  146. orders = res.scalars().all()
  147. items = []
  148. for o in orders:
  149. items.append({
  150. "order_id": o.id,
  151. "user_id": o.user_id,
  152. "product_name": o.product_name,
  153. "final_amount": o.final_amount,
  154. "currency": o.base_currency,
  155. "status": o.status,
  156. "created_at": o.created_at.strftime("%Y-%m-%d %H:%M:%S") if o.created_at else None,
  157. })
  158. return {
  159. "count": len(items),
  160. "orders": items,
  161. }
  162. @agent_tool(
  163. name="admin_update_order_status",
  164. description="管理员手动调整订单状态(支持改为 paid-已支付, completed-已履约完成, closed-已关闭, pending-待支付)",
  165. is_dangerous=True,
  166. )
  167. async def admin_update_order_status(
  168. order_id: str,
  169. status: str,
  170. note: Optional[str] = None,
  171. *,
  172. db: AsyncSession,
  173. current_user: VasUser,
  174. ) -> Dict[str, Any]:
  175. """管理员更新订单状态"""
  176. if current_user.role != "admin":
  177. return {"error": "Permission denied: This operation is restricted to system administrators (admin)"}
  178. clean_status = status.strip().lower()
  179. valid_statuses = {"pending", "paid", "completed", "closed"}
  180. if clean_status not in valid_statuses:
  181. return {"error": f"Invalid status '{clean_status}'. Valid statuses: {sorted(list(valid_statuses))}"}
  182. stmt = select(VasOrder).where(VasOrder.id == order_id.strip())
  183. res = await db.execute(stmt)
  184. order = res.scalar_one_or_none()
  185. if not order:
  186. return {"error": f"Order {order_id} does not exist"}
  187. old_status = order.status
  188. order.status = clean_status
  189. await db.commit()
  190. await db.refresh(order)
  191. logger.info(f"📦 [AI_AGENT] Updated order status: order={order.id} ({old_status} -> {clean_status}) by admin={current_user.id}, note={note}")
  192. return {
  193. "success": True,
  194. "order_id": order.id,
  195. "previous_status": old_status,
  196. "new_status": order.status,
  197. }