""" 平台充值记录API路由 """ from typing import Any, List, Optional from fastapi import APIRouter, Depends, HTTPException, Query, status from sqlalchemy import select, func, and_, or_ from sqlalchemy.ext.asyncio import AsyncSession from datetime import datetime from loguru import logger from app.database import get_async_session from app.models.streamer import PlatformRecharge from app.schemas.recharge import ( PlatformRechargeCreate, PlatformRechargeUpdate, PlatformRechargeResponse, PlatformRechargeListResponse, ) router = APIRouter() @router.get("", response_model=PlatformRechargeListResponse) async def list_recharges( page: int = Query(1, ge=1, description="页码"), size: int = Query(10, ge=1, le=100, description="每页数量"), user_id: str = Query(None, description="用户ID"), user_name: str = Query(None, description="用户昵称"), payment_method: str = Query(None, description="支付方式"), status: str = Query(None, description="充值状态"), start_date: str = Query(None, description="开始日期"), end_date: str = Query(None, description="结束日期"), db: AsyncSession = Depends(get_async_session), ): """ 获取平台充值记录列表(分页查询) """ logger.info(f"获取平台充值记录列表: page={page}, size={size}") # 构建查询 query = select(PlatformRecharge) # 添加过滤条件 conditions = [] if user_id: conditions.append(PlatformRecharge.user_id.ilike(f"%{user_id}%")) if user_name: conditions.append(PlatformRecharge.user_name.ilike(f"%{user_name}%")) if payment_method: conditions.append(PlatformRecharge.payment_method == payment_method) if status: conditions.append(PlatformRecharge.status == status) if start_date: conditions.append(PlatformRecharge.recharge_time >= start_date) if end_date: conditions.append(PlatformRecharge.recharge_time <= end_date) if conditions: query = query.where(and_(*conditions)) # 获取总数 count_query = select(func.count()).select_from(PlatformRecharge) if conditions: count_query = count_query.where(and_(*conditions)) total_result = await db.execute(count_query) total = total_result.scalar() # 分页 query = query.offset((page - 1) * size).limit(size) # 执行查询 result = await db.execute(query) records = result.scalars().all() # 转换为响应格式 response_records = [] for recharge in records: response_records.append({ "id": recharge.id, "recharge_id": recharge.recharge_id, "user_id": recharge.user_id, "user_name": recharge.user_name, "user_phone": recharge.user_phone, "recharge_amount": recharge.recharge_amount, "recharge_time": recharge.recharge_time.isoformat() if recharge.recharge_time else None, "payment_method": recharge.payment_method, "payment_channel": recharge.payment_channel, "transaction_no": recharge.transaction_no, "platform_order_no": recharge.platform_order_no, "currency_type": recharge.currency_type, "actual_amount_cny": recharge.actual_amount_cny, "recharge_type": recharge.recharge_type, "bonus_coins": recharge.bonus_coins, "total_coins": recharge.total_coins, "is_first_recharge": recharge.is_first_recharge, "province": recharge.province, "city": recharge.city, "status": recharge.status, "withdrawal_status": recharge.withdrawal_status, "withdrawn_amount": recharge.withdrawn_amount, "created_at": recharge.created_at.isoformat() if recharge.created_at else None, }) return PlatformRechargeListResponse( records=response_records, total=total, page=page, size=size, ) @router.get("/{recharge_id}", response_model=PlatformRechargeResponse) async def get_recharge(recharge_id: str, db: AsyncSession = Depends(get_async_session)): """ 根据ID获取平台充值记录详细信息 """ logger.info(f"获取平台充值记录详情: {recharge_id}") # 查询 query = select(PlatformRecharge).where(PlatformRecharge.recharge_id == recharge_id) result = await db.execute(query) recharge = result.scalar_one_or_none() if not recharge: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"平台充值记录不存在: {recharge_id}", ) # 转换为响应格式 response = { "id": recharge.id, "recharge_id": recharge.recharge_id, "user_id": recharge.user_id, "user_name": recharge.user_name, "user_phone": recharge.user_phone, "recharge_amount": recharge.recharge_amount, "recharge_time": recharge.recharge_time.isoformat() if recharge.recharge_time else None, "payment_method": recharge.payment_method, "payment_channel": recharge.payment_channel, "transaction_no": recharge.transaction_no, "platform_order_no": recharge.platform_order_no, "currency_type": recharge.currency_type, "actual_amount_cny": recharge.actual_amount_cny, "recharge_type": recharge.recharge_type, "bonus_coins": recharge.bonus_coins, "total_coins": recharge.total_coins, "is_first_recharge": recharge.is_first_recharge, "province": recharge.province, "city": recharge.city, "status": recharge.status, "withdrawal_status": recharge.withdrawal_status, "withdrawn_amount": recharge.withdrawn_amount, "created_at": recharge.created_at.isoformat() if recharge.created_at else None, } return response @router.post("", response_model=PlatformRechargeResponse, status_code=status.HTTP_201_CREATED) async def create_recharge(recharge: PlatformRechargeCreate, db: AsyncSession = Depends(get_async_session)): """ 创建新的平台充值记录 """ logger.info(f"创建平台充值记录: {recharge.user_id}") # 生成充值记录ID query = select(func.count()).select_from(PlatformRecharge) result = await db.execute(query) count = result.scalar() recharge_id = f"RCG{2024}{(count + 1):06d}" # 为缺失的字段设置默认值 # 生成交易流水号 transaction_no = recharge.transaction_no or f"TXN{datetime.now().strftime('%Y%m%d%H%M%S')}{(count + 1):06d}" # 生成平台订单号 platform_order_no = recharge.platform_order_no or f"ORD{datetime.now().strftime('%Y%m%d%H%M%S')}{(count + 1):06d}" # 折算人民币金额(默认等于充值金额) actual_amount_cny = recharge.actual_amount_cny or recharge.recharge_amount # 到账虚拟币(默认等于充值金额) total_coins = recharge.total_coins or recharge.recharge_amount # 充值状态(默认成功) status = recharge.status or "success" # 提现状态(默认未提现) withdrawal_status = recharge.withdrawal_status or "not_withdrawn" # 创建新记录 new_recharge = PlatformRecharge( recharge_id=recharge_id, user_id=recharge.user_id, user_name=recharge.user_name, user_phone=recharge.user_phone, recharge_amount=recharge.recharge_amount, recharge_time=recharge.recharge_time or datetime.now(), payment_method=recharge.payment_method, payment_channel=recharge.payment_channel, transaction_no=transaction_no, platform_order_no=platform_order_no, currency_type=recharge.currency_type or "CNY", exchange_rate=recharge.exchange_rate or 1.0, actual_amount_cny=actual_amount_cny, recharge_type=recharge.recharge_type or "normal", bonus_coins=recharge.bonus_coins or 0, total_coins=total_coins, is_first_recharge=recharge.is_first_recharge or False, ip_address=recharge.ip_address, device_type=recharge.device_type, device_id=recharge.device_id, province=recharge.province, city=recharge.city, status=status, refund_amount=recharge.refund_amount or 0, withdrawal_status=withdrawal_status, withdrawn_amount=recharge.withdrawn_amount or 0, ) db.add(new_recharge) await db.commit() await db.refresh(new_recharge) # 转换为响应格式 response = { "id": new_recharge.id, "recharge_id": new_recharge.recharge_id, "user_id": new_recharge.user_id, "user_name": new_recharge.user_name, "user_phone": new_recharge.user_phone, "recharge_amount": new_recharge.recharge_amount, "recharge_time": new_recharge.recharge_time.isoformat() if new_recharge.recharge_time else None, "payment_method": new_recharge.payment_method, "payment_channel": new_recharge.payment_channel, "transaction_no": new_recharge.transaction_no, "platform_order_no": new_recharge.platform_order_no, "currency_type": new_recharge.currency_type, "actual_amount_cny": new_recharge.actual_amount_cny, "recharge_type": new_recharge.recharge_type, "bonus_coins": new_recharge.bonus_coins, "total_coins": new_recharge.total_coins, "is_first_recharge": new_recharge.is_first_recharge, "province": new_recharge.province, "city": new_recharge.city, "status": new_recharge.status, "withdrawal_status": new_recharge.withdrawal_status, "withdrawn_amount": new_recharge.withdrawn_amount, "created_at": new_recharge.created_at.isoformat() if new_recharge.created_at else None, } return response @router.put("/{recharge_id}", response_model=PlatformRechargeResponse) async def update_recharge( recharge_id: str, recharge_update: PlatformRechargeUpdate, db: AsyncSession = Depends(get_async_session), ): """ 修改平台充值记录 """ logger.info(f"修改平台充值记录: {recharge_id}") # 查询 query = select(PlatformRecharge).where(PlatformRecharge.recharge_id == recharge_id) result = await db.execute(query) recharge = result.scalar_one_or_none() if not recharge: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"平台充值记录不存在: {recharge_id}", ) # 更新字段 update_data = recharge_update.model_dump(exclude_unset=True) for key, value in update_data.items(): if hasattr(recharge, key): setattr(recharge, key, value) await db.commit() await db.refresh(recharge) # 转换为响应格式 response = { "id": recharge.id, "recharge_id": recharge.recharge_id, "user_id": recharge.user_id, "user_name": recharge.user_name, "user_phone": recharge.user_phone, "recharge_amount": recharge.recharge_amount, "recharge_time": recharge.recharge_time.isoformat() if recharge.recharge_time else None, "payment_method": recharge.payment_method, "payment_channel": recharge.payment_channel, "transaction_no": recharge.transaction_no, "platform_order_no": recharge.platform_order_no, "currency_type": recharge.currency_type, "actual_amount_cny": recharge.actual_amount_cny, "recharge_type": recharge.recharge_type, "bonus_coins": recharge.bonus_coins, "total_coins": recharge.total_coins, "is_first_recharge": recharge.is_first_recharge, "province": recharge.province, "city": recharge.city, "status": recharge.status, "withdrawal_status": recharge.withdrawal_status, "withdrawn_amount": recharge.withdrawn_amount, "created_at": recharge.created_at.isoformat() if recharge.created_at else None, } return response @router.delete("/{recharge_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_recharge(recharge_id: str, db: AsyncSession = Depends(get_async_session)): """ 删除平台充值记录 """ logger.info(f"删除平台充值记录: {recharge_id}") # 查询 query = select(PlatformRecharge).where(PlatformRecharge.recharge_id == recharge_id) result = await db.execute(query) recharge = result.scalar_one_or_none() if not recharge: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail=f"平台充值记录不存在: {recharge_id}", ) # 删除 await db.delete(recharge) await db.commit() return None