Merge remote-tracking branch 'upstream/alpha' into update-gemini-ratio

This commit is contained in:
RedwindA
2025-06-19 20:02:27 +08:00
40 changed files with 856 additions and 374 deletions

View File

@@ -52,6 +52,14 @@ func GetAllChannels(c *gin.Context) {
channelData := make([]*model.Channel, 0) channelData := make([]*model.Channel, 0)
idSort, _ := strconv.ParseBool(c.Query("id_sort")) idSort, _ := strconv.ParseBool(c.Query("id_sort"))
enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode")) enableTagMode, _ := strconv.ParseBool(c.Query("tag_mode"))
// type filter
typeStr := c.Query("type")
typeFilter := -1
if typeStr != "" {
if t, err := strconv.Atoi(typeStr); err == nil {
typeFilter = t
}
}
var total int64 var total int64
@@ -72,6 +80,14 @@ func GetAllChannels(c *gin.Context) {
} }
// 计算 tag 总数用于分页 // 计算 tag 总数用于分页
total, _ = model.CountAllTags() total, _ = model.CountAllTags()
} else if typeFilter >= 0 {
channels, err := model.GetChannelsByType((p-1)*pageSize, pageSize, idSort, typeFilter)
if err != nil {
c.JSON(http.StatusOK, gin.H{"success": false, "message": err.Error()})
return
}
channelData = channels
total, _ = model.CountChannelsByType(typeFilter)
} else { } else {
channels, err := model.GetAllChannels((p-1)*pageSize, pageSize, false, idSort) channels, err := model.GetAllChannels((p-1)*pageSize, pageSize, false, idSort)
if err != nil { if err != nil {
@@ -82,14 +98,18 @@ func GetAllChannels(c *gin.Context) {
total, _ = model.CountAllChannels() total, _ = model.CountAllChannels()
} }
// calculate type counts
typeCounts, _ := model.CountChannelsGroupByType()
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"message": "", "message": "",
"data": gin.H{ "data": gin.H{
"items": channelData, "items": channelData,
"total": total, "total": total,
"page": p, "page": p,
"page_size": pageSize, "page_size": pageSize,
"type_counts": typeCounts,
}, },
}) })
return return
@@ -217,10 +237,20 @@ func SearchChannels(c *gin.Context) {
} }
channelData = channels channelData = channels
} }
// calculate type counts for search results
typeCounts := make(map[int64]int64)
for _, channel := range channelData {
typeCounts[int64(channel.Type)]++
}
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": true, "success": true,
"message": "", "message": "",
"data": channelData, "data": gin.H{
"items": channelData,
"type_counts": typeCounts,
},
}) })
return return
} }

View File

