- 后端 Go+Gin+GORM: 配置(OT_ env)/SQLite/Postgres 双驱动、用户体系(argon2id+JWT access/refresh)、 API Key(sk- 48位, 仅存 SHA-256 哈希) - 代理网关: /v1/chat/completions、/v1/responses、/v1/messages、/v1/models;错误按客户端协议返回 - 三协议互转(convert 包): Chat↔Messages↔Responses 请求/响应 + 流式 SSE 逐事件转换(直通优先) - 用量计费: 异步批量记账、余额扣减、balance_logs、usage_daily 日聚合 - 管理 API: 用户/渠道 CRUD+测试+模型导入/模型定价+绑定/统计/系统配置 - 前端 Vue3+TS+Tailwind(taste-skill 设计 tokens): Landing/登录注册/控制台/管理后台, 自建组件+Phosphor 图标+自建 SVG 趋势图, 已过 web-design-guidelines 复查 - mock 上游: OpenAI+Anthropic 双协议模拟(含流式) Co-Authored-By: Claude <noreply@anthropic.com>
64 lines
1.9 KiB
Go
64 lines
1.9 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)。
|
|
func (h *Handler) UserModels(c *gin.Context) {
|
|
var ms []store.Model
|
|
if err := h.a.DB.Where("enabled = ?", true).Order("sort ASC, id ASC").Find(&ms).Error; err != nil {
|
|
resp.Fail(c, http.StatusInternalServerError, "failed to load models")
|
|
return
|
|
}
|
|
out := make([]string, 0, len(ms))
|
|
for _, m := range ms {
|
|
out = append(out, m.Name)
|
|
}
|
|
resp.OK(c, gin.H{"items": out})
|
|
}
|