Просмотр исходного кода

feat: return user's quota with billing api (close #92)

JustSong 2 лет назад
Родитель
Сommit
d4794fc051
3 измененных файлов с 63 добавлено и 4 удалено
  1. 41 0
      controller/billing.go
  2. 17 2
      controller/channel-billing.go
  3. 5 2
      router/dashboard.go

+ 41 - 0
controller/billing.go

@@ -0,0 +1,41 @@
+package controller
+
+import (
+	"github.com/gin-gonic/gin"
+	"one-api/model"
+)
+
+func GetSubscription(c *gin.Context) {
+	userId := c.GetInt("id")
+	quota, err := model.GetUserQuota(userId)
+	if err != nil {
+		openAIError := OpenAIError{
+			Message: err.Error(),
+			Type:    "one_api_error",
+		}
+		c.JSON(200, gin.H{
+			"error": openAIError,
+		})
+		return
+	}
+	subscription := OpenAISubscriptionResponse{
+		Object:             "billing_subscription",
+		HasPaymentMethod:   true,
+		SoftLimitUSD:       float64(quota),
+		HardLimitUSD:       float64(quota),
+		SystemHardLimitUSD: float64(quota),
+	}
+	c.JSON(200, subscription)
+	return
+}
+
+func GetUsage(c *gin.Context) {
+	//userId := c.GetInt("id")
+	// TODO: get usage from database
+	usage := OpenAIUsageResponse{
+		Object:     "list",
+		TotalUsage: 0,
+	}
+	c.JSON(200, usage)
+	return
+}

+ 17 - 2
controller/channel-billing.go

@@ -13,12 +13,27 @@ import (
 	"time"
 )
 
+// https://github.com/songquanpeng/one-api/issues/79
+
 type OpenAISubscriptionResponse struct {
-	HasPaymentMethod bool    `json:"has_payment_method"`
-	HardLimitUSD     float64 `json:"hard_limit_usd"`
+	Object             string  `json:"object"`
+	HasPaymentMethod   bool    `json:"has_payment_method"`
+	SoftLimitUSD       float64 `json:"soft_limit_usd"`
+	HardLimitUSD       float64 `json:"hard_limit_usd"`
+	SystemHardLimitUSD float64 `json:"system_hard_limit_usd"`
+}
+
+type OpenAIUsageDailyCost struct {
+	Timestamp float64 `json:"timestamp"`
+	LineItems []struct {
+		Name string  `json:"name"`
+		Cost float64 `json:"cost"`
+	}
 }
 
 type OpenAIUsageResponse struct {
+	Object string `json:"object"`
+	//DailyCosts []OpenAIUsageDailyCost `json:"daily_costs"`
 	TotalUsage float64 `json:"total_usage"` // unit: 0.01 dollar
 }
 

+ 5 - 2
router/dashboard.go

@@ -8,11 +8,14 @@ import (
 )
 
 func SetDashboardRouter(router *gin.Engine) {
-	apiRouter := router.Group("/dashboard")
+	apiRouter := router.Group("/")
 	apiRouter.Use(gzip.Gzip(gzip.DefaultCompression))
 	apiRouter.Use(middleware.GlobalAPIRateLimit())
 	apiRouter.Use(middleware.TokenAuth())
 	{
-		apiRouter.GET("/billing/credit_grants", controller.GetTokenStatus)
+		apiRouter.GET("/dashboard/billing/subscription", controller.GetSubscription)
+		apiRouter.GET("/v1/dashboard/billing/subscription", controller.GetSubscription)
+		apiRouter.GET("/dashboard/billing/usage", controller.GetUsage)
+		apiRouter.GET("/v1/dashboard/billing/usage", controller.GetUsage)
 	}
 }