@@ -4,13 +4,14 @@ import (
"net/http" "net/http"
"one-api/model" "one-api/model"
"one-api/setting" "one-api/setting"
"one-api/setting/ratio_setting"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func GetGroups(c *gin.Context) { func GetGroups(c *gin.Context) {
groupNames := make([]string, 0) groupNames := make([]string, 0)
for groupName, _ := range setting.GetGroupRatioCopy() { for groupName := range ratio_setting.GetGroupRatioCopy() {
groupNames = append(groupNames, groupName) groupNames = append(groupNames, groupName)
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
@@ -25,7 +26,7 @@ func GetUserGroups(c *gin.Context) {
userGroup := "" userGroup := ""
userId := c.GetInt("id") userId := c.GetInt("id")
userGroup, _ = model.GetUserGroup(userId, false) userGroup, _ = model.GetUserGroup(userId, false)
for groupName, ratio := range setting.GetGroupRatioCopy() { for groupName, ratio := range ratio_setting.GetGroupRatioCopy() {
// UserUsableGroups contains the groups that the user can use // UserUsableGroups contains the groups that the user can use
userUsableGroups := setting.GetUserUsableGroups(userGroup) userUsableGroups := setting.GetUserUsableGroups(userGroup)
if desc, ok := userUsableGroups[groupName]; ok { if desc, ok := userUsableGroups[groupName]; ok {

View File

@@ -76,6 +76,7 @@ func GetStatus(c *gin.Context) {
"demo_site_enabled": operation_setting.DemoSiteEnabled, "demo_site_enabled": operation_setting.DemoSiteEnabled,
"self_use_mode_enabled": operation_setting.SelfUseModeEnabled, "self_use_mode_enabled": operation_setting.SelfUseModeEnabled,
"default_use_auto_group": setting.DefaultUseAutoGroup, "default_use_auto_group": setting.DefaultUseAutoGroup,
"pay_methods": setting.PayMethods,
// 面板启用开关 // 面板启用开关
"api_info_enabled": cs.ApiInfoEnabled, "api_info_enabled": cs.ApiInfoEnabled,

View File

@@ -7,6 +7,7 @@ import (
"one-api/model" "one-api/model"
"one-api/setting" "one-api/setting"
"one-api/setting/console_setting" "one-api/setting/console_setting"
"one-api/setting/ratio_setting"
"one-api/setting/system_setting" "one-api/setting/system_setting"
"strings" "strings"
@@ -103,7 +104,7 @@ func UpdateOption(c *gin.Context) {
return return
} }
case "GroupRatio": case "GroupRatio":
err = setting.CheckGroupRatio(option.Value) err = ratio_setting.CheckGroupRatio(option.Value)
if err != nil { if err != nil {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"success": false, "success": false,

View File

@@ -3,7 +3,7 @@ package controller
import ( import (
"one-api/model" "one-api/model"
"one-api/setting" "one-api/setting"
"one-api/setting/operation_setting" "one-api/setting/ratio_setting"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -13,7 +13,7 @@ func GetPricing(c *gin.Context) {
userId, exists := c.Get("id") userId, exists := c.Get("id")
usableGroup := map[string]string{} usableGroup := map[string]string{}
groupRatio := map[string]float64{} groupRatio := map[string]float64{}
for s, f := range setting.GetGroupRatioCopy() { for s, f := range ratio_setting.GetGroupRatioCopy() {
groupRatio[s] = f groupRatio[s] = f
} }
var group string var group string
@@ -22,7 +22,7 @@ func GetPricing(c *gin.Context) {
if err == nil { if err == nil {
group = user.Group group = user.Group
for g := range groupRatio { for g := range groupRatio {
ratio, ok := setting.GetGroupGroupRatio(group, g) ratio, ok := ratio_setting.GetGroupGroupRatio(group, g)
if ok { if ok {
groupRatio[g] = ratio groupRatio[g] = ratio
} }
@@ -32,7 +32,7 @@ func GetPricing(c *gin.Context) {
usableGroup = setting.GetUserUsableGroups(group) usableGroup = setting.GetUserUsableGroups(group)
// check groupRatio contains usableGroup // check groupRatio contains usableGroup
for group := range setting.GetGroupRatioCopy() { for group := range ratio_setting.GetGroupRatioCopy() {
if _, ok := usableGroup[group]; !ok { if _, ok := usableGroup[group]; !ok {
delete(groupRatio, group) delete(groupRatio, group)
} }
@@ -47,7 +47,7 @@ func GetPricing(c *gin.Context) {
} }
func ResetModelRatio(c *gin.Context) { func ResetModelRatio(c *gin.Context) {
defaultStr := operation_setting.DefaultModelRatio2JSONString() defaultStr := ratio_setting.DefaultModelRatio2JSONString()
err := model.UpdateOption("ModelRatio", defaultStr) err := model.UpdateOption("ModelRatio", defaultStr)
if err != nil { if err != nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
@@ -56,7 +56,7 @@ func ResetModelRatio(c *gin.Context) {
}) })
return return
} }
err = operation_setting.UpdateModelRatioByJSONString(defaultStr) err = ratio_setting.UpdateModelRatioByJSONString(defaultStr)
if err != nil { if err != nil {
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"success": false, "success": false,

View File

@@ -53,6 +53,7 @@ type GeneralOpenAIRequest struct {
Modalities json.RawMessage `json:"modalities,omitempty"` Modalities json.RawMessage `json:"modalities,omitempty"`
Audio json.RawMessage `json:"audio,omitempty"` Audio json.RawMessage `json:"audio,omitempty"`
EnableThinking any `json:"enable_thinking,omitempty"` // ali EnableThinking any `json:"enable_thinking,omitempty"` // ali
THINKING json.RawMessage `json:"thinking,omitempty"` // doubao
ExtraBody json.RawMessage `json:"extra_body,omitempty"` ExtraBody json.RawMessage `json:"extra_body,omitempty"`
WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"` WebSearchOptions *WebSearchOptions `json:"web_search_options,omitempty"`
// OpenRouter Params // OpenRouter Params

View File

@@ -12,7 +12,7 @@ import (
"one-api/model" "one-api/model"
"one-api/router" "one-api/router"
"one-api/service" "one-api/service"
"one-api/setting/operation_setting" "one-api/setting/ratio_setting"
"os" "os"
"strconv" "strconv"
@@ -74,7 +74,7 @@ func main() {
} }
// Initialize model settings // Initialize model settings
operation_setting.InitRatioSettings() ratio_setting.InitRatioSettings()
// Initialize constants // Initialize constants
constant.InitEnv() constant.InitEnv()
// Initialize options // Initialize options

View File

@@ -11,6 +11,7 @@ import (
relayconstant "one-api/relay/constant" relayconstant "one-api/relay/constant"
"one-api/service" "one-api/service"
"one-api/setting" "one-api/setting"
"one-api/setting/ratio_setting"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -48,7 +49,7 @@ func Distribute() func(c *gin.Context) {
return return
} }
// check group in common.GroupRatio // check group in common.GroupRatio
if !setting.ContainsGroupRatio(tokenGroup) { if !ratio_setting.ContainsGroupRatio(tokenGroup) {
if tokenGroup != "auto" { if tokenGroup != "auto" {
abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup)) abortWithOpenAiMessage(c, http.StatusForbidden, fmt.Sprintf("分组 %s 已被弃用", tokenGroup))
return return

View File

@@ -597,3 +597,39 @@ func CountAllTags() (int64, error) {
err := DB.Model(&Channel{}).Where("tag is not null AND tag != ''").Distinct("tag").Count(&total).Error err := DB.Model(&Channel{}).Where("tag is not null AND tag != ''").Distinct("tag").Count(&total).Error
return total, err return total, err
} }
// Get channels of specified type with pagination
func GetChannelsByType(startIdx int, num int, idSort bool, channelType int) ([]*Channel, error) {
var channels []*Channel
order := "priority desc"
if idSort {
order = "id desc"
}
err := DB.Where("type = ?", channelType).Order(order).Limit(num).Offset(startIdx).Omit("key").Find(&channels).Error
return channels, err
}
// Count channels of specific type
func CountChannelsByType(channelType int) (int64, error) {
var count int64
err := DB.Model(&Channel{}).Where("type = ?", channelType).Count(&count).Error
return count, err
}
// Return map[type]count for all channels
func CountChannelsGroupByType() (map[int64]int64, error) {
type result struct {
Type int64 `gorm:"column:type"`
Count int64 `gorm:"column:count"`
}
var results []result
err := DB.Model(&Channel{}).Select("type, count(*) as count").Group("type").Find(&results).Error
if err != nil {
return nil, err
}
counts := make(map[int64]int64)
for _, r := range results {
counts[r.Type] = r.Count
}
return counts, nil
}

View File

@@ -46,6 +46,15 @@ func initCol() {
logGroupCol = commonGroupCol logGroupCol = commonGroupCol
logKeyCol = commonKeyCol logKeyCol = commonKeyCol
} }
} else {
// LOG_SQL_DSN 为空时,日志数据库与主数据库相同
if common.UsingPostgreSQL {
logGroupCol = `"group"`
logKeyCol = `"key"`
} else {
logGroupCol = commonGroupCol
logKeyCol = commonKeyCol
}
} }
// log sql type and database type // log sql type and database type
common.SysLog("Using Log SQL Type: " + common.LogSqlType) common.SysLog("Using Log SQL Type: " + common.LogSqlType)

View File

@@ -5,6 +5,7 @@ import (
"one-api/setting" "one-api/setting"
"one-api/setting/config" "one-api/setting/config"
"one-api/setting/operation_setting" "one-api/setting/operation_setting"
"one-api/setting/ratio_setting"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -78,6 +79,7 @@ func InitOptionMap() {
common.OptionMap["Chats"] = setting.Chats2JsonString() common.OptionMap["Chats"] = setting.Chats2JsonString()
common.OptionMap["AutoGroups"] = setting.AutoGroups2JsonString() common.OptionMap["AutoGroups"] = setting.AutoGroups2JsonString()
common.OptionMap["DefaultUseAutoGroup"] = strconv.FormatBool(setting.DefaultUseAutoGroup) common.OptionMap["DefaultUseAutoGroup"] = strconv.FormatBool(setting.DefaultUseAutoGroup)
common.OptionMap["PayMethods"] = setting.PayMethods2JsonString()
common.OptionMap["GitHubClientId"] = "" common.OptionMap["GitHubClientId"] = ""
common.OptionMap["GitHubClientSecret"] = "" common.OptionMap["GitHubClientSecret"] = ""
common.OptionMap["TelegramBotToken"] = "" common.OptionMap["TelegramBotToken"] = ""
@@ -96,13 +98,13 @@ func InitOptionMap() {
common.OptionMap["ModelRequestRateLimitDurationMinutes"] = strconv.Itoa(setting.ModelRequestRateLimitDurationMinutes) common.OptionMap["ModelRequestRateLimitDurationMinutes"] = strconv.Itoa(setting.ModelRequestRateLimitDurationMinutes)
common.OptionMap["ModelRequestRateLimitSuccessCount"] = strconv.Itoa(setting.ModelRequestRateLimitSuccessCount) common.OptionMap["ModelRequestRateLimitSuccessCount"] = strconv.Itoa(setting.ModelRequestRateLimitSuccessCount)
common.OptionMap["ModelRequestRateLimitGroup"] = setting.ModelRequestRateLimitGroup2JSONString() common.OptionMap["ModelRequestRateLimitGroup"] = setting.ModelRequestRateLimitGroup2JSONString()
common.OptionMap["ModelRatio"] = operation_setting.ModelRatio2JSONString() common.OptionMap["ModelRatio"] = ratio_setting.ModelRatio2JSONString()
common.OptionMap["ModelPrice"] = operation_setting.ModelPrice2JSONString() common.OptionMap["ModelPrice"] = ratio_setting.ModelPrice2JSONString()
common.OptionMap["CacheRatio"] = operation_setting.CacheRatio2JSONString() common.OptionMap["CacheRatio"] = ratio_setting.CacheRatio2JSONString()
common.OptionMap["GroupRatio"] = setting.GroupRatio2JSONString() common.OptionMap["GroupRatio"] = ratio_setting.GroupRatio2JSONString()
common.OptionMap["GroupGroupRatio"] = setting.GroupGroupRatio2JSONString() common.OptionMap["GroupGroupRatio"] = ratio_setting.GroupGroupRatio2JSONString()
common.OptionMap["UserUsableGroups"] = setting.UserUsableGroups2JSONString() common.OptionMap["UserUsableGroups"] = setting.UserUsableGroups2JSONString()
common.OptionMap["CompletionRatio"] = operation_setting.CompletionRatio2JSONString() common.OptionMap["CompletionRatio"] = ratio_setting.CompletionRatio2JSONString()
common.OptionMap["TopUpLink"] = common.TopUpLink common.OptionMap["TopUpLink"] = common.TopUpLink
//common.OptionMap["ChatLink"] = common.ChatLink //common.OptionMap["ChatLink"] = common.ChatLink
//common.OptionMap["ChatLink2"] = common.ChatLink2 //common.OptionMap["ChatLink2"] = common.ChatLink2
@@ -358,19 +360,19 @@ func updateOptionMap(key string, value string) (err error) {
case "DataExportDefaultTime": case "DataExportDefaultTime":
common.DataExportDefaultTime = value common.DataExportDefaultTime = value
case "ModelRatio": case "ModelRatio":
err = operation_setting.UpdateModelRatioByJSONString(value) err = ratio_setting.UpdateModelRatioByJSONString(value)
case "GroupRatio": case "GroupRatio":
err = setting.UpdateGroupRatioByJSONString(value) err = ratio_setting.UpdateGroupRatioByJSONString(value)
case "GroupGroupRatio": case "GroupGroupRatio":
err = setting.UpdateGroupGroupRatioByJSONString(value) err = ratio_setting.UpdateGroupGroupRatioByJSONString(value)
case "UserUsableGroups": case "UserUsableGroups":
err = setting.UpdateUserUsableGroupsByJSONString(value) err = setting.UpdateUserUsableGroupsByJSONString(value)
case "CompletionRatio": case "CompletionRatio":
err = operation_setting.UpdateCompletionRatioByJSONString(value) err = ratio_setting.UpdateCompletionRatioByJSONString(value)
case "ModelPrice": case "ModelPrice":
err = operation_setting.UpdateModelPriceByJSONString(value) err = ratio_setting.UpdateModelPriceByJSONString(value)
case "CacheRatio": case "CacheRatio":
err = operation_setting.UpdateCacheRatioByJSONString(value) err = ratio_setting.UpdateCacheRatioByJSONString(value)
case "TopUpLink": case "TopUpLink":
common.TopUpLink = value common.TopUpLink = value
//case "ChatLink": //case "ChatLink":
@@ -387,6 +389,8 @@ func updateOptionMap(key string, value string) (err error) {
operation_setting.AutomaticDisableKeywordsFromString(value) operation_setting.AutomaticDisableKeywordsFromString(value)
case "StreamCacheQueueLength": case "StreamCacheQueueLength":
setting.StreamCacheQueueLength, _ = strconv.Atoi(value) setting.StreamCacheQueueLength, _ = strconv.Atoi(value)
case "PayMethods":
err = setting.UpdatePayMethodsByJsonString(value)
} }
return err return err
} }

View File

@@ -2,7 +2,7 @@ package model
import ( import (
"one-api/common" "one-api/common"
"one-api/setting/operation_setting" "one-api/setting/ratio_setting"
"sync" "sync"
"time" "time"
) )
@@ -65,14 +65,14 @@ func updatePricing() {
ModelName: model, ModelName: model,
EnableGroup: groups, EnableGroup: groups,
} }
modelPrice, findPrice := operation_setting.GetModelPrice(model, false) modelPrice, findPrice := ratio_setting.GetModelPrice(model, false)
if findPrice { if findPrice {
pricing.ModelPrice = modelPrice pricing.ModelPrice = modelPrice
pricing.QuotaType = 1 pricing.QuotaType = 1
} else { } else {
modelRatio, _ := operation_setting.GetModelRatio(model) modelRatio, _ := ratio_setting.GetModelRatio(model)
pricing.ModelRatio = modelRatio pricing.ModelRatio = modelRatio
pricing.CompletionRatio = operation_setting.GetCompletionRatio(model) pricing.CompletionRatio = ratio_setting.GetCompletionRatio(model)
pricing.QuotaType = 0 pricing.QuotaType = 0
} }
pricingMap = append(pricingMap, pricing) pricingMap = append(pricingMap, pricing)

View File

@@ -2,11 +2,12 @@ package model
import ( import (
"errors" "errors"
"github.com/bytedance/gopkg/util/gopool"
"gorm.io/gorm"
"one-api/common" "one-api/common"
"sync" "sync"
"time" "time"
"github.com/bytedance/gopkg/util/gopool"
"gorm.io/gorm"
) )
const ( const (
@@ -48,6 +49,22 @@ func addNewRecord(type_ int, id int, value int) {
} }
func batchUpdate() { func batchUpdate() {
// check if there's any data to update
hasData := false
for i := 0; i < BatchUpdateTypeCount; i++ {
batchUpdateLocks[i].Lock()
if len(batchUpdateStores[i]) > 0 {
hasData = true
batchUpdateLocks[i].Unlock()
break
}
batchUpdateLocks[i].Unlock()
}
if !hasData {
return
}
common.SysLog("batch update started") common.SysLog("batch update started")
for i := 0; i < BatchUpdateTypeCount; i++ { for i := 0; i < BatchUpdateTypeCount; i++ {
batchUpdateLocks[i].Lock() batchUpdateLocks[i].Lock()

View File

@@ -140,6 +140,7 @@ type GeminiChatGenerationConfig struct {
Seed int64 `json:"seed,omitempty"` Seed int64 `json:"seed,omitempty"`
ResponseModalities []string `json:"responseModalities,omitempty"` ResponseModalities []string `json:"responseModalities,omitempty"`
ThinkingConfig *GeminiThinkingConfig `json:"thinkingConfig,omitempty"` ThinkingConfig *GeminiThinkingConfig `json:"thinkingConfig,omitempty"`
SpeechConfig json.RawMessage `json:"speechConfig,omitempty"` // RawMessage to allow flexible speech config
} }
type GeminiChatCandidate struct { type GeminiChatCandidate struct {

View File

@@ -373,7 +373,9 @@ func CovertGemini2OpenAI(textRequest dto.GeneralOpenAIRequest, info *relaycommon
if content.Role == "assistant" { if content.Role == "assistant" {
content.Role = "model" content.Role = "model"
} }
geminiRequest.Contents = append(geminiRequest.Contents, content) if len(content.Parts) > 0 {
geminiRequest.Contents = append(geminiRequest.Contents, content)
}
} }
if len(system_content) > 0 { if len(system_content) > 0 {

View File

@@ -123,14 +123,23 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
if v, ok := claudeModelMap[info.UpstreamModelName]; ok { if v, ok := claudeModelMap[info.UpstreamModelName]; ok {
model = v model = v
} }
return fmt.Sprintf( if region == "global" {
"https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/anthropic/models/%s:%s", return fmt.Sprintf(
region, "https://aiplatform.googleapis.com/v1/projects/%s/locations/global/publishers/anthropic/models/%s:%s",
adc.ProjectID, adc.ProjectID,
region, model,
model, suffix,
suffix, ), nil
), nil } else {
return fmt.Sprintf(
"https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/anthropic/models/%s:%s",
region,
adc.ProjectID,
region,
model,
suffix,
), nil
}
} else if a.RequestMode == RequestModeLlama { } else if a.RequestMode == RequestModeLlama {
return fmt.Sprintf( return fmt.Sprintf(
"https://%s-aiplatform.googleapis.com/v1beta1/projects/%s/locations/%s/endpoints/openapi/chat/completions", "https://%s-aiplatform.googleapis.com/v1beta1/projects/%s/locations/%s/endpoints/openapi/chat/completions",

View File

@@ -5,8 +5,7 @@ import (
"one-api/common" "one-api/common"
constant2 "one-api/constant" constant2 "one-api/constant"
relaycommon "one-api/relay/common" relaycommon "one-api/relay/common"
"one-api/setting" "one-api/setting/ratio_setting"
"one-api/setting/operation_setting"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@@ -36,7 +35,7 @@ func (p PriceData) ToSetting() string {
func HandleGroupRatio(ctx *gin.Context, relayInfo *relaycommon.RelayInfo) GroupRatioInfo { func HandleGroupRatio(ctx *gin.Context, relayInfo *relaycommon.RelayInfo) GroupRatioInfo {
groupRatioInfo := GroupRatioInfo{ groupRatioInfo := GroupRatioInfo{
GroupRatio: 1.0, // default ratio GroupRatio: 1.0, // default ratio
GroupSpecialRatio: 1.0, // default user group ratio GroupSpecialRatio: -1,
} }
// check auto group // check auto group
@@ -49,21 +48,21 @@ func HandleGroupRatio(ctx *gin.Context, relayInfo *relaycommon.RelayInfo) GroupR
} }
// check user group special ratio // check user group special ratio
userGroupRatio, ok := setting.GetGroupGroupRatio(relayInfo.UserGroup, relayInfo.Group) userGroupRatio, ok := ratio_setting.GetGroupGroupRatio(relayInfo.UserGroup, relayInfo.Group)
if ok { if ok {
// user group special ratio // user group special ratio
groupRatioInfo.GroupSpecialRatio = userGroupRatio groupRatioInfo.GroupSpecialRatio = userGroupRatio
groupRatioInfo.GroupRatio = userGroupRatio groupRatioInfo.GroupRatio = userGroupRatio
} else { } else {
// normal group ratio // normal group ratio
groupRatioInfo.GroupRatio = setting.GetGroupRatio(relayInfo.Group) groupRatioInfo.GroupRatio = ratio_setting.GetGroupRatio(relayInfo.Group)
} }
return groupRatioInfo return groupRatioInfo
} }
func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens int, maxTokens int) (PriceData, error) { func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens int, maxTokens int) (PriceData, error) {
modelPrice, usePrice := operation_setting.GetModelPrice(info.OriginModelName, false) modelPrice, usePrice := ratio_setting.GetModelPrice(info.OriginModelName, false)
groupRatioInfo := HandleGroupRatio(c, info) groupRatioInfo := HandleGroupRatio(c, info)
@@ -79,7 +78,7 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
preConsumedTokens = promptTokens + maxTokens preConsumedTokens = promptTokens + maxTokens
} }
var success bool var success bool
modelRatio, success = operation_setting.GetModelRatio(info.OriginModelName) modelRatio, success = ratio_setting.GetModelRatio(info.OriginModelName)
if !success { if !success {
acceptUnsetRatio := false acceptUnsetRatio := false
if accept, ok := info.UserSetting[constant2.UserAcceptUnsetRatioModel]; ok { if accept, ok := info.UserSetting[constant2.UserAcceptUnsetRatioModel]; ok {
@@ -92,10 +91,10 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置请联系管理员设置或开始自用模式Model %s ratio or price not set, please set or start self-use mode", info.OriginModelName, info.OriginModelName) return PriceData{}, fmt.Errorf("模型 %s 倍率或价格未配置请联系管理员设置或开始自用模式Model %s ratio or price not set, please set or start self-use mode", info.OriginModelName, info.OriginModelName)
} }
} }
completionRatio = operation_setting.GetCompletionRatio(info.OriginModelName) completionRatio = ratio_setting.GetCompletionRatio(info.OriginModelName)
cacheRatio, _ = operation_setting.GetCacheRatio(info.OriginModelName) cacheRatio, _ = ratio_setting.GetCacheRatio(info.OriginModelName)
cacheCreationRatio, _ = operation_setting.GetCreateCacheRatio(info.OriginModelName) cacheCreationRatio, _ = ratio_setting.GetCreateCacheRatio(info.OriginModelName)
imageRatio, _ = operation_setting.GetImageRatio(info.OriginModelName) imageRatio, _ = ratio_setting.GetImageRatio(info.OriginModelName)
ratio := modelRatio * groupRatioInfo.GroupRatio ratio := modelRatio * groupRatioInfo.GroupRatio
preConsumedQuota = int(float64(preConsumedTokens) * ratio) preConsumedQuota = int(float64(preConsumedTokens) * ratio)
} else { } else {
@@ -122,11 +121,11 @@ func ModelPriceHelper(c *gin.Context, info *relaycommon.RelayInfo, promptTokens
} }
func ContainPriceOrRatio(modelName string) bool { func ContainPriceOrRatio(modelName string) bool {
_, ok := operation_setting.GetModelPrice(modelName, false) _, ok := ratio_setting.GetModelPrice(modelName, false)
if ok { if ok {
return true return true
} }
_, ok = operation_setting.GetModelRatio(modelName) _, ok = ratio_setting.GetModelRatio(modelName)
if ok { if ok {
return true return true
} }

View File

@@ -155,6 +155,10 @@ func GeminiHelper(c *gin.Context) (openaiErr *dto.OpenAIErrorWithStatusCode) {
return service.OpenAIErrorWrapperLocal(err, "marshal_text_request_failed", http.StatusInternalServerError) return service.OpenAIErrorWrapperLocal(err, "marshal_text_request_failed", http.StatusInternalServerError)
} }
if common.DebugEnabled {
println("Gemini request body: %s", string(requestBody))
}
resp, err := adaptor.DoRequest(c, relayInfo, bytes.NewReader(requestBody)) resp, err := adaptor.DoRequest(c, relayInfo, bytes.NewReader(requestBody))
if err != nil { if err != nil {
common.LogError(c, "Do gemini request failed: "+err.Error()) common.LogError(c, "Do gemini request failed: "+err.Error())

View File

@@ -15,7 +15,7 @@ import (
relayconstant "one-api/relay/constant" relayconstant "one-api/relay/constant"
"one-api/service" "one-api/service"
"one-api/setting" "one-api/setting"
"one-api/setting/operation_setting" "one-api/setting/ratio_setting"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@@ -174,17 +174,17 @@ func RelaySwapFace(c *gin.Context) *dto.MidjourneyResponse {
return service.MidjourneyErrorWrapper(constant.MjRequestError, "sour_base64_and_target_base64_is_required") return service.MidjourneyErrorWrapper(constant.MjRequestError, "sour_base64_and_target_base64_is_required")
} }
modelName := service.CoverActionToModelName(constant.MjActionSwapFace) modelName := service.CoverActionToModelName(constant.MjActionSwapFace)
modelPrice, success := operation_setting.GetModelPrice(modelName, true) modelPrice, success := ratio_setting.GetModelPrice(modelName, true)
// 如果没有配置价格,则使用默认价格 // 如果没有配置价格,则使用默认价格
if !success { if !success {
defaultPrice, ok := operation_setting.GetDefaultModelRatioMap()[modelName] defaultPrice, ok := ratio_setting.GetDefaultModelRatioMap()[modelName]
if !ok { if !ok {
modelPrice = 0.1 modelPrice = 0.1
} else { } else {
modelPrice = defaultPrice modelPrice = defaultPrice
} }
} }
groupRatio := setting.GetGroupRatio(group) groupRatio := ratio_setting.GetGroupRatio(group)
ratio := modelPrice * groupRatio ratio := modelPrice * groupRatio
userQuota, err := model.GetUserQuota(userId, false) userQuota, err := model.GetUserQuota(userId, false)
if err != nil { if err != nil {
@@ -480,17 +480,17 @@ func RelayMidjourneySubmit(c *gin.Context, relayMode int) *dto.MidjourneyRespons
fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL) fullRequestURL := fmt.Sprintf("%s%s", baseURL, requestURL)
modelName := service.CoverActionToModelName(midjRequest.Action) modelName := service.CoverActionToModelName(midjRequest.Action)
modelPrice, success := operation_setting.GetModelPrice(modelName, true) modelPrice, success := ratio_setting.GetModelPrice(modelName, true)
// 如果没有配置价格,则使用默认价格 // 如果没有配置价格,则使用默认价格
if !success { if !success {
defaultPrice, ok := operation_setting.GetDefaultModelRatioMap()[modelName] defaultPrice, ok := ratio_setting.GetDefaultModelRatioMap()[modelName]
if !ok { if !ok {
modelPrice = 0.1 modelPrice = 0.1
} else { } else {
modelPrice = defaultPrice modelPrice = defaultPrice
} }
} }
groupRatio := setting.GetGroupRatio(group) groupRatio := ratio_setting.GetGroupRatio(group)
ratio := modelPrice * groupRatio ratio := modelPrice * groupRatio
userQuota, err := model.GetUserQuota(userId, false) userQuota, err := model.GetUserQuota(userId, false)
if err != nil { if err != nil {

View File

@@ -15,8 +15,7 @@ import (
relaycommon "one-api/relay/common" relaycommon "one-api/relay/common"
relayconstant "one-api/relay/constant" relayconstant "one-api/relay/constant"
"one-api/service" "one-api/service"
"one-api/setting" "one-api/setting/ratio_setting"
"one-api/setting/operation_setting"
) )
/* /*
@@ -38,9 +37,9 @@ func RelayTaskSubmit(c *gin.Context, relayMode int) (taskErr *dto.TaskError) {
} }
modelName := service.CoverTaskActionToModelName(platform, relayInfo.Action) modelName := service.CoverTaskActionToModelName(platform, relayInfo.Action)
modelPrice, success := operation_setting.GetModelPrice(modelName, true) modelPrice, success := ratio_setting.GetModelPrice(modelName, true)
if !success { if !success {
defaultPrice, ok := operation_setting.GetDefaultModelRatioMap()[modelName] defaultPrice, ok := ratio_setting.GetDefaultModelRatioMap()[modelName]
if !ok { if !ok {
modelPrice = 0.1 modelPrice = 0.1
} else { } else {
@@ -49,7 +48,7 @@ func RelayTaskSubmit(c *gin.Context, relayMode int) (taskErr *dto.TaskError) {
} }
// 预扣 // 预扣
groupRatio := setting.GetGroupRatio(relayInfo.Group) groupRatio := ratio_setting.GetGroupRatio(relayInfo.Group)
ratio := modelPrice * groupRatio ratio := modelPrice * groupRatio
userQuota, err := model.GetUserQuota(relayInfo.UserId, false) userQuota, err := model.GetUserQuota(relayInfo.UserId, false)
if err != nil { if err != nil {

View File

@@ -11,7 +11,7 @@ import (
relaycommon "one-api/relay/common" relaycommon "one-api/relay/common"
"one-api/relay/helper" "one-api/relay/helper"
"one-api/setting" "one-api/setting"
"one-api/setting/operation_setting" "one-api/setting/ratio_setting"
"strings" "strings"
"time" "time"
@@ -46,9 +46,9 @@ func calculateAudioQuota(info QuotaInfo) int {
return int(quota.IntPart()) return int(quota.IntPart())
} }
completionRatio := decimal.NewFromFloat(operation_setting.GetCompletionRatio(info.ModelName)) completionRatio := decimal.NewFromFloat(ratio_setting.GetCompletionRatio(info.ModelName))
audioRatio := decimal.NewFromFloat(operation_setting.GetAudioRatio(info.ModelName)) audioRatio := decimal.NewFromFloat(ratio_setting.GetAudioRatio(info.ModelName))
audioCompletionRatio := decimal.NewFromFloat(operation_setting.GetAudioCompletionRatio(info.ModelName)) audioCompletionRatio := decimal.NewFromFloat(ratio_setting.GetAudioCompletionRatio(info.ModelName))
groupRatio := decimal.NewFromFloat(info.GroupRatio) groupRatio := decimal.NewFromFloat(info.GroupRatio)
modelRatio := decimal.NewFromFloat(info.ModelRatio) modelRatio := decimal.NewFromFloat(info.ModelRatio)
@@ -94,18 +94,18 @@ func PreWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, usag
textOutTokens := usage.OutputTokenDetails.TextTokens textOutTokens := usage.OutputTokenDetails.TextTokens
audioInputTokens := usage.InputTokenDetails.AudioTokens audioInputTokens := usage.InputTokenDetails.AudioTokens
audioOutTokens := usage.OutputTokenDetails.AudioTokens audioOutTokens := usage.OutputTokenDetails.AudioTokens
groupRatio := setting.GetGroupRatio(relayInfo.Group) groupRatio := ratio_setting.GetGroupRatio(relayInfo.Group)
modelRatio, _ := operation_setting.GetModelRatio(modelName) modelRatio, _ := ratio_setting.GetModelRatio(modelName)
autoGroup, exists := ctx.Get("auto_group") autoGroup, exists := ctx.Get("auto_group")
if exists { if exists {
groupRatio = setting.GetGroupRatio(autoGroup.(string)) groupRatio = ratio_setting.GetGroupRatio(autoGroup.(string))
log.Printf("final group ratio: %f", groupRatio) log.Printf("final group ratio: %f", groupRatio)
relayInfo.Group = autoGroup.(string) relayInfo.Group = autoGroup.(string)
} }
actualGroupRatio := groupRatio actualGroupRatio := groupRatio
userGroupRatio, ok := setting.GetGroupGroupRatio(relayInfo.UserGroup, relayInfo.Group) userGroupRatio, ok := ratio_setting.GetGroupGroupRatio(relayInfo.UserGroup, relayInfo.Group)
if ok { if ok {
actualGroupRatio = userGroupRatio actualGroupRatio = userGroupRatio
} }
@@ -154,9 +154,9 @@ func PostWssConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo, mod
audioOutTokens := usage.OutputTokenDetails.AudioTokens audioOutTokens := usage.OutputTokenDetails.AudioTokens
tokenName := ctx.GetString("token_name") tokenName := ctx.GetString("token_name")
completionRatio := decimal.NewFromFloat(operation_setting.GetCompletionRatio(modelName)) completionRatio := decimal.NewFromFloat(ratio_setting.GetCompletionRatio(modelName))
audioRatio := decimal.NewFromFloat(operation_setting.GetAudioRatio(relayInfo.OriginModelName)) audioRatio := decimal.NewFromFloat(ratio_setting.GetAudioRatio(relayInfo.OriginModelName))
audioCompletionRatio := decimal.NewFromFloat(operation_setting.GetAudioCompletionRatio(modelName)) audioCompletionRatio := decimal.NewFromFloat(ratio_setting.GetAudioCompletionRatio(modelName))
modelRatio := priceData.ModelRatio modelRatio := priceData.ModelRatio
groupRatio := priceData.GroupRatioInfo.GroupRatio groupRatio := priceData.GroupRatioInfo.GroupRatio
@@ -289,9 +289,9 @@ func PostAudioConsumeQuota(ctx *gin.Context, relayInfo *relaycommon.RelayInfo,
audioOutTokens := usage.CompletionTokenDetails.AudioTokens audioOutTokens := usage.CompletionTokenDetails.AudioTokens
tokenName := ctx.GetString("token_name") tokenName := ctx.GetString("token_name")
completionRatio := decimal.NewFromFloat(operation_setting.GetCompletionRatio(relayInfo.OriginModelName)) completionRatio := decimal.NewFromFloat(ratio_setting.GetCompletionRatio(relayInfo.OriginModelName))
audioRatio := decimal.NewFromFloat(operation_setting.GetAudioRatio(relayInfo.OriginModelName)) audioRatio := decimal.NewFromFloat(ratio_setting.GetAudioRatio(relayInfo.OriginModelName))
audioCompletionRatio := decimal.NewFromFloat(operation_setting.GetAudioCompletionRatio(relayInfo.OriginModelName)) audioCompletionRatio := decimal.NewFromFloat(ratio_setting.GetAudioCompletionRatio(relayInfo.OriginModelName))
modelRatio := priceData.ModelRatio modelRatio := priceData.ModelRatio
groupRatio := priceData.GroupRatioInfo.GroupRatio groupRatio := priceData.GroupRatioInfo.GroupRatio

View File

@@ -1,8 +1,45 @@
package setting package setting
import "encoding/json"
var PayAddress = "" var PayAddress = ""
var CustomCallbackAddress = "" var CustomCallbackAddress = ""
var EpayId = "" var EpayId = ""
var EpayKey = "" var EpayKey = ""
var Price = 7.3 var Price = 7.3
var MinTopUp = 1 var MinTopUp = 1
var PayMethods = []map[string]string{
{
"name": "支付宝",
"color": "rgba(var(--semi-blue-5), 1)",
"type": "zfb",
},
{
"name": "微信",
"color": "rgba(var(--semi-green-5), 1)",
"type": "wx",
},
}
func UpdatePayMethodsByJsonString(jsonString string) error {
PayMethods = make([]map[string]string, 0)
return json.Unmarshal([]byte(jsonString), &PayMethods)
}
func PayMethods2JsonString() string {
jsonBytes, err := json.Marshal(PayMethods)
if err != nil {
return "[]"
}
return string(jsonBytes)
}
func ContainsPayMethod(method string) bool {
for _, payMethod := range PayMethods {
if payMethod["type"] == method {
return true
}
}
return false
}

View File

@@ -1,4 +1,4 @@
package operation_setting package ratio_setting
import ( import (
"encoding/json" "encoding/json"

View File

@@ -1,4 +1,4 @@
package setting package ratio_setting
import ( import (
"encoding/json" "encoding/json"

View File

@@ -1,8 +1,9 @@
package operation_setting package ratio_setting
import ( import (
"encoding/json" "encoding/json"
"one-api/common" "one-api/common"
"one-api/setting/operation_setting"
"strings" "strings"
"sync" "sync"
) )
@@ -369,7 +370,7 @@ func GetModelRatio(name string) (float64, bool) {
} }
ratio, ok := modelRatioMap[name] ratio, ok := modelRatioMap[name]
if !ok { if !ok {
return 37.5, SelfUseModeEnabled return 37.5, operation_setting.SelfUseModeEnabled
} }
return ratio, true return ratio, true
} }

View File

@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { Card, Spin, Tabs } from '@douyinfe/semi-ui'; import { Card, Spin } from '@douyinfe/semi-ui';
import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral.js'; import SettingsGeneral from '../../pages/Setting/Operation/SettingsGeneral.js';
import SettingsDrawing from '../../pages/Setting/Operation/SettingsDrawing.js'; import SettingsDrawing from '../../pages/Setting/Operation/SettingsDrawing.js';
import SettingsSensitiveWords from '../../pages/Setting/Operation/SettingsSensitiveWords.js'; import SettingsSensitiveWords from '../../pages/Setting/Operation/SettingsSensitiveWords.js';
@@ -7,63 +7,58 @@ import SettingsLog from '../../pages/Setting/Operation/SettingsLog.js';
import SettingsDataDashboard from '../../pages/Setting/Operation/SettingsDataDashboard.js'; import SettingsDataDashboard from '../../pages/Setting/Operation/SettingsDataDashboard.js';
import SettingsMonitoring from '../../pages/Setting/Operation/SettingsMonitoring.js'; import SettingsMonitoring from '../../pages/Setting/Operation/SettingsMonitoring.js';
import SettingsCreditLimit from '../../pages/Setting/Operation/SettingsCreditLimit.js'; import SettingsCreditLimit from '../../pages/Setting/Operation/SettingsCreditLimit.js';
import ModelSettingsVisualEditor from '../../pages/Setting/Operation/ModelSettingsVisualEditor.js';
import GroupRatioSettings from '../../pages/Setting/Operation/GroupRatioSettings.js';
import ModelRatioSettings from '../../pages/Setting/Operation/ModelRatioSettings.js';
import { API, showError, showSuccess } from '../../helpers';
import SettingsChats from '../../pages/Setting/Operation/SettingsChats.js'; import SettingsChats from '../../pages/Setting/Operation/SettingsChats.js';
import { useTranslation } from 'react-i18next'; import { API, showError } from '../../helpers';
import ModelRatioNotSetEditor from '../../pages/Setting/Operation/ModelRationNotSetEditor.js';
const OperationSetting = () => { const OperationSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({ let [inputs, setInputs] = useState({
/* 额度相关 */
QuotaForNewUser: 0, QuotaForNewUser: 0,
PreConsumedQuota: 0,
QuotaForInviter: 0, QuotaForInviter: 0,
QuotaForInvitee: 0, QuotaForInvitee: 0,
QuotaRemindThreshold: 0,
PreConsumedQuota: 0, /* 通用设置 */
StreamCacheQueueLength: 0,
ModelRatio: '',
CacheRatio: '',
CompletionRatio: '',
ModelPrice: '',
GroupRatio: '',
GroupGroupRatio: '',
AutoGroups: '',
DefaultUseAutoGroup: false,
UserUsableGroups: '',
TopUpLink: '', TopUpLink: '',
'general_setting.docs_link': '', 'general_setting.docs_link': '',
// ChatLink2: '', // 添加的新状态变量
QuotaPerUnit: 0, QuotaPerUnit: 0,
AutomaticDisableChannelEnabled: false, RetryTimes: 0,
AutomaticEnableChannelEnabled: false,
ChannelDisableThreshold: 0,
LogConsumeEnabled: false,
DisplayInCurrencyEnabled: false, DisplayInCurrencyEnabled: false,
DisplayTokenStatEnabled: false, DisplayTokenStatEnabled: false,
CheckSensitiveEnabled: false, DefaultCollapseSidebar: false,
CheckSensitiveOnPromptEnabled: false, DemoSiteEnabled: false,
CheckSensitiveOnCompletionEnabled: '', SelfUseModeEnabled: false,
StopOnSensitiveEnabled: '',
SensitiveWords: '', /* 绘图设置 */
DrawingEnabled: false,
MjNotifyEnabled: false, MjNotifyEnabled: false,
MjAccountFilterEnabled: false, MjAccountFilterEnabled: false,
MjModeClearEnabled: false,
MjForwardUrlEnabled: false, MjForwardUrlEnabled: false,
MjModeClearEnabled: false,
MjActionCheckSuccessEnabled: false, MjActionCheckSuccessEnabled: false,
DrawingEnabled: false,
/* 敏感词设置 */
CheckSensitiveEnabled: false,
CheckSensitiveOnPromptEnabled: false,
SensitiveWords: '',
/* 日志设置 */
LogConsumeEnabled: false,
/* 数据看板 */
DataExportEnabled: false, DataExportEnabled: false,
DataExportDefaultTime: 'hour', DataExportDefaultTime: 'hour',
DataExportInterval: 5, DataExportInterval: 5,
DefaultCollapseSidebar: false, // 默认折叠侧边栏
RetryTimes: 0, /* 监控设置 */
Chats: '[]', ChannelDisableThreshold: 0,
DemoSiteEnabled: false, QuotaRemindThreshold: 0,
SelfUseModeEnabled: false, AutomaticDisableChannelEnabled: false,
AutomaticEnableChannelEnabled: false,
AutomaticDisableKeywords: '', AutomaticDisableKeywords: '',
/* 聊天设置 */
Chats: '[]',
}); });
let [loading, setLoading] = useState(false); let [loading, setLoading] = useState(false);
@@ -74,22 +69,9 @@ const OperationSetting = () => {
if (success) { if (success) {
let newInputs = {}; let newInputs = {};
data.forEach((item) => { data.forEach((item) => {
if (
item.key === 'ModelRatio' ||
item.key === 'GroupRatio' ||
item.key === 'GroupGroupRatio' ||
item.key === 'AutoGroups' ||
item.key === 'UserUsableGroups' ||
item.key === 'CompletionRatio' ||
item.key === 'ModelPrice' ||
item.key === 'CacheRatio'
) {
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
}
if ( if (
item.key.endsWith('Enabled') || item.key.endsWith('Enabled') ||
['DefaultCollapseSidebar'].includes(item.key) || ['DefaultCollapseSidebar'].includes(item.key)
['DefaultUseAutoGroup'].includes(item.key)
) { ) {
newInputs[item.key] = item.value === 'true' ? true : false; newInputs[item.key] = item.value === 'true' ? true : false;
} else { } else {
@@ -153,24 +135,6 @@ const OperationSetting = () => {
<Card style={{ marginTop: '10px' }}> <Card style={{ marginTop: '10px' }}>
<SettingsChats options={inputs} refresh={onRefresh} /> <SettingsChats options={inputs} refresh={onRefresh} />
</Card> </Card>
{/* 分组倍率设置 */}
<Card style={{ marginTop: '10px' }}>
<GroupRatioSettings options={inputs} refresh={onRefresh} />
</Card>
{/* 合并模型倍率设置和可视化倍率设置 */}
<Card style={{ marginTop: '10px' }}>
<Tabs type='line'>
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
<ModelRatioSettings options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('可视化倍率设置')} itemKey='visual'>
<ModelSettingsVisualEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
<ModelRatioNotSetEditor options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
</Tabs>
</Card>
</Spin> </Spin>
</> </>
); );

View File

@@ -0,0 +1,109 @@
import React, { useEffect, useState } from 'react';
import { Card, Spin, Tabs } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import GroupRatioSettings from '../../pages/Setting/Ratio/GroupRatioSettings.js';
import ModelRatioSettings from '../../pages/Setting/Ratio/ModelRatioSettings.js';
import ModelSettingsVisualEditor from '../../pages/Setting/Ratio/ModelSettingsVisualEditor.js';
import ModelRatioNotSetEditor from '../../pages/Setting/Ratio/ModelRationNotSetEditor.js';
import { API, showError } from '../../helpers';
const RatioSetting = () => {
const { t } = useTranslation();
let [inputs, setInputs] = useState({
ModelPrice: '',
ModelRatio: '',
CacheRatio: '',
CompletionRatio: '',
GroupRatio: '',
GroupGroupRatio: '',
AutoGroups: '',
DefaultUseAutoGroup: false,
UserUsableGroups: '',
});
const [loading, setLoading] = useState(false);
const getOptions = async () => {
const res = await API.get('/api/option/');
const { success, message, data } = res.data;
if (success) {
let newInputs = {};
data.forEach((item) => {
if (
item.key === 'ModelRatio' ||
item.key === 'GroupRatio' ||
item.key === 'GroupGroupRatio' ||
item.key === 'AutoGroups' ||
item.key === 'UserUsableGroups' ||
item.key === 'CompletionRatio' ||
item.key === 'ModelPrice' ||
item.key === 'CacheRatio'
) {
try {
item.value = JSON.stringify(JSON.parse(item.value), null, 2);
} catch (e) {
// 如果后端返回的不是合法 JSON直接展示
}
}
if (['DefaultUseAutoGroup'].includes(item.key)) {
newInputs[item.key] = item.value === 'true' ? true : false;
} else {
newInputs[item.key] = item.value;
}
});
setInputs(newInputs);
} else {
showError(message);
}
};
const onRefresh = async () => {
try {
setLoading(true);
await getOptions();
} catch (error) {
showError('刷新失败');
} finally {
setLoading(false);
}
};
useEffect(() => {
onRefresh();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<Spin spinning={loading} size='large'>
{/* 分组倍率设置 */}
<Card style={{ marginTop: '10px' }}>
<GroupRatioSettings options={inputs} refresh={onRefresh} />
</Card>
{/* 模型倍率设置以及可视化编辑器 */}
<Card style={{ marginTop: '10px' }}>
<Tabs type='line'>
<Tabs.TabPane tab={t('模型倍率设置')} itemKey='model'>
<ModelRatioSettings options={inputs} refresh={onRefresh} />
</Tabs.TabPane>
<Tabs.TabPane tab={t('可视化倍率设置')} itemKey='visual'>
<ModelSettingsVisualEditor
options={inputs}
refresh={onRefresh}
/>
</Tabs.TabPane>
<Tabs.TabPane tab={t('未设置倍率模型')} itemKey='unset_models'>
<ModelRatioNotSetEditor
options={inputs}
refresh={onRefresh}
/>
</Tabs.TabPane>
</Tabs>
</Card>
</Spin>
);
};
export default RatioSetting;

View File

@@ -17,7 +17,7 @@ import {
removeTrailingSlash, removeTrailingSlash,
showError, showError,
showSuccess, showSuccess,
verifyJSON verifyJSON,
} from '../../helpers'; } from '../../helpers';
import axios from 'axios'; import axios from 'axios';
@@ -73,6 +73,7 @@ const SystemSetting = () => {
LinuxDOOAuthEnabled: '', LinuxDOOAuthEnabled: '',
LinuxDOClientId: '', LinuxDOClientId: '',
LinuxDOClientSecret: '', LinuxDOClientSecret: '',
PayMethods: '',
}); });
const [originInputs, setOriginInputs] = useState({}); const [originInputs, setOriginInputs] = useState({});
@@ -230,6 +231,12 @@ const SystemSetting = () => {
return; return;
} }
} }
if (originInputs['PayMethods'] !== inputs.PayMethods) {
if (!verifyJSON(inputs.PayMethods)) {
showError('充值方式设置不是合法的 JSON 字符串');
return;
}
}
const options = [ const options = [
{ key: 'PayAddress', value: removeTrailingSlash(inputs.PayAddress) }, { key: 'PayAddress', value: removeTrailingSlash(inputs.PayAddress) },
@@ -256,6 +263,9 @@ const SystemSetting = () => {
if (originInputs['TopupGroupRatio'] !== inputs.TopupGroupRatio) { if (originInputs['TopupGroupRatio'] !== inputs.TopupGroupRatio) {
options.push({ key: 'TopupGroupRatio', value: inputs.TopupGroupRatio }); options.push({ key: 'TopupGroupRatio', value: inputs.TopupGroupRatio });
} }
if (originInputs['PayMethods'] !== inputs.PayMethods) {
options.push({ key: 'PayMethods', value: inputs.PayMethods });
}
await updateOptions(options); await updateOptions(options);
}; };
@@ -658,6 +668,12 @@ const SystemSetting = () => {
placeholder='为一个 JSON 文本,键为组名称,值为倍率' placeholder='为一个 JSON 文本,键为组名称,值为倍率'
autosize autosize
/> />
<Form.TextArea
field='PayMethods'
label='充值方式设置'
placeholder='为一个 JSON 文本'
autosize
/>
<Button onClick={submitPayAddress}>更新支付设置</Button> <Button onClick={submitPayAddress}>更新支付设置</Button>
</Form.Section> </Form.Section>
</Card> </Card>

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState, useMemo, useRef } from 'react';
import { import {
API, API,
showError, showError,
@@ -16,11 +16,6 @@ import {
XCircle, XCircle,
AlertCircle, AlertCircle,
HelpCircle, HelpCircle,
TestTube,
Zap,
Timer,
Clock,
AlertTriangle,
Coins, Coins,
Tags Tags
} from 'lucide-react'; } from 'lucide-react';
@@ -43,7 +38,9 @@ import {
Typography, Typography,
Checkbox, Checkbox,
Card, Card,
Form Form,
Tabs,
TabPane
} from '@douyinfe/semi-ui'; } from '@douyinfe/semi-ui';
import { import {
IllustrationNoResult, IllustrationNoResult,
@@ -141,31 +138,31 @@ const ChannelsTable = () => {
time = time.toFixed(2) + t(' 秒'); time = time.toFixed(2) + t(' 秒');
if (responseTime === 0) { if (responseTime === 0) {
return ( return (
<Tag size='large' color='grey' shape='circle' prefixIcon={<TestTube size={14} />}> <Tag size='large' color='grey' shape='circle'>
{t('未测试')} {t('未测试')}
</Tag> </Tag>
); );
} else if (responseTime <= 1000) { } else if (responseTime <= 1000) {
return ( return (
<Tag size='large' color='green' shape='circle' prefixIcon={<Zap size={14} />}> <Tag size='large' color='green' shape='circle'>
{time} {time}
</Tag> </Tag>
); );
} else if (responseTime <= 3000) { } else if (responseTime <= 3000) {
return ( return (
<Tag size='large' color='lime' shape='circle' prefixIcon={<Timer size={14} />}> <Tag size='large' color='lime' shape='circle'>
{time} {time}
</Tag> </Tag>
); );
} else if (responseTime <= 5000) { } else if (responseTime <= 5000) {
return ( return (
<Tag size='large' color='yellow' shape='circle' prefixIcon={<Clock size={14} />}> <Tag size='large' color='yellow' shape='circle'>
{time} {time}
</Tag> </Tag>
); );
} else { } else {
return ( return (
<Tag size='large' color='red' shape='circle' prefixIcon={<AlertTriangle size={14} />}> <Tag size='large' color='red' shape='circle'>
{time} {time}
</Tag> </Tag>
); );
@@ -682,11 +679,10 @@ const ChannelsTable = () => {
const [isBatchTesting, setIsBatchTesting] = useState(false); const [isBatchTesting, setIsBatchTesting] = useState(false);
const [testQueue, setTestQueue] = useState([]); const [testQueue, setTestQueue] = useState([]);
const [isProcessingQueue, setIsProcessingQueue] = useState(false); const [isProcessingQueue, setIsProcessingQueue] = useState(false);
const [activeTypeKey, setActiveTypeKey] = useState('all');
// Form API 引用 const [typeCounts, setTypeCounts] = useState({});
const requestCounter = useRef(0);
const [formApi, setFormApi] = useState(null); const [formApi, setFormApi] = useState(null);
// Form 初始值
const formInitValues = { const formInitValues = {
searchKeyword: '', searchKeyword: '',
searchGroup: '', searchGroup: '',
@@ -868,17 +864,23 @@ const ChannelsTable = () => {
setChannels(channelDates); setChannels(channelDates);
}; };
const loadChannels = async (page, pageSize, idSort, enableTagMode) => { const loadChannels = async (page, pageSize, idSort, enableTagMode, typeKey = activeTypeKey) => {
const reqId = ++requestCounter.current; // 记录当前请求序号
setLoading(true); setLoading(true);
const typeParam = (!enableTagMode && typeKey !== 'all') ? `&type=${typeKey}` : '';
const res = await API.get( const res = await API.get(
`/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}`, `/api/channel/?p=${page}&page_size=${pageSize}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}`,
); );
if (res === undefined) { if (res === undefined || reqId !== requestCounter.current) {
return; return;
} }
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
const { items, total } = data; const { items, total, type_counts } = data;
if (type_counts) {
const sumAll = Object.values(type_counts).reduce((acc, v) => acc + v, 0);
setTypeCounts({ ...type_counts, all: sumAll });
}
setChannelFormat(items, enableTagMode); setChannelFormat(items, enableTagMode);
setChannelCount(total); setChannelCount(total);
} else { } else {
@@ -1044,12 +1046,16 @@ const ChannelsTable = () => {
return; return;
} }
const typeParam = (!enableTagMode && activeTypeKey !== 'all') ? `&type=${activeTypeKey}` : '';
const res = await API.get( const res = await API.get(
`/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${idSort}&tag_mode=${enableTagMode}`, `/api/channel/search?keyword=${searchKeyword}&group=${searchGroup}&model=${searchModel}&id_sort=${idSort}&tag_mode=${enableTagMode}${typeParam}`,
); );
const { success, message, data } = res.data; const { success, message, data } = res.data;
if (success) { if (success) {
setChannelFormat(data, enableTagMode); const { items = [], type_counts = {} } = data;
const sumAll = Object.values(type_counts).reduce((acc, v) => acc + v, 0);
setTypeCounts({ ...type_counts, all: sumAll });
setChannelFormat(items, enableTagMode);
setActivePage(1); setActivePage(1);
} else { } else {
showError(message); showError(message);
@@ -1179,7 +1185,94 @@ const ChannelsTable = () => {
} }
}; };
const channelTypeCounts = useMemo(() => {
if (Object.keys(typeCounts).length > 0) return typeCounts;
// fallback 本地计算
const counts = { all: channels.length };
channels.forEach((channel) => {
const collect = (ch) => {
const type = ch.type;
counts[type] = (counts[type] || 0) + 1;
};
if (channel.children !== undefined) {
channel.children.forEach(collect);
} else {
collect(channel);
}
});
return counts;
}, [typeCounts, channels]);
const availableTypeKeys = useMemo(() => {
const keys = ['all'];
Object.entries(channelTypeCounts).forEach(([k, v]) => {
if (k !== 'all' && v > 0) keys.push(String(k));
});
return keys;
}, [channelTypeCounts]);
const renderTypeTabs = () => {
if (enableTagMode) return null;
return (
<Tabs
activeKey={activeTypeKey}
type="card"
collapsible
onChange={(key) => {
setActiveTypeKey(key);
setActivePage(1);
loadChannels(1, pageSize, idSort, enableTagMode, key);
}}
className="mb-4"
>
<TabPane
itemKey="all"
tab={
<span className="flex items-center gap-2">
{t('全部')}
<Tag color={activeTypeKey === 'all' ? 'red' : 'grey'} size='small' shape='circle'>
{channelTypeCounts['all'] || 0}
</Tag>
</span>
}
/>
{CHANNEL_OPTIONS.filter((opt) => availableTypeKeys.includes(String(opt.value))).map((option) => {
const key = String(option.value);
const count = channelTypeCounts[option.value] || 0;
return (
<TabPane
key={key}
itemKey={key}
tab={
<span className="flex items-center gap-2">
{getChannelIcon(option.value)}
{option.label}
<Tag color={activeTypeKey === key ? 'red' : 'grey'} size='small' shape='circle'>
{count}
</Tag>
</span>
}
/>
);
})}
</Tabs>
);
};
let pageData = channels; let pageData = channels;
if (activeTypeKey !== 'all') {
const typeVal = parseInt(activeTypeKey);
if (!isNaN(typeVal)) {
pageData = pageData.filter((ch) => {
if (ch.children !== undefined) {
return ch.children.some((c) => c.type === typeVal);
}
return ch.type === typeVal;
});
}
}
const handlePageChange = (page) => { const handlePageChange = (page) => {
setActivePage(page); setActivePage(page);
@@ -1371,6 +1464,7 @@ const ChannelsTable = () => {
const renderHeader = () => ( const renderHeader = () => (
<div className="flex flex-col w-full"> <div className="flex flex-col w-full">
{renderTypeTabs()}
<div className="flex flex-col md:flex-row justify-between gap-4"> <div className="flex flex-col md:flex-row justify-between gap-4">
<div className="flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1"> <div className="flex flex-wrap md:flex-nowrap items-center gap-2 w-full md:w-auto order-2 md:order-1">
<Button <Button

View File

@@ -96,20 +96,8 @@ const renderTimestamp = (timestampInSeconds) => {
}; };
function renderDuration(submit_time, finishTime) { function renderDuration(submit_time, finishTime) {
// 确保startTime和finishTime都是有效的时间戳
if (!submit_time || !finishTime) return 'N/A'; if (!submit_time || !finishTime) return 'N/A';
const durationSec = finishTime - submit_time;
// 将时间戳转换为Date对象
const start = new Date(submit_time);
const finish = new Date(finishTime);
// 计算时间差(毫秒)
const durationMs = finish - start;
// 将时间差转换为秒,并保留一位小数
const durationSec = (durationMs / 1000).toFixed(1);
// 设置颜色大于60秒则为红色小于等于60秒则为绿色
const color = durationSec > 60 ? 'red' : 'green'; const color = durationSec > 60 ? 'red' : 'green';
// 返回带有样式的颜色标签 // 返回带有样式的颜色标签

View File

@@ -9,6 +9,7 @@ export function setStatusData(data) {
localStorage.setItem('enable_task', data.enable_task); localStorage.setItem('enable_task', data.enable_task);
localStorage.setItem('enable_data_export', data.enable_data_export); localStorage.setItem('enable_data_export', data.enable_data_export);
localStorage.setItem('chats', JSON.stringify(data.chats)); localStorage.setItem('chats', JSON.stringify(data.chats));
localStorage.setItem('pay_methods', JSON.stringify(data.pay_methods));
localStorage.setItem( localStorage.setItem(
'data_export_default_time', 'data_export_default_time',
data.data_export_default_time, data.data_export_default_time,

View File

@@ -1588,7 +1588,7 @@
"性能指标": "Performance Indicators", "性能指标": "Performance Indicators",
"模型数据分析": "Model Data Analysis", "模型数据分析": "Model Data Analysis",
"搜索无结果": "No results found", "搜索无结果": "No results found",
"仪表盘置": "Dashboard Configuration", "仪表盘置": "Dashboard Settings",
"API信息管理可以配置多个API地址用于状态展示和负载均衡最多50个": "API information management, you can configure multiple API addresses for status display and load balancing (maximum 50)", "API信息管理可以配置多个API地址用于状态展示和负载均衡最多50个": "API information management, you can configure multiple API addresses for status display and load balancing (maximum 50)",
"线路描述": "Route description", "线路描述": "Route description",
"颜色": "Color", "颜色": "Color",

View File

@@ -298,18 +298,27 @@ const EditChannel = (props) => {
} }
}; };
useEffect(() => { useEffect(() => {
let localModelOptions = [...originModelOptions]; // 使用 Map 来避免重复,以 value 为键
inputs.models.forEach((model) => { const modelMap = new Map();
if (!localModelOptions.find((option) => option.label === model)) {
localModelOptions.push({ // 先添加原始模型选项
label: model, originModelOptions.forEach(option => {
value: model, modelMap.set(option.value, option);
}); });
}
}); // 再添加当前选中的模型(如果不存在)
setModelOptions(localModelOptions); inputs.models.forEach(model => {
}, [originModelOptions, inputs.models]); if (!modelMap.has(model)) {
modelMap.set(model, {
label: model,
value: model,
});
}
});
setModelOptions(Array.from(modelMap.values()));
}, [originModelOptions, inputs.models]);
useEffect(() => { useEffect(() => {
fetchModels().then(); fetchModels().then();
@@ -530,7 +539,7 @@ const EditChannel = (props) => {
handleInputChange('key', value); handleInputChange('key', value);
}} }}
value={inputs.key} value={inputs.key}
style={{ minHeight: 150, fontFamily: 'JetBrains Mono, Consolas' }} autosize={{ minRows: 6, maxRows: 6 }}
autoComplete='new-password' autoComplete='new-password'
className="!rounded-lg" className="!rounded-lg"
/> />

View File

@@ -1112,6 +1112,7 @@ const Detail = (props) => {
</div> </div>
<Tabs <Tabs
type="button" type="button"
preventScroll={true}
activeKey={activeChartTab} activeKey={activeChartTab}
onChange={setActiveChartTab} onChange={setActiveChartTab}
> >
@@ -1388,6 +1389,7 @@ const Detail = (props) => {
) : ( ) : (
<Tabs <Tabs
type="card" type="card"
preventScroll={true}
collapsible collapsible
activeKey={activeUptimeTab} activeKey={activeUptimeTab}
onChange={setActiveUptimeTab} onChange={setActiveUptimeTab}

View File

@@ -184,16 +184,16 @@ export default function GroupRatioSettings(props) {
if (!value || value.trim() === '') { if (!value || value.trim() === '') {
return true; // Allow empty values return true; // Allow empty values
} }
// First check if it's valid JSON // First check if it's valid JSON
try { try {
const parsed = JSON.parse(value); const parsed = JSON.parse(value);
// Check if it's an array // Check if it's an array
if (!Array.isArray(parsed)) { if (!Array.isArray(parsed)) {
return false; return false;
} }
// Check if every element is a string // Check if every element is a string
return parsed.every(item => typeof item === 'string'); return parsed.every(item => typeof item === 'string');
} catch (error) { } catch (error) {

View File

@@ -10,6 +10,7 @@ import OperationSetting from '../../components/settings/OperationSetting.js';
import RateLimitSetting from '../../components/settings/RateLimitSetting.js'; import RateLimitSetting from '../../components/settings/RateLimitSetting.js';
import ModelSetting from '../../components/settings/ModelSetting.js'; import ModelSetting from '../../components/settings/ModelSetting.js';
import DashboardSetting from '../../components/settings/DashboardSetting.js'; import DashboardSetting from '../../components/settings/DashboardSetting.js';
import RatioSetting from '../../components/settings/RatioSetting.js';
const Setting = () => { const Setting = () => {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -24,6 +25,11 @@ const Setting = () => {
content: <OperationSetting />, content: <OperationSetting />,
itemKey: 'operation', itemKey: 'operation',
}); });
panes.push({
tab: t('倍率设置'),
content: <RatioSetting />,
itemKey: 'ratio',
});
panes.push({ panes.push({
tab: t('速率限制设置'), tab: t('速率限制设置'),
content: <RateLimitSetting />, content: <RateLimitSetting />,
@@ -45,7 +51,7 @@ const Setting = () => {
itemKey: 'other', itemKey: 'other',
}); });
panes.push({ panes.push({
tab: t('仪表盘置'), tab: t('仪表盘置'),
content: <DashboardSetting />, content: <DashboardSetting />,
itemKey: 'dashboard', itemKey: 'dashboard',
}); });

View File

@@ -7,7 +7,7 @@ import {
renderQuota, renderQuota,
renderQuotaWithAmount, renderQuotaWithAmount,
copy, copy,
getQuotaPerUnit getQuotaPerUnit,
} from '../../helpers'; } from '../../helpers';
import { import {
Avatar, Avatar,
@@ -34,7 +34,7 @@ import {
Copy, Copy,
Users, Users,
User, User,
Coins Coins,
} from 'lucide-react'; } from 'lucide-react';
const { Text, Title } = Typography; const { Text, Title } = Typography;
@@ -49,9 +49,15 @@ const TopUp = () => {
const [topUpCode, setTopUpCode] = useState(''); const [topUpCode, setTopUpCode] = useState('');
const [amount, setAmount] = useState(0.0); const [amount, setAmount] = useState(0.0);
const [minTopUp, setMinTopUp] = useState(statusState?.status?.min_topup || 1); const [minTopUp, setMinTopUp] = useState(statusState?.status?.min_topup || 1);
const [topUpCount, setTopUpCount] = useState(statusState?.status?.min_topup || 1); const [topUpCount, setTopUpCount] = useState(
const [topUpLink, setTopUpLink] = useState(statusState?.status?.top_up_link || ''); statusState?.status?.min_topup || 1,
const [enableOnlineTopUp, setEnableOnlineTopUp] = useState(statusState?.status?.enable_online_topup || false); );
const [topUpLink, setTopUpLink] = useState(
statusState?.status?.top_up_link || '',
);
const [enableOnlineTopUp, setEnableOnlineTopUp] = useState(
statusState?.status?.enable_online_topup || false,
);
const [priceRatio, setPriceRatio] = useState(statusState?.status?.price || 1); const [priceRatio, setPriceRatio] = useState(statusState?.status?.price || 1);
const [userQuota, setUserQuota] = useState(0); const [userQuota, setUserQuota] = useState(0);
const [isSubmitting, setIsSubmitting] = useState(false); const [isSubmitting, setIsSubmitting] = useState(false);
@@ -61,6 +67,7 @@ const TopUp = () => {
const [amountLoading, setAmountLoading] = useState(false); const [amountLoading, setAmountLoading] = useState(false);
const [paymentLoading, setPaymentLoading] = useState(false); const [paymentLoading, setPaymentLoading] = useState(false);
const [confirmLoading, setConfirmLoading] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false);
const [payMethods, setPayMethods] = useState([]);
// 邀请相关状态 // 邀请相关状态
const [affLink, setAffLink] = useState(''); const [affLink, setAffLink] = useState('');
@@ -76,7 +83,7 @@ const TopUp = () => {
{ value: 100 }, { value: 100 },
{ value: 300 }, { value: 300 },
{ value: 500 }, { value: 500 },
{ value: 1000 } { value: 1000 },
]); ]);
const [selectedPreset, setSelectedPreset] = useState(null); const [selectedPreset, setSelectedPreset] = useState(null);
@@ -126,7 +133,7 @@ const TopUp = () => {
if (userState.user) { if (userState.user) {
const updatedUser = { const updatedUser = {
...userState.user, ...userState.user,
quota: userState.user.quota + data quota: userState.user.quota + data,
}; };
userDispatch({ type: 'login', payload: updatedUser }); userDispatch({ type: 'login', payload: updatedUser });
} }
@@ -283,6 +290,34 @@ const TopUp = () => {
} }
getAffLink().then(); getAffLink().then();
setTransferAmount(getQuotaPerUnit()); setTransferAmount(getQuotaPerUnit());
let payMethods = localStorage.getItem('pay_methods');
try {
payMethods = JSON.parse(payMethods);
if (payMethods && payMethods.length > 0) {
// 检查name和type是否为空
payMethods = payMethods.filter((method) => {
return method.name && method.type;
});
// 如果没有color则设置默认颜色
payMethods = payMethods.map((method) => {
if (!method.color) {
if (method.type === 'zfb') {
method.color = 'rgba(var(--semi-blue-5), 1)';
} else if (method.type === 'wx') {
method.color = 'rgba(var(--semi-green-5), 1)';
} else {
method.color = 'rgba(var(--semi-primary-5), 1)';
}
}
return method;
});
setPayMethods(payMethods);
}
} catch (e) {
console.log(e);
showError(t('支付方式配置错误, 请联系管理员'));
}
}, []); }, []);
useEffect(() => { useEffect(() => {
@@ -347,12 +382,12 @@ const TopUp = () => {
}; };
return ( return (
<div className="mx-auto relative min-h-screen lg:min-h-0"> <div className='mx-auto relative min-h-screen lg:min-h-0'>
{/* 划转模态框 */} {/* 划转模态框 */}
<Modal <Modal
title={ title={
<div className="flex items-center"> <div className='flex items-center'>
<CreditCard className="mr-2" size={18} /> <CreditCard className='mr-2' size={18} />
{t('划转邀请额度')} {t('划转邀请额度')}
</div> </div>
} }
@@ -360,22 +395,22 @@ const TopUp = () => {
onOk={transfer} onOk={transfer}
onCancel={handleTransferCancel} onCancel={handleTransferCancel}
maskClosable={false} maskClosable={false}
size="small" size='small'
centered centered
> >
<div className="space-y-4"> <div className='space-y-4'>
<div> <div>
<Typography.Text strong className="block mb-2"> <Typography.Text strong className='block mb-2'>
{t('可用邀请额度')} {t('可用邀请额度')}
</Typography.Text> </Typography.Text>
<Input <Input
value={renderQuota(userState?.user?.aff_quota)} value={renderQuota(userState?.user?.aff_quota)}
disabled disabled
size="large" size='large'
/> />
</div> </div>
<div> <div>
<Typography.Text strong className="block mb-2"> <Typography.Text strong className='block mb-2'>
{t('划转额度')} ({t('最低') + renderQuota(getQuotaPerUnit())}) {t('划转额度')} ({t('最低') + renderQuota(getQuotaPerUnit())})
</Typography.Text> </Typography.Text>
<InputNumber <InputNumber
@@ -383,8 +418,8 @@ const TopUp = () => {
max={userState?.user?.aff_quota || 0} max={userState?.user?.aff_quota || 0}
value={transferAmount} value={transferAmount}
onChange={(value) => setTransferAmount(value)} onChange={(value) => setTransferAmount(value)}
size="large" size='large'
className="w-full" className='w-full'
/> />
</div> </div>
</div> </div>
@@ -393,8 +428,8 @@ const TopUp = () => {
{/* 充值确认模态框 */} {/* 充值确认模态框 */}
<Modal <Modal
title={ title={
<div className="flex items-center"> <div className='flex items-center'>
<CreditCard className="mr-2" size={18} /> <CreditCard className='mr-2' size={18} />
{t('充值确认')} {t('充值确认')}
</div> </div>
} }
@@ -402,57 +437,80 @@ const TopUp = () => {
onOk={onlineTopUp} onOk={onlineTopUp}
onCancel={handleCancel} onCancel={handleCancel}
maskClosable={false} maskClosable={false}
size="small" size='small'
centered centered
confirmLoading={confirmLoading} confirmLoading={confirmLoading}
> >
<div className="space-y-4"> <div className='space-y-4'>
<div className="flex justify-between items-center py-2"> <div className='flex justify-between items-center py-2'>
<Text strong>{t('充值数量')}</Text> <Text strong>{t('充值数量')}</Text>
<Text>{renderQuotaWithAmount(topUpCount)}</Text> <Text>{renderQuotaWithAmount(topUpCount)}</Text>
</div> </div>
<div className="flex justify-between items-center py-2"> <div className='flex justify-between items-center py-2'>
<Text strong>{t('实付金额')}</Text> <Text strong>{t('实付金额')}</Text>
{amountLoading ? ( {amountLoading ? (
<Skeleton.Title style={{ width: '60px', height: '16px' }} /> <Skeleton.Title style={{ width: '60px', height: '16px' }} />
) : ( ) : (
<Text type="danger" strong>{renderAmount()}</Text> <Text type='danger' strong>
{renderAmount()}
</Text>
)} )}
</div> </div>
<div className="flex justify-between items-center py-2"> <div className='flex justify-between items-center py-2'>
<Text strong>{t('支付方式')}</Text> <Text strong>{t('支付方式')}</Text>
<Text> <Text>
{payWay === 'zfb' ? ( {(() => {
<div className="flex items-center"> const payMethod = payMethods.find(
<SiAlipay className="mr-1" size={16} /> (method) => method.type === payWay,
{t('支付宝')} );
</div> if (payMethod) {
) : ( return (
<div className="flex items-center"> <div className='flex items-center'>
<SiWechat className="mr-1" size={16} /> {payMethod.type === 'zfb' ? (
{t('微信')} <SiAlipay className='mr-1' size={16} />
</div> ) : payMethod.type === 'wx' ? (
)} <SiWechat className='mr-1' size={16} />
) : (
<CreditCard className='mr-1' size={16} />
)}
{payMethod.name}
</div>
);
} else {
// 默认充值方式
return payWay === 'zfb' ? (
<div className='flex items-center'>
<SiAlipay className='mr-1' size={16} />
{t('支付宝')}
</div>
) : (
<div className='flex items-center'>
<SiWechat className='mr-1' size={16} />
{t('微信')}
</div>
);
}
})()}
</Text> </Text>
</div> </div>
</div> </div>
</Modal> </Modal>
<div className="grid grid-cols-1 lg:grid-cols-12 gap-6"> <div className='grid grid-cols-1 lg:grid-cols-12 gap-6'>
{/* 左侧充值区域 */} {/* 左侧充值区域 */}
<div className="lg:col-span-7 space-y-6 w-full"> <div className='lg:col-span-7 space-y-6 w-full'>
{/* 在线充值卡片 */} {/* 在线充值卡片 */}
<Card <Card
className="!rounded-2xl" className='!rounded-2xl'
shadows='always' shadows='always'
bordered={false} bordered={false}
header={ header={
<div className="px-5 py-4 pb-0"> <div className='px-5 py-4 pb-0'>
<div className="flex items-center justify-between"> <div className='flex items-center justify-between'>
<div className="flex items-center"> <div className='flex items-center'>
<Avatar <Avatar
className="mr-3 shadow-md flex-shrink-0" className='mr-3 shadow-md flex-shrink-0'
color="blue" color='blue'
> >
<CreditCard size={24} /> <CreditCard size={24} />
</Avatar> </Avatar>
@@ -460,21 +518,23 @@ const TopUp = () => {
<Title heading={5} style={{ margin: 0 }}> <Title heading={5} style={{ margin: 0 }}>
{t('在线充值')} {t('在线充值')}
</Title> </Title>
<Text type="tertiary" className="text-sm"> <Text type='tertiary' className='text-sm'>
{t('快速方便的充值方式')} {t('快速方便的充值方式')}
</Text> </Text>
</div> </div>
</div> </div>
<div className="flex items-center"> <div className='flex items-center'>
{userDataLoading ? ( {userDataLoading ? (
<Skeleton.Paragraph style={{ width: '120px' }} rows={1} /> <Skeleton.Paragraph style={{ width: '120px' }} rows={1} />
) : ( ) : (
<Text type="tertiary" className="hidden sm:block"> <Text type='tertiary' className='hidden sm:block'>
<div className="flex items-center"> <div className='flex items-center'>
<User size={14} className="mr-1" /> <User size={14} className='mr-1' />
<span className="hidden md:inline">{getUsername()} ({getUserRole()})</span> <span className='hidden md:inline'>
<span className="md:hidden">{getUsername()}</span> {getUsername()} ({getUserRole()})
</span>
<span className='md:hidden'>{getUsername()}</span>
</div> </div>
</Text> </Text>
)} )}
@@ -483,29 +543,33 @@ const TopUp = () => {
</div> </div>
} }
> >
<div className="space-y-4"> <div className='space-y-4'>
{/* 账户余额信息 */} {/* 账户余额信息 */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-2"> <div className='grid grid-cols-1 md:grid-cols-2 gap-4 mb-2'>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<Text type="tertiary" className="mb-1"> <Text type='tertiary' className='mb-1'>
{t('当前余额')} {t('当前余额')}
</Text> </Text>
{userDataLoading ? ( {userDataLoading ? (
<Skeleton.Title style={{ width: '100px', height: '30px' }} /> <Skeleton.Title
style={{ width: '100px', height: '30px' }}
/>
) : ( ) : (
<div className="text-xl font-semibold mt-2"> <div className='text-xl font-semibold mt-2'>
{renderQuota(userState?.user?.quota || userQuota)} {renderQuota(userState?.user?.quota || userQuota)}
</div> </div>
)} )}
</Card> </Card>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<Text type="tertiary" className="mb-1"> <Text type='tertiary' className='mb-1'>
{t('历史消耗')} {t('历史消耗')}
</Text> </Text>
{userDataLoading ? ( {userDataLoading ? (
<Skeleton.Title style={{ width: '100px', height: '30px' }} /> <Skeleton.Title
style={{ width: '100px', height: '30px' }}
/>
) : ( ) : (
<div className="text-xl font-semibold mt-2"> <div className='text-xl font-semibold mt-2'>
{renderQuota(userState?.user?.used_quota || 0)} {renderQuota(userState?.user?.used_quota || 0)}
</div> </div>
)} )}
@@ -516,47 +580,59 @@ const TopUp = () => {
<> <>
{/* 预设充值额度卡片网格 */} {/* 预设充值额度卡片网格 */}
<div> <div>
<Text strong className="block mb-3">{t('选择充值额度')}</Text> <Text strong className='block mb-3'>
<div className="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3"> {t('选择充值额度')}
</Text>
<div className='grid grid-cols-1 sm:grid-cols-2 md:grid-cols-4 gap-3'>
{presetAmounts.map((preset, index) => ( {presetAmounts.map((preset, index) => (
<Card <Card
key={index} key={index}
onClick={() => selectPresetAmount(preset)} onClick={() => selectPresetAmount(preset)}
className={`cursor-pointer !rounded-2xl transition-all hover:shadow-md ${selectedPreset === preset.value className={`cursor-pointer !rounded-2xl transition-all hover:shadow-md ${
? 'border-blue-500' selectedPreset === preset.value
: 'border-gray-200 hover:border-gray-300' ? 'border-blue-500'
}`} : 'border-gray-200 hover:border-gray-300'
}`}
bodyStyle={{ textAlign: 'center' }} bodyStyle={{ textAlign: 'center' }}
> >
<div className="font-medium text-lg flex items-center justify-center mb-1"> <div className='font-medium text-lg flex items-center justify-center mb-1'>
<Coins size={16} className="mr-0.5" /> <Coins size={16} className='mr-0.5' />
{formatLargeNumber(preset.value)} {formatLargeNumber(preset.value)}
</div> </div>
<div className="text-xs text-gray-500"> <div className='text-xs text-gray-500'>
{t('实付')} {(preset.value * priceRatio).toFixed(2)} {t('实付')}
{(preset.value * priceRatio).toFixed(2)}
</div> </div>
</Card> </Card>
))} ))}
</div> </div>
</div> </div>
{/* 桌面端显示的自定义金额和支付按钮 */} {/* 桌面端显示的自定义金额和支付按钮 */}
<div className="hidden md:block space-y-4"> <div className='hidden md:block space-y-4'>
<Divider style={{ margin: '24px 0' }}> <Divider style={{ margin: '24px 0' }}>
<Text className="text-sm font-medium">{t('或输入自定义金额')}</Text> <Text className='text-sm font-medium'>
{t('或输入自定义金额')}
</Text>
</Divider> </Divider>
<div> <div>
<div className="flex justify-between mb-2"> <div className='flex justify-between mb-2'>
<Text strong>{t('充值数量')}</Text> <Text strong>{t('充值数量')}</Text>
{amountLoading ? ( {amountLoading ? (
<Skeleton.Title style={{ width: '80px', height: '16px' }} /> <Skeleton.Title
style={{ width: '80px', height: '16px' }}
/>
) : ( ) : (
<Text type="tertiary">{t('实付金额:') + renderAmount()}</Text> <Text type='tertiary'>
{t('实付金额:') + renderAmount()}
</Text>
)} )}
</div> </div>
<InputNumber <InputNumber
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
placeholder={t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)} placeholder={
t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)
}
value={topUpCount} value={topUpCount}
min={minTopUp} min={minTopUp}
max={999999999} max={999999999}
@@ -576,36 +652,63 @@ const TopUp = () => {
getAmount(1); getAmount(1);
} }
}} }}
size="large" size='large'
className="w-full" className='w-full'
formatter={(value) => value ? `${value}` : ''} formatter={(value) => (value ? `${value}` : '')}
parser={(value) => value ? parseInt(value.replace(/[^\d]/g, '')) : 0} parser={(value) =>
value ? parseInt(value.replace(/[^\d]/g, '')) : 0
}
/> />
</div> </div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4"> <div className='grid grid-cols-1 sm:grid-cols-2 gap-4'>
<Button {/* <Button
type="primary" type='primary'
onClick={() => preTopUp('zfb')} onClick={() => preTopUp('zfb')}
size="large" size='large'
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === 'zfb'} loading={paymentLoading && payWay === 'zfb'}
icon={<SiAlipay size={18} />} icon={<SiAlipay size={18} />}
style={{ height: '44px' }} style={{ height: '44px' }}
> >
<span className="ml-2">{t('支付宝')}</span> <span className='ml-2'>{t('支付宝')}</span>
</Button> </Button>
<Button <Button
type="primary" type='primary'
onClick={() => preTopUp('wx')} onClick={() => preTopUp('wx')}
size="large" size='large'
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === 'wx'} loading={paymentLoading && payWay === 'wx'}
icon={<SiWechat size={18} />} icon={<SiWechat size={18} />}
style={{ height: '44px' }} style={{ height: '44px' }}
> >
<span className="ml-2">{t('微信')}</span> <span className='ml-2'>{t('微信')}</span>
</Button> </Button> */}
{payMethods.map((payMethod) => (
<Button
key={payMethod.type}
type='primary'
onClick={() => preTopUp(payMethod.type)}
size='large'
disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === payMethod.type}
icon={
payMethod.type === 'zfb' ? (
<SiAlipay size={18} />
) : payMethod.type === 'wx' ? (
<SiWechat size={18} />
) : (
<CreditCard size={18} />
)
}
style={{
height: '44px',
color: payMethod.color,
}}
>
<span className='ml-2'>{payMethod.name}</span>
</Button>
))}
</div> </div>
</div> </div>
</> </>
@@ -613,39 +716,41 @@ const TopUp = () => {
{!enableOnlineTopUp && ( {!enableOnlineTopUp && (
<Banner <Banner
type="warning" type='warning'
description={t('管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。')} description={t(
'管理员未开启在线充值功能,请联系管理员开启或使用兑换码充值。',
)}
closeIcon={null} closeIcon={null}
className="!rounded-2xl" className='!rounded-2xl'
/> />
)} )}
<Divider style={{ margin: '24px 0' }}> <Divider style={{ margin: '24px 0' }}>
<Text className="text-sm font-medium">{t('兑换码充值')}</Text> <Text className='text-sm font-medium'>{t('兑换码充值')}</Text>
</Divider> </Divider>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<div className="flex items-start mb-4"> <div className='flex items-start mb-4'>
<Gift size={16} className="mr-2 mt-0.5" /> <Gift size={16} className='mr-2 mt-0.5' />
<Text strong>{t('使用兑换码快速充值')}</Text> <Text strong>{t('使用兑换码快速充值')}</Text>
</div> </div>
<div className="mb-4"> <div className='mb-4'>
<Input <Input
placeholder={t('请输入兑换码')} placeholder={t('请输入兑换码')}
value={redemptionCode} value={redemptionCode}
onChange={(value) => setRedemptionCode(value)} onChange={(value) => setRedemptionCode(value)}
size="large" size='large'
/> />
</div> </div>
<div className="flex flex-col sm:flex-row gap-3"> <div className='flex flex-col sm:flex-row gap-3'>
{topUpLink && ( {topUpLink && (
<Button <Button
type="secondary" type='secondary'
onClick={openTopUpLink} onClick={openTopUpLink}
size="large" size='large'
className="flex-1" className='flex-1'
icon={<LinkIcon size={16} />} icon={<LinkIcon size={16} />}
style={{ height: '40px' }} style={{ height: '40px' }}
> >
@@ -653,12 +758,12 @@ const TopUp = () => {
</Button> </Button>
)} )}
<Button <Button
type="primary" type='primary'
onClick={topUp} onClick={topUp}
disabled={isSubmitting || !redemptionCode} disabled={isSubmitting || !redemptionCode}
loading={isSubmitting} loading={isSubmitting}
size="large" size='large'
className="flex-1" className='flex-1'
style={{ height: '40px' }} style={{ height: '40px' }}
> >
{isSubmitting ? t('兑换中...') : t('兑换')} {isSubmitting ? t('兑换中...') : t('兑换')}
@@ -670,18 +775,18 @@ const TopUp = () => {
</div> </div>
{/* 右侧邀请信息卡片 */} {/* 右侧邀请信息卡片 */}
<div className="lg:col-span-5"> <div className='lg:col-span-5'>
<Card <Card
className="!rounded-2xl" className='!rounded-2xl'
shadows='always' shadows='always'
bordered={false} bordered={false}
header={ header={
<div className="px-5 py-4 pb-0"> <div className='px-5 py-4 pb-0'>
<div className="flex items-center justify-between"> <div className='flex items-center justify-between'>
<div className="flex items-center"> <div className='flex items-center'>
<Avatar <Avatar
className="mr-3 shadow-md flex-shrink-0" className='mr-3 shadow-md flex-shrink-0'
color="green" color='green'
> >
<Users size={24} /> <Users size={24} />
</Avatar> </Avatar>
@@ -689,7 +794,7 @@ const TopUp = () => {
<Title heading={5} style={{ margin: 0 }}> <Title heading={5} style={{ margin: 0 }}>
{t('邀请奖励')} {t('邀请奖励')}
</Title> </Title>
<Text type="tertiary" className="text-sm"> <Text type='tertiary' className='text-sm'>
{t('邀请好友获得额外奖励')} {t('邀请好友获得额外奖励')}
</Text> </Text>
</div> </div>
@@ -698,53 +803,56 @@ const TopUp = () => {
</div> </div>
} }
> >
<div className="space-y-6"> <div className='space-y-6'>
<div className="grid grid-cols-1 gap-4"> <div className='grid grid-cols-1 gap-4'>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<div className="flex justify-between items-center"> <div className='flex justify-between items-center'>
<Text type="tertiary">{t('待使用收益')}</Text> <Text type='tertiary'>{t('待使用收益')}</Text>
<Button <Button
type="primary" type='primary'
theme="solid" theme='solid'
size="small" size='small'
disabled={!userState?.user?.aff_quota || userState?.user?.aff_quota <= 0} disabled={
!userState?.user?.aff_quota ||
userState?.user?.aff_quota <= 0
}
onClick={() => setOpenTransfer(true)} onClick={() => setOpenTransfer(true)}
> >
{t('划转到余额')} {t('划转到余额')}
</Button> </Button>
</div> </div>
<div className="text-2xl font-semibold mt-2"> <div className='text-2xl font-semibold mt-2'>
{renderQuota(userState?.user?.aff_quota || 0)} {renderQuota(userState?.user?.aff_quota || 0)}
</div> </div>
</Card> </Card>
<div className="grid grid-cols-2 gap-4"> <div className='grid grid-cols-2 gap-4'>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<Text type="tertiary">{t('总收益')}</Text> <Text type='tertiary'>{t('总收益')}</Text>
<div className="text-xl font-semibold mt-2"> <div className='text-xl font-semibold mt-2'>
{renderQuota(userState?.user?.aff_history_quota || 0)} {renderQuota(userState?.user?.aff_history_quota || 0)}
</div> </div>
</Card> </Card>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<Text type="tertiary">{t('邀请人数')}</Text> <Text type='tertiary'>{t('邀请人数')}</Text>
<div className="text-xl font-semibold mt-2 flex items-center"> <div className='text-xl font-semibold mt-2 flex items-center'>
<Users size={16} className="mr-1" /> <Users size={16} className='mr-1' />
{userState?.user?.aff_count || 0} {userState?.user?.aff_count || 0}
</div> </div>
</Card> </Card>
</div> </div>
</div> </div>
<div className="space-y-4"> <div className='space-y-4'>
<Title heading={6}>{t('邀请链接')}</Title> <Title heading={6}>{t('邀请链接')}</Title>
<Input <Input
value={affLink} value={affLink}
readOnly readOnly
size="large" size='large'
suffix={ suffix={
<Button <Button
type="primary" type='primary'
theme="light" theme='light'
onClick={handleAffLinkClick} onClick={handleAffLinkClick}
icon={<Copy size={14} />} icon={<Copy size={14} />}
> >
@@ -753,24 +861,24 @@ const TopUp = () => {
} }
/> />
<div className="mt-4"> <div className='mt-4'>
<Card className="!rounded-2xl"> <Card className='!rounded-2xl'>
<div className="space-y-4"> <div className='space-y-4'>
<div className="flex items-start"> <div className='flex items-start'>
<div className="w-1.5 h-1.5 rounded-full bg-blue-500 mt-2 mr-3 flex-shrink-0"></div> <div className='w-1.5 h-1.5 rounded-full bg-blue-500 mt-2 mr-3 flex-shrink-0'></div>
<Text type="tertiary" className="text-sm leading-6"> <Text type='tertiary' className='text-sm leading-6'>
{t('邀请好友注册,好友充值后您可获得相应奖励')} {t('邀请好友注册,好友充值后您可获得相应奖励')}
</Text> </Text>
</div> </div>
<div className="flex items-start"> <div className='flex items-start'>
<div className="w-1.5 h-1.5 rounded-full bg-green-500 mt-2 mr-3 flex-shrink-0"></div> <div className='w-1.5 h-1.5 rounded-full bg-green-500 mt-2 mr-3 flex-shrink-0'></div>
<Text type="tertiary" className="text-sm leading-6"> <Text type='tertiary' className='text-sm leading-6'>
{t('通过划转功能将奖励额度转入到您的账户余额中')} {t('通过划转功能将奖励额度转入到您的账户余额中')}
</Text> </Text>
</div> </div>
<div className="flex items-start"> <div className='flex items-start'>
<div className="w-1.5 h-1.5 rounded-full bg-purple-500 mt-2 mr-3 flex-shrink-0"></div> <div className='w-1.5 h-1.5 rounded-full bg-purple-500 mt-2 mr-3 flex-shrink-0'></div>
<Text type="tertiary" className="text-sm leading-6"> <Text type='tertiary' className='text-sm leading-6'>
{t('邀请的好友越多,获得的奖励越多')} {t('邀请的好友越多,获得的奖励越多')}
</Text> </Text>
</div> </div>
@@ -785,20 +893,27 @@ const TopUp = () => {
{/* 移动端底部固定的自定义金额和支付区域 */} {/* 移动端底部固定的自定义金额和支付区域 */}
{enableOnlineTopUp && ( {enableOnlineTopUp && (
<div className="md:hidden fixed bottom-0 left-0 right-0 p-4 shadow-lg z-50" style={{ background: 'var(--semi-color-bg-0)' }}> <div
<div className="space-y-4"> className='md:hidden fixed bottom-0 left-0 right-0 p-4 shadow-lg z-50'
style={{ background: 'var(--semi-color-bg-0)' }}
>
<div className='space-y-4'>
<div> <div>
<div className="flex justify-between mb-2"> <div className='flex justify-between mb-2'>
<Text strong>{t('充值数量')}</Text> <Text strong>{t('充值数量')}</Text>
{amountLoading ? ( {amountLoading ? (
<Skeleton.Title style={{ width: '80px', height: '16px' }} /> <Skeleton.Title style={{ width: '80px', height: '16px' }} />
) : ( ) : (
<Text type="tertiary">{t('实付金额:') + renderAmount()}</Text> <Text type='tertiary'>
{t('实付金额:') + renderAmount()}
</Text>
)} )}
</div> </div>
<InputNumber <InputNumber
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
placeholder={t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)} placeholder={
t('充值数量,最低 ') + renderQuotaWithAmount(minTopUp)
}
value={topUpCount} value={topUpCount}
min={minTopUp} min={minTopUp}
max={999999999} max={999999999}
@@ -818,31 +933,56 @@ const TopUp = () => {
getAmount(1); getAmount(1);
} }
}} }}
className="w-full" className='w-full'
formatter={(value) => value ? `${value}` : ''} formatter={(value) => (value ? `${value}` : '')}
parser={(value) => value ? parseInt(value.replace(/[^\d]/g, '')) : 0} parser={(value) =>
value ? parseInt(value.replace(/[^\d]/g, '')) : 0
}
/> />
</div> </div>
<div className="grid grid-cols-2 gap-4"> <div className='grid grid-cols-2 gap-4'>
<Button {/* <Button
type="primary" type='primary'
onClick={() => preTopUp('zfb')} onClick={() => preTopUp('zfb')}
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === 'zfb'} loading={paymentLoading && payWay === 'zfb'}
icon={<SiAlipay size={18} />} icon={<SiAlipay size={18} />}
> >
<span className="ml-2">{t('支付宝')}</span> <span className='ml-2'>{t('支付宝')}</span>
</Button> </Button>
<Button <Button
type="primary" type='primary'
onClick={() => preTopUp('wx')} onClick={() => preTopUp('wx')}
disabled={!enableOnlineTopUp} disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === 'wx'} loading={paymentLoading && payWay === 'wx'}
icon={<SiWechat size={18} />} icon={<SiWechat size={18} />}
> >
<span className="ml-2">{t('微信')}</span> <span className='ml-2'>{t('微信')}</span>
</Button> </Button> */}
{payMethods.map((payMethod) => (
<Button
key={payMethod.type}
type='primary'
onClick={() => preTopUp(payMethod.type)}
disabled={!enableOnlineTopUp}
loading={paymentLoading && payWay === payMethod.type}
icon={
payMethod.type === 'zfb' ? (
<SiAlipay size={18} />
) : payMethod.type === 'wx' ? (
<SiWechat size={18} />
) : (
<CreditCard size={18} />
)
}
style={{
color: payMethod.color,
}}
>
<span className='ml-2'>{payMethod.name}</span>
</Button>
))}
</div> </div>
</div> </div>
</div> </div>