38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
from fastapi import APIRouter, Depends, Body
|
|
from sqlalchemy.orm import Session
|
|
|
|
from database import get_db
|
|
from models import TokenAccount, TokenPlan
|
|
from responses import ok, fail
|
|
|
|
router = APIRouter(tags=["Token"])
|
|
|
|
|
|
@router.get("/token/balance")
|
|
def balance(db: Session = Depends(get_db)):
|
|
acc = db.query(TokenAccount).first()
|
|
return ok({"balance": acc.balance if acc else 0})
|
|
|
|
|
|
@router.get("/token/plans")
|
|
def plans(db: Session = Depends(get_db)):
|
|
items = db.query(TokenPlan).order_by(TokenPlan.price.asc()).all()
|
|
return ok([p.to_dict() for p in items])
|
|
|
|
|
|
@router.post("/token/charge")
|
|
def charge(payload: dict = Body(...), db: Session = Depends(get_db)):
|
|
plan_id = payload.get("planId")
|
|
plan = db.query(TokenPlan).filter(TokenPlan.id == plan_id).first()
|
|
if not plan:
|
|
return fail("套餐不存在", 404)
|
|
acc = db.query(TokenAccount).first()
|
|
if not acc:
|
|
acc = TokenAccount(balance=0)
|
|
db.add(acc)
|
|
db.commit()
|
|
db.refresh(acc)
|
|
acc.balance += plan.amount
|
|
db.commit()
|
|
return ok({"balance": acc.balance, "charged": plan.amount})
|