141 lines
5.3 KiB
Python
141 lines
5.3 KiB
Python
from fastapi import APIRouter, Depends, HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from app import models, database
|
|
from pydantic import BaseModel
|
|
from typing import Optional
|
|
from app.utils_jwt import get_current_user
|
|
|
|
router = APIRouter()
|
|
|
|
def get_db():
|
|
db = database.SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
# 根路径返回所有订单(管理员)
|
|
@router.get("/")
|
|
def root_orders(db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
if not getattr(user, "is_admin", False):
|
|
raise HTTPException(status_code=403, detail="无权限")
|
|
|
|
try:
|
|
# 从历史记录表中获取消费记录
|
|
consume_records = db.query(models.History).filter(models.History.type == "consume").all()
|
|
|
|
result = []
|
|
for r in consume_records:
|
|
# 获取用户名(如果存在)
|
|
username = ""
|
|
user_record = db.query(models.User).filter(models.User.id == r.user_id).first()
|
|
if user_record:
|
|
username = user_record.username
|
|
|
|
# 安全处理时间格式
|
|
timestamp_str = ""
|
|
try:
|
|
if hasattr(r, 'created_at') and r.created_at:
|
|
timestamp_str = r.created_at.strftime('%Y-%m-%d %H:%M:%S')
|
|
elif hasattr(r, 'timestamp') and r.timestamp:
|
|
timestamp_str = r.timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
|
except:
|
|
timestamp_str = str(r.created_at or r.timestamp or "")
|
|
|
|
result.append({
|
|
"id": r.id,
|
|
"user_id": r.user_id,
|
|
"username": username,
|
|
"type": r.type,
|
|
"amount": abs(r.amount), # 转为正数显示
|
|
"desc": r.desc,
|
|
"time": timestamp_str,
|
|
"status": "已完成" # 默认状态
|
|
})
|
|
|
|
return {"orders": result}
|
|
except Exception as e:
|
|
print(f"Error in root_orders: {str(e)}")
|
|
return {"orders": [], "error": str(e)}
|
|
|
|
# 查询当前用户订单
|
|
@router.get("/my")
|
|
def my_orders(db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
orders = db.query(models.Order).filter(models.Order.user_id == user.id).all()
|
|
return {"orders": [
|
|
{"id": o.id, "app_id": o.app_id, "amount": o.amount, "status": o.status, "timestamp": o.timestamp} for o in orders
|
|
]}
|
|
|
|
# 管理员查询所有订单
|
|
@router.get("/all")
|
|
def all_orders(db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
if not getattr(user, "is_admin", False):
|
|
raise HTTPException(status_code=403, detail="无权限")
|
|
|
|
try:
|
|
# 从历史记录表中获取消费记录
|
|
consume_records = db.query(models.History).filter(models.History.type == "consume").all()
|
|
|
|
result = []
|
|
for r in consume_records:
|
|
# 获取用户名(如果存在)
|
|
username = ""
|
|
user_record = db.query(models.User).filter(models.User.id == r.user_id).first()
|
|
if user_record:
|
|
username = user_record.username
|
|
|
|
# 安全处理时间格式
|
|
timestamp_str = ""
|
|
try:
|
|
if hasattr(r, 'created_at') and r.created_at:
|
|
timestamp_str = r.created_at.strftime('%Y-%m-%d %H:%M:%S')
|
|
elif hasattr(r, 'timestamp') and r.timestamp:
|
|
timestamp_str = r.timestamp.strftime('%Y-%m-%d %H:%M:%S')
|
|
except:
|
|
timestamp_str = str(r.created_at or r.timestamp or "")
|
|
|
|
result.append({
|
|
"id": r.id,
|
|
"user_id": r.user_id,
|
|
"username": username,
|
|
"type": r.type,
|
|
"amount": abs(r.amount), # 转为正数显示
|
|
"desc": r.desc,
|
|
"time": timestamp_str,
|
|
"status": "已完成" # 默认状态
|
|
})
|
|
|
|
return {"orders": result}
|
|
except Exception as e:
|
|
print(f"Error in all_orders: {str(e)}")
|
|
return {"orders": [], "error": str(e)}
|
|
|
|
class OrderUpdate(BaseModel):
|
|
status: Optional[str] = None
|
|
amount: Optional[float] = None
|
|
|
|
# 管理员修改订单
|
|
@router.put("/orders/{order_id}")
|
|
def update_order(order_id: int, order: OrderUpdate, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
if not getattr(user, "is_admin", False):
|
|
raise HTTPException(status_code=403, detail="无权限")
|
|
db_order = db.query(models.Order).filter(models.Order.id == order_id).first()
|
|
if not db_order:
|
|
raise HTTPException(status_code=404, detail="订单不存在")
|
|
for field, value in order.dict(exclude_unset=True).items():
|
|
setattr(db_order, field, value)
|
|
db.commit()
|
|
return {"msg": "修改成功"}
|
|
|
|
# 管理员删除订单
|
|
@router.delete("/orders/{order_id}")
|
|
def delete_order(order_id: int, db: Session = Depends(get_db), user=Depends(get_current_user)):
|
|
if not getattr(user, "is_admin", False):
|
|
raise HTTPException(status_code=403, detail="无权限")
|
|
db_order = db.query(models.Order).filter(models.Order.id == order_id).first()
|
|
if not db_order:
|
|
raise HTTPException(status_code=404, detail="订单不存在")
|
|
db.delete(db_order)
|
|
db.commit()
|
|
return {"msg": "删除成功"}
|