# 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, or_ 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 {order_id} does not exist"} # 数据权限校验:非管理员只能查看自己的订单 if order.user_id != current_user.id and current_user.role != "admin": return {"error": f"Permission denied: You cannot view order {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 {order_id_clean} does not exist"} if order.user_id != current_user.id and current_user.role != "admin": return {"error": f"Permission denied: You cannot cancel order {order_id_clean}"} if order.status == "closed": return {"message": f"Order {order_id_clean} is already closed, no need to cancel again"} if order.status == "completed": return {"error": f"Order {order_id_clean} has already been fulfilled and cannot be cancelled"} 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 {order_id_clean} was successfully cancelled", } except Exception as e: return {"error": f"Failed to cancel order: {str(e)}"} @agent_tool( name="admin_list_all_orders", description="管理员全景查询全站订单列表,支持按订单状态(pending-待支付, paid-已支付, completed-已完成, closed-已关闭)、特定用户ID、产品名称关键词或订单号筛选", ) async def admin_list_all_orders( status: Optional[str] = None, user_id: Optional[str] = None, keyword: Optional[str] = None, limit: int = 15, offset: int = 0, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """管理员全景查询全站订单列表""" if current_user.role != "admin": return {"error": "Permission denied: This operation is restricted to system administrators (admin)"} limit = max(1, min(limit, 50)) offset = max(0, offset) stmt = select(VasOrder) if status and status.strip(): stmt = stmt.where(VasOrder.status == status.strip().lower()) if user_id and user_id.strip(): stmt = stmt.where(VasOrder.user_id == user_id.strip()) if keyword and keyword.strip(): kw = f"%{keyword.strip()}%" stmt = stmt.where( or_( VasOrder.id.ilike(kw), VasOrder.product_name.ilike(kw), ) ) 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, "user_id": o.user_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="admin_update_order_status", description="管理员手动调整订单状态(支持改为 paid-已支付, completed-已履约完成, closed-已关闭, pending-待支付)", is_dangerous=True, ) async def admin_update_order_status( order_id: str, status: str, note: Optional[str] = None, *, db: AsyncSession, current_user: VasUser, ) -> Dict[str, Any]: """管理员更新订单状态""" if current_user.role != "admin": return {"error": "Permission denied: This operation is restricted to system administrators (admin)"} clean_status = status.strip().lower() valid_statuses = {"pending", "paid", "completed", "closed"} if clean_status not in valid_statuses: return {"error": f"Invalid status '{clean_status}'. Valid statuses: {sorted(list(valid_statuses))}"} 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 {order_id} does not exist"} old_status = order.status order.status = clean_status await db.commit() await db.refresh(order) logger.info(f"📦 [AI_AGENT] Updated order status: order={order.id} ({old_status} -> {clean_status}) by admin={current_user.id}, note={note}") return { "success": True, "order_id": order.id, "previous_status": old_status, "new_status": order.status, }