billing.go 1.8 KB

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