71 lines
2.3 KiB
Go
71 lines
2.3 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/openteam/server/internal/pkg/resp"
|
|
"github.com/openteam/server/internal/store"
|
|
)
|
|
|
|
// UserProfile GET /api/v1/user/profile
|
|
func (h *Handler) UserProfile(c *gin.Context) {
|
|
u, _ := userFromContext(c)
|
|
resp.OK(c, gin.H{"user": h.publicUser(u)})
|
|
}
|
|
|
|
// UserBalance GET /api/v1/user/balance — 余额 + 近 30 日消耗。
|
|
func (h *Handler) UserBalance(c *gin.Context) {
|
|
u, _ := userFromContext(c)
|
|
var spent float64
|
|
h.a.DB.Model(&store.UsageLog{}).
|
|
Where("user_id = ? AND status = ? AND created_at >= ?", u.ID, store.UsageStatusSuccess, time.Now().Add(-30*24*time.Hour)).
|
|
Select("COALESCE(SUM(cost),0)").Scan(&spent)
|
|
resp.OK(c, gin.H{
|
|
"balance": u.Balance,
|
|
"spent_last_30d": spent,
|
|
"today": h.todayUsage(c, u.ID),
|
|
"models_available": h.availableModelCount(),
|
|
})
|
|
}
|
|
|
|
func (h *Handler) availableModelCount() int64 {
|
|
var n int64
|
|
h.a.DB.Model(&store.Model{}).Where("enabled = ?", true).Count(&n)
|
|
return n
|
|
}
|
|
|
|
func (h *Handler) todayUsage(c *gin.Context, userID uint64) gin.H {
|
|
var requests int64
|
|
var tokens int64
|
|
var cost float64
|
|
today := time.Now().UTC().Format("2006-01-02")
|
|
h.a.DB.Model(&store.UsageDaily{}).
|
|
Where("user_id = ? AND date = ?", userID, today).
|
|
Select("COALESCE(SUM(requests),0), COALESCE(SUM(input_tokens+output_tokens+cache_read_tokens),0), COALESCE(SUM(cost),0)").
|
|
Row().Scan(&requests, &tokens, &cost)
|
|
return gin.H{"requests": requests, "tokens": tokens, "cost": cost}
|
|
}
|
|
|
|
// UserModels GET /api/v1/user/models — 控制台可用模型列表(无需 API Key)。
|
|
// 仅返回启用的模型且至少绑定到一个启用且健康的渠道,与 /v1/models 口径一致。
|
|
func (h *Handler) UserModels(c *gin.Context) {
|
|
var names []string
|
|
if err := h.a.DB.Table("models").
|
|
Joins("JOIN channel_model_bindings ON channel_model_bindings.model_id = models.id").
|
|
Joins("JOIN channels ON channels.id = channel_model_bindings.channel_id").
|
|
Where("models.enabled = ? AND channels.enabled = ? AND channels.health_status = ?",
|
|
true, true, store.ChannelHealthHealthy).
|
|
Distinct("models.name").
|
|
Order("models.sort ASC, models.id ASC").
|
|
Pluck("models.name", &names).Error; err != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to load models")
|
|
return
|
|
}
|
|
if names == nil {
|
|
names = []string{}
|
|
}
|
|
resp.OK(c, gin.H{"items": names})
|
|
}
|