| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- # app/services/agent/tools/builtin/order_tools.py
- from typing import Optional, Dict, Any, List
- from sqlalchemy.ext.asyncio import AsyncSession
- from sqlalchemy import select, desc
- from app.models.order import VasOrder
- from app.models.user import VasUser
- from app.services.order_service import OrderService
- from app.services.agent.tools.registry import agent_tool
- from app.core.logger import logger
- @agent_tool(
- name="query_user_orders",
- description="查询当前登录用户的订单列表,可按订单状态筛选(pending-待支付, paid-已支付, completed-已完成, closed-已关闭)",
- )
- async def query_user_orders(
- status: Optional[str] = None,
- limit: int = 10,
- offset: int = 0,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """查询用户的订单列表"""
- limit = max(1, min(limit, 50))
- offset = max(0, offset)
- stmt = select(VasOrder).where(VasOrder.user_id == current_user.id)
- if status and status.strip():
- stmt = stmt.where(VasOrder.status == status.strip().lower())
- stmt = stmt.order_by(desc(VasOrder.created_at)).offset(offset).limit(limit)
- res = await db.execute(stmt)
- orders = res.scalars().all()
- items = []
- for o in orders:
- items.append({
- "order_id": o.id,
- "product_name": o.product_name,
- "final_amount": o.final_amount,
- "currency": o.base_currency,
- "status": o.status,
- "created_at": o.created_at.strftime("%Y-%m-%d %H:%M:%S") if o.created_at else None,
- })
- return {
- "count": len(items),
- "orders": items,
- }
- @agent_tool(
- name="get_order_detail",
- description="获取指定订单ID的详细信息,包含产品信息、金额、状态及填写的数据",
- )
- async def get_order_detail(
- order_id: str,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """获取指定订单详情"""
- stmt = select(VasOrder).where(VasOrder.id == order_id.strip())
- res = await db.execute(stmt)
- order = res.scalar_one_or_none()
- if not order:
- return {"error": f"订单 {order_id} 不存在"}
- # 数据权限校验:非管理员只能查看自己的订单
- if order.user_id != current_user.id and current_user.role != "admin":
- return {"error": f"无权查看该订单 {order_id}"}
- return {
- "order_id": order.id,
- "product_id": order.product_id,
- "product_name": order.product_name,
- "base_amount": order.base_amount,
- "final_amount": order.final_amount,
- "currency": order.base_currency,
- "status": order.status,
- "user_inputs": order.user_inputs,
- "created_at": order.created_at.strftime("%Y-%m-%d %H:%M:%S") if order.created_at else None,
- "updated_at": order.updated_at.strftime("%Y-%m-%d %H:%M:%S") if order.updated_at else None,
- }
- @agent_tool(
- name="cancel_user_order",
- description="取消指定的订单(仅未完成/未关闭的订单可取消)",
- is_dangerous=True,
- )
- async def cancel_user_order(
- order_id: str,
- reason: Optional[str] = None,
- *,
- db: AsyncSession,
- current_user: VasUser,
- ) -> Dict[str, Any]:
- """取消用户自己的订单"""
- order_id_clean = order_id.strip()
- stmt = select(VasOrder).where(VasOrder.id == order_id_clean)
- res = await db.execute(stmt)
- order = res.scalar_one_or_none()
- if not order:
- return {"error": f"订单 {order_id_clean} 不存在"}
- if order.user_id != current_user.id and current_user.role != "admin":
- return {"error": f"无权取消订单 {order_id_clean}"}
- if order.status == "closed":
- return {"message": f"订单 {order_id_clean} 已经处于已关闭状态,无需重复取消"}
- if order.status == "completed":
- return {"error": f"订单 {order_id_clean} 已履约完成,无法取消"}
- try:
- cancelled = await OrderService.cancel(db, order_id_clean)
- logger.info(f"Agent cancelled order {order_id_clean} on behalf of user {current_user.id}, reason={reason}")
- return {
- "success": True,
- "order_id": cancelled.id,
- "status": cancelled.status,
- "message": f"订单 {order_id_clean} 已成功取消",
- }
- except Exception as e:
- return {"error": f"取消订单失败: {str(e)}"}
|