Files
2026-01-09 09:48:57 +08:00

148 lines
4.8 KiB
Python

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app import models, database
from pydantic import BaseModel
router = APIRouter()
def get_db():
db = database.SessionLocal()
try:
yield db
finally:
db.close()
from app.utils_jwt import get_current_user
# 根路径返回所有应用
@router.get("/")
def root_apps(db: Session = Depends(get_db)):
apps = db.query(models.App).all()
return {"apps": [
{"id": app.id, "name": app.name, "desc": app.desc, "price": app.price, "status": app.status} for app in apps
]}
class AppCreate(BaseModel):
name: str
desc: str
price: float
status: str = "上架"
class AppUpdate(BaseModel):
name: str = None
desc: str = None
price: float = None
status: str = None
# 查询所有应用(用户/前端)
@router.get("/list")
def list_apps(db: Session = Depends(get_db)):
apps = db.query(models.App).all()
return {"apps": [
{"id": app.id, "name": app.name, "desc": app.desc, "price": app.price, "status": app.status} for app in apps
]}
# 管理员获取全部应用(含下架)
@router.get("/all")
def list_all_apps(db: Session = Depends(get_db), user=Depends(get_current_user)):
if not getattr(user, "is_admin", False):
raise HTTPException(status_code=403, detail="无权限")
apps = db.query(models.App).all()
return [
{"id": app.id, "name": app.name, "desc": app.desc, "price": app.price, "status": app.status} for app in apps
]
# 新增应用(管理员)
@router.post("/add")
def add_app(app: AppCreate, db: Session = Depends(get_db), user=Depends(get_current_user)):
if not getattr(user, "is_admin", False):
raise HTTPException(status_code=403, detail="无权限")
new_app = models.App(**app.dict())
db.add(new_app)
db.commit()
db.refresh(new_app)
return {"msg": "添加成功", "app": {"id": new_app.id, "name": new_app.name}}
# 修改应用(管理员)
@router.put("/edit/{app_id}")
def edit_app(app_id: int, app: AppUpdate, db: Session = Depends(get_db), user=Depends(get_current_user)):
if not getattr(user, "is_admin", False):
raise HTTPException(status_code=403, detail="无权限")
db_app = db.query(models.App).filter(models.App.id == app_id).first()
if not db_app:
raise HTTPException(status_code=404, detail="应用不存在")
for field, value in app.dict(exclude_unset=True).items():
setattr(db_app, field, value)
db.commit()
return {"msg": "修改成功"}
# 删除应用(管理员)
@router.delete("/delete/{app_id}")
def delete_app(app_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_app = db.query(models.App).filter(models.App.id == app_id).first()
if not db_app:
raise HTTPException(status_code=404, detail="应用不存在")
db.delete(db_app)
db.commit()
return {"msg": "删除成功"}
# 用户调用应用(消费)
class UseAppRequest(BaseModel):
app_id: int
@router.post("/use")
def use_app(req: UseAppRequest, db: Session = Depends(get_db), user=Depends(get_current_user)):
# 获取应用信息
db_app = db.query(models.App).filter(models.App.id == req.app_id).first()
if not db_app:
raise HTTPException(status_code=404, detail="应用不存在")
# 获取最新的用户信息
db_user = db.query(models.User).filter(models.User.id == user.id).first()
if not db_user:
raise HTTPException(status_code=404, detail="用户不存在")
# 检查余额
if db_user.balance < db_app.price:
raise HTTPException(status_code=400, detail="余额不足,请先充值")
try:
# 扣除余额
db_user.balance -= db_app.price
# 添加消费记录
from app.models import History
record = History(
user_id=db_user.id,
type='consume',
amount=-db_app.price,
desc=f"调用{db_app.name}"
)
db.add(record)
# 添加订单记录
from app.models import Order
order = Order(
user_id=db_user.id,
app_id=db_app.id,
type=db_app.name, # 使用应用名称作为订单类型
amount=db_app.price,
description=db_app.desc, # 添加应用描述
status="已完成" # 使用"已完成"代替"已支付"
)
db.add(order)
# 提交事务
db.commit()
return {
"msg": f"成功调用 {db_app.name}!已扣除{db_app.price}元。",
"balance": db_user.balance
}
except Exception as e:
db.rollback()
raise HTTPException(status_code=500, detail=f"操作失败:{str(e)}")