billing.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package controller
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "one-api/common"
  5. "one-api/dto"
  6. "one-api/model"
  7. )
  8. func GetSubscription(c *gin.Context) {
  9. var remainQuota int
  10. var usedQuota int
  11. var err error
  12. var token *model.Token
  13. var expiredTime int64
  14. if common.DisplayTokenStatEnabled {
  15. tokenId := c.GetInt("token_id")
  16. token, err = model.GetTokenById(tokenId)
  17. expiredTime = token.ExpiredTime
  18. remainQuota = token.RemainQuota
  19. usedQuota = token.UsedQuota
  20. } else {
  21. userId := c.GetInt("id")
  22. remainQuota, err = model.GetUserQuota(userId, false)
  23. usedQuota, err = model.GetUserUsedQuota(userId)
  24. }
  25. if expiredTime <= 0 {
  26. expiredTime = 0
  27. }
  28. if err != nil {
  29. openAIError := dto.OpenAIError{
  30. Message: err.Error(),
  31. Type: "upstream_error",
  32. }
  33. c.JSON(200, gin.H{
  34. "error": openAIError,
  35. })
  36. return
  37. }
  38. quota := remainQuota + usedQuota
  39. amount := float64(quota)
  40. if common.DisplayInCurrencyEnabled {
  41. amount /= common.QuotaPerUnit
  42. }
  43. if token != nil && token.UnlimitedQuota {
  44. amount = 100000000
  45. }
  46. subscription := OpenAISubscriptionResponse{
  47. Object: "billing_subscription",
  48. HasPaymentMethod: true,
  49. SoftLimitUSD: amount,
  50. HardLimitUSD: amount,
  51. SystemHardLimitUSD: amount,
  52. AccessUntil: expiredTime,
  53. }
  54. c.JSON(200, subscription)
  55. return
  56. }
  57. func GetUsage(c *gin.Context) {
  58. var quota int
  59. var err error
  60. var token *model.Token
  61. if common.DisplayTokenStatEnabled {
  62. tokenId := c.GetInt("token_id")
  63. token, err = model.GetTokenById(tokenId)
  64. quota = token.UsedQuota
  65. } else {
  66. userId := c.GetInt("id")
  67. quota, err = model.GetUserUsedQuota(userId)
  68. }
  69. if err != nil {
  70. openAIError := dto.OpenAIError{
  71. Message: err.Error(),
  72. Type: "new_api_error",
  73. }
  74. c.JSON(200, gin.H{
  75. "error": openAIError,
  76. })
  77. return
  78. }
  79. amount := float64(quota)
  80. if common.DisplayInCurrencyEnabled {
  81. amount /= common.QuotaPerUnit
  82. }
  83. usage := OpenAIUsageResponse{
  84. Object: "list",
  85. TotalUsage: amount * 100,
  86. }
  87. c.JSON(200, usage)
  88. return
  89. }