feat(channel): 缓存扁平化 + 网关映射集成 + 计费模式统一 + 模型限制
- 缓存按 (groupID, platform, model) 三维 key 扁平化,避免跨平台同名模型冲突
- buildCache 批量查询 group platform,按平台过滤展开定价和映射
- model_mapping 改为嵌套格式 {platform: {src: dst}}
- channel_model_pricing 新增 platform 列
- 前端按平台维度重构:每个平台独立配置分组/映射/定价
- 迁移 086: platform 列 + model_mapping 嵌套格式迁移
This commit is contained in:
@@ -28,7 +28,7 @@ type createChannelRequest struct {
|
|||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
GroupIDs []int64 `json:"group_ids"`
|
GroupIDs []int64 `json:"group_ids"`
|
||||||
ModelPricing []channelModelPricingRequest `json:"model_pricing"`
|
ModelPricing []channelModelPricingRequest `json:"model_pricing"`
|
||||||
ModelMapping map[string]string `json:"model_mapping"`
|
ModelMapping map[string]map[string]string `json:"model_mapping"`
|
||||||
BillingModelSource string `json:"billing_model_source" binding:"omitempty,oneof=requested upstream"`
|
BillingModelSource string `json:"billing_model_source" binding:"omitempty,oneof=requested upstream"`
|
||||||
RestrictModels bool `json:"restrict_models"`
|
RestrictModels bool `json:"restrict_models"`
|
||||||
}
|
}
|
||||||
@@ -39,12 +39,13 @@ type updateChannelRequest struct {
|
|||||||
Status string `json:"status" binding:"omitempty,oneof=active disabled"`
|
Status string `json:"status" binding:"omitempty,oneof=active disabled"`
|
||||||
GroupIDs *[]int64 `json:"group_ids"`
|
GroupIDs *[]int64 `json:"group_ids"`
|
||||||
ModelPricing *[]channelModelPricingRequest `json:"model_pricing"`
|
ModelPricing *[]channelModelPricingRequest `json:"model_pricing"`
|
||||||
ModelMapping map[string]string `json:"model_mapping"`
|
ModelMapping map[string]map[string]string `json:"model_mapping"`
|
||||||
BillingModelSource string `json:"billing_model_source" binding:"omitempty,oneof=requested upstream"`
|
BillingModelSource string `json:"billing_model_source" binding:"omitempty,oneof=requested upstream"`
|
||||||
RestrictModels *bool `json:"restrict_models"`
|
RestrictModels *bool `json:"restrict_models"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type channelModelPricingRequest struct {
|
type channelModelPricingRequest struct {
|
||||||
|
Platform string `json:"platform" binding:"omitempty,max=50"`
|
||||||
Models []string `json:"models" binding:"required,min=1,max=100"`
|
Models []string `json:"models" binding:"required,min=1,max=100"`
|
||||||
BillingMode string `json:"billing_mode" binding:"omitempty,oneof=token per_request image"`
|
BillingMode string `json:"billing_mode" binding:"omitempty,oneof=token per_request image"`
|
||||||
InputPrice *float64 `json:"input_price" binding:"omitempty,min=0"`
|
InputPrice *float64 `json:"input_price" binding:"omitempty,min=0"`
|
||||||
@@ -77,13 +78,14 @@ type channelResponse struct {
|
|||||||
RestrictModels bool `json:"restrict_models"`
|
RestrictModels bool `json:"restrict_models"`
|
||||||
GroupIDs []int64 `json:"group_ids"`
|
GroupIDs []int64 `json:"group_ids"`
|
||||||
ModelPricing []channelModelPricingResponse `json:"model_pricing"`
|
ModelPricing []channelModelPricingResponse `json:"model_pricing"`
|
||||||
ModelMapping map[string]string `json:"model_mapping"`
|
ModelMapping map[string]map[string]string `json:"model_mapping"`
|
||||||
CreatedAt string `json:"created_at"`
|
CreatedAt string `json:"created_at"`
|
||||||
UpdatedAt string `json:"updated_at"`
|
UpdatedAt string `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type channelModelPricingResponse struct {
|
type channelModelPricingResponse struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
|
Platform string `json:"platform"`
|
||||||
Models []string `json:"models"`
|
Models []string `json:"models"`
|
||||||
BillingMode string `json:"billing_mode"`
|
BillingMode string `json:"billing_mode"`
|
||||||
InputPrice *float64 `json:"input_price"`
|
InputPrice *float64 `json:"input_price"`
|
||||||
@@ -131,7 +133,7 @@ func channelToResponse(ch *service.Channel) *channelResponse {
|
|||||||
resp.GroupIDs = []int64{}
|
resp.GroupIDs = []int64{}
|
||||||
}
|
}
|
||||||
if resp.ModelMapping == nil {
|
if resp.ModelMapping == nil {
|
||||||
resp.ModelMapping = map[string]string{}
|
resp.ModelMapping = map[string]map[string]string{}
|
||||||
}
|
}
|
||||||
|
|
||||||
resp.ModelPricing = make([]channelModelPricingResponse, 0, len(ch.ModelPricing))
|
resp.ModelPricing = make([]channelModelPricingResponse, 0, len(ch.ModelPricing))
|
||||||
@@ -144,6 +146,10 @@ func channelToResponse(ch *service.Channel) *channelResponse {
|
|||||||
if billingMode == "" {
|
if billingMode == "" {
|
||||||
billingMode = "token"
|
billingMode = "token"
|
||||||
}
|
}
|
||||||
|
platform := p.Platform
|
||||||
|
if platform == "" {
|
||||||
|
platform = "anthropic"
|
||||||
|
}
|
||||||
intervals := make([]pricingIntervalResponse, 0, len(p.Intervals))
|
intervals := make([]pricingIntervalResponse, 0, len(p.Intervals))
|
||||||
for _, iv := range p.Intervals {
|
for _, iv := range p.Intervals {
|
||||||
intervals = append(intervals, pricingIntervalResponse{
|
intervals = append(intervals, pricingIntervalResponse{
|
||||||
@@ -161,6 +167,7 @@ func channelToResponse(ch *service.Channel) *channelResponse {
|
|||||||
}
|
}
|
||||||
resp.ModelPricing = append(resp.ModelPricing, channelModelPricingResponse{
|
resp.ModelPricing = append(resp.ModelPricing, channelModelPricingResponse{
|
||||||
ID: p.ID,
|
ID: p.ID,
|
||||||
|
Platform: platform,
|
||||||
Models: models,
|
Models: models,
|
||||||
BillingMode: billingMode,
|
BillingMode: billingMode,
|
||||||
InputPrice: p.InputPrice,
|
InputPrice: p.InputPrice,
|
||||||
@@ -182,6 +189,10 @@ func pricingRequestToService(reqs []channelModelPricingRequest) []service.Channe
|
|||||||
if billingMode == "" {
|
if billingMode == "" {
|
||||||
billingMode = service.BillingModeToken
|
billingMode = service.BillingModeToken
|
||||||
}
|
}
|
||||||
|
platform := r.Platform
|
||||||
|
if platform == "" {
|
||||||
|
platform = "anthropic"
|
||||||
|
}
|
||||||
intervals := make([]service.PricingInterval, 0, len(r.Intervals))
|
intervals := make([]service.PricingInterval, 0, len(r.Intervals))
|
||||||
for _, iv := range r.Intervals {
|
for _, iv := range r.Intervals {
|
||||||
intervals = append(intervals, service.PricingInterval{
|
intervals = append(intervals, service.PricingInterval{
|
||||||
@@ -197,6 +208,7 @@ func pricingRequestToService(reqs []channelModelPricingRequest) []service.Channe
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
result = append(result, service.ChannelModelPricing{
|
result = append(result, service.ChannelModelPricing{
|
||||||
|
Platform: platform,
|
||||||
Models: r.Models,
|
Models: r.Models,
|
||||||
BillingMode: billingMode,
|
BillingMode: billingMode,
|
||||||
InputPrice: r.InputPrice,
|
InputPrice: r.InputPrice,
|
||||||
|
|||||||
@@ -406,8 +406,9 @@ func (r *channelRepository) GetGroupsInOtherChannels(ctx context.Context, channe
|
|||||||
return conflicting, nil
|
return conflicting, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// marshalModelMapping 将 model mapping 序列化为 JSON 字节,nil/空 map 返回 '{}'
|
// marshalModelMapping 将 model mapping 序列化为嵌套 JSON 字节
|
||||||
func marshalModelMapping(m map[string]string) ([]byte, error) {
|
// 格式:{"platform": {"src": "dst"}, ...}
|
||||||
|
func marshalModelMapping(m map[string]map[string]string) ([]byte, error) {
|
||||||
if len(m) == 0 {
|
if len(m) == 0 {
|
||||||
return []byte("{}"), nil
|
return []byte("{}"), nil
|
||||||
}
|
}
|
||||||
@@ -418,14 +419,43 @@ func marshalModelMapping(m map[string]string) ([]byte, error) {
|
|||||||
return data, nil
|
return data, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// unmarshalModelMapping 将 JSON 字节反序列化为 model mapping
|
// unmarshalModelMapping 将 JSON 字节反序列化为嵌套 model mapping
|
||||||
func unmarshalModelMapping(data []byte) map[string]string {
|
func unmarshalModelMapping(data []byte) map[string]map[string]string {
|
||||||
if len(data) == 0 {
|
if len(data) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
var m map[string]string
|
var m map[string]map[string]string
|
||||||
if err := json.Unmarshal(data, &m); err != nil {
|
if err := json.Unmarshal(data, &m); err != nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// GetGroupPlatforms 批量查询分组 ID 对应的平台
|
||||||
|
func (r *channelRepository) GetGroupPlatforms(ctx context.Context, groupIDs []int64) (map[int64]string, error) {
|
||||||
|
if len(groupIDs) == 0 {
|
||||||
|
return make(map[int64]string), nil
|
||||||
|
}
|
||||||
|
rows, err := r.db.QueryContext(ctx,
|
||||||
|
`SELECT id, platform FROM groups WHERE id = ANY($1)`,
|
||||||
|
pq.Array(groupIDs),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("get group platforms: %w", err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
result := make(map[int64]string, len(groupIDs))
|
||||||
|
for rows.Next() {
|
||||||
|
var id int64
|
||||||
|
var platform string
|
||||||
|
if err := rows.Scan(&id, &platform); err != nil {
|
||||||
|
return nil, fmt.Errorf("scan group platform: %w", err)
|
||||||
|
}
|
||||||
|
result[id] = platform
|
||||||
|
}
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, fmt.Errorf("iterate group platforms: %w", err)
|
||||||
|
}
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ import (
|
|||||||
|
|
||||||
func (r *channelRepository) ListModelPricing(ctx context.Context, channelID int64) ([]service.ChannelModelPricing, error) {
|
func (r *channelRepository) ListModelPricing(ctx context.Context, channelID int64) ([]service.ChannelModelPricing, error) {
|
||||||
rows, err := r.db.QueryContext(ctx,
|
rows, err := r.db.QueryContext(ctx,
|
||||||
`SELECT id, channel_id, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price, created_at, updated_at
|
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price, created_at, updated_at
|
||||||
FROM channel_model_pricing WHERE channel_id = $1 ORDER BY id`, channelID,
|
FROM channel_model_pricing WHERE channel_id = $1 ORDER BY id`, channelID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -56,10 +56,10 @@ func (r *channelRepository) UpdateModelPricing(ctx context.Context, pricing *ser
|
|||||||
}
|
}
|
||||||
result, err := r.db.ExecContext(ctx,
|
result, err := r.db.ExecContext(ctx,
|
||||||
`UPDATE channel_model_pricing
|
`UPDATE channel_model_pricing
|
||||||
SET models = $1, billing_mode = $2, input_price = $3, output_price = $4, cache_write_price = $5, cache_read_price = $6, image_output_price = $7, per_request_price = $8, updated_at = NOW()
|
SET models = $1, billing_mode = $2, input_price = $3, output_price = $4, cache_write_price = $5, cache_read_price = $6, image_output_price = $7, per_request_price = $8, platform = $9, updated_at = NOW()
|
||||||
WHERE id = $9`,
|
WHERE id = $10`,
|
||||||
modelsJSON, billingMode, pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheReadPrice,
|
modelsJSON, billingMode, pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheReadPrice,
|
||||||
pricing.ImageOutputPrice, pricing.PerRequestPrice, pricing.ID,
|
pricing.ImageOutputPrice, pricing.PerRequestPrice, pricing.Platform, pricing.ID,
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("update model pricing: %w", err)
|
return fmt.Errorf("update model pricing: %w", err)
|
||||||
@@ -90,7 +90,7 @@ func (r *channelRepository) ReplaceModelPricing(ctx context.Context, channelID i
|
|||||||
// batchLoadModelPricing 批量加载多个渠道的模型定价(含区间)
|
// batchLoadModelPricing 批量加载多个渠道的模型定价(含区间)
|
||||||
func (r *channelRepository) batchLoadModelPricing(ctx context.Context, channelIDs []int64) (map[int64][]service.ChannelModelPricing, error) {
|
func (r *channelRepository) batchLoadModelPricing(ctx context.Context, channelIDs []int64) (map[int64][]service.ChannelModelPricing, error) {
|
||||||
rows, err := r.db.QueryContext(ctx,
|
rows, err := r.db.QueryContext(ctx,
|
||||||
`SELECT id, channel_id, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price, created_at, updated_at
|
`SELECT id, channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price, created_at, updated_at
|
||||||
FROM channel_model_pricing WHERE channel_id = ANY($1) ORDER BY channel_id, id`,
|
FROM channel_model_pricing WHERE channel_id = ANY($1) ORDER BY channel_id, id`,
|
||||||
pq.Array(channelIDs),
|
pq.Array(channelIDs),
|
||||||
)
|
)
|
||||||
@@ -169,7 +169,7 @@ func scanModelPricingRows(rows *sql.Rows) ([]service.ChannelModelPricing, []int6
|
|||||||
var p service.ChannelModelPricing
|
var p service.ChannelModelPricing
|
||||||
var modelsJSON []byte
|
var modelsJSON []byte
|
||||||
if err := rows.Scan(
|
if err := rows.Scan(
|
||||||
&p.ID, &p.ChannelID, &modelsJSON, &p.BillingMode,
|
&p.ID, &p.ChannelID, &p.Platform, &modelsJSON, &p.BillingMode,
|
||||||
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheReadPrice,
|
&p.InputPrice, &p.OutputPrice, &p.CacheWritePrice, &p.CacheReadPrice,
|
||||||
&p.ImageOutputPrice, &p.PerRequestPrice, &p.CreatedAt, &p.UpdatedAt,
|
&p.ImageOutputPrice, &p.PerRequestPrice, &p.CreatedAt, &p.UpdatedAt,
|
||||||
); err != nil {
|
); err != nil {
|
||||||
@@ -223,10 +223,14 @@ func createModelPricingExec(ctx context.Context, exec dbExec, pricing *service.C
|
|||||||
if billingMode == "" {
|
if billingMode == "" {
|
||||||
billingMode = service.BillingModeToken
|
billingMode = service.BillingModeToken
|
||||||
}
|
}
|
||||||
|
platform := pricing.Platform
|
||||||
|
if platform == "" {
|
||||||
|
platform = "anthropic"
|
||||||
|
}
|
||||||
err = exec.QueryRowContext(ctx,
|
err = exec.QueryRowContext(ctx,
|
||||||
`INSERT INTO channel_model_pricing (channel_id, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price)
|
`INSERT INTO channel_model_pricing (channel_id, platform, models, billing_mode, input_price, output_price, cache_write_price, cache_read_price, image_output_price, per_request_price)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id, created_at, updated_at`,
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id, created_at, updated_at`,
|
||||||
pricing.ChannelID, modelsJSON, billingMode,
|
pricing.ChannelID, platform, modelsJSON, billingMode,
|
||||||
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheReadPrice,
|
pricing.InputPrice, pricing.OutputPrice, pricing.CacheWritePrice, pricing.CacheReadPrice,
|
||||||
pricing.ImageOutputPrice, pricing.PerRequestPrice,
|
pricing.ImageOutputPrice, pricing.PerRequestPrice,
|
||||||
).Scan(&pricing.ID, &pricing.CreatedAt, &pricing.UpdatedAt)
|
).Scan(&pricing.ID, &pricing.CreatedAt, &pricing.UpdatedAt)
|
||||||
|
|||||||
@@ -41,16 +41,17 @@ type Channel struct {
|
|||||||
|
|
||||||
// 关联的分组 ID 列表
|
// 关联的分组 ID 列表
|
||||||
GroupIDs []int64
|
GroupIDs []int64
|
||||||
// 模型定价列表
|
// 模型定价列表(每条含 Platform 字段)
|
||||||
ModelPricing []ChannelModelPricing
|
ModelPricing []ChannelModelPricing
|
||||||
// 渠道级模型映射
|
// 渠道级模型映射(按平台分组:platform → {src→dst})
|
||||||
ModelMapping map[string]string
|
ModelMapping map[string]map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
// ChannelModelPricing 渠道模型定价条目
|
// ChannelModelPricing 渠道模型定价条目
|
||||||
type ChannelModelPricing struct {
|
type ChannelModelPricing struct {
|
||||||
ID int64
|
ID int64
|
||||||
ChannelID int64
|
ChannelID int64
|
||||||
|
Platform string // 所属平台(anthropic/openai/gemini/...)
|
||||||
Models []string // 绑定的模型列表
|
Models []string // 绑定的模型列表
|
||||||
BillingMode BillingMode // 计费模式
|
BillingMode BillingMode // 计费模式
|
||||||
InputPrice *float64 // 每 token 输入价格(USD)— 向后兼容 flat 定价
|
InputPrice *float64 // 每 token 输入价格(USD)— 向后兼容 flat 定价
|
||||||
@@ -82,21 +83,26 @@ type PricingInterval struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ResolveMappedModel 解析渠道级模型映射,返回映射后的模型名。
|
// ResolveMappedModel 解析渠道级模型映射,返回映射后的模型名。
|
||||||
|
// platform 指定查找哪个平台的映射规则。
|
||||||
// 支持通配符(如 "claude-*" → "claude-sonnet-4")。
|
// 支持通配符(如 "claude-*" → "claude-sonnet-4")。
|
||||||
// 如果没有匹配的映射规则,返回原始模型名。
|
// 如果没有匹配的映射规则,返回原始模型名。
|
||||||
func (c *Channel) ResolveMappedModel(requestedModel string) string {
|
func (c *Channel) ResolveMappedModel(platform, requestedModel string) string {
|
||||||
if len(c.ModelMapping) == 0 {
|
if len(c.ModelMapping) == 0 {
|
||||||
return requestedModel
|
return requestedModel
|
||||||
}
|
}
|
||||||
|
platformMapping, ok := c.ModelMapping[platform]
|
||||||
|
if !ok || len(platformMapping) == 0 {
|
||||||
|
return requestedModel
|
||||||
|
}
|
||||||
lower := strings.ToLower(requestedModel)
|
lower := strings.ToLower(requestedModel)
|
||||||
// 精确匹配优先
|
// 精确匹配优先
|
||||||
for src, dst := range c.ModelMapping {
|
for src, dst := range platformMapping {
|
||||||
if strings.ToLower(src) == lower {
|
if strings.ToLower(src) == lower {
|
||||||
return dst
|
return dst
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// 通配符匹配
|
// 通配符匹配
|
||||||
for src, dst := range c.ModelMapping {
|
for src, dst := range platformMapping {
|
||||||
srcLower := strings.ToLower(src)
|
srcLower := strings.ToLower(src)
|
||||||
if strings.HasSuffix(srcLower, "*") {
|
if strings.HasSuffix(srcLower, "*") {
|
||||||
prefix := strings.TrimSuffix(srcLower, "*")
|
prefix := strings.TrimSuffix(srcLower, "*")
|
||||||
@@ -190,9 +196,13 @@ func (c *Channel) Clone() *Channel {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if c.ModelMapping != nil {
|
if c.ModelMapping != nil {
|
||||||
cp.ModelMapping = make(map[string]string, len(c.ModelMapping))
|
cp.ModelMapping = make(map[string]map[string]string, len(c.ModelMapping))
|
||||||
for k, v := range c.ModelMapping {
|
for platform, mapping := range c.ModelMapping {
|
||||||
cp.ModelMapping[k] = v
|
inner := make(map[string]string, len(mapping))
|
||||||
|
for k, v := range mapping {
|
||||||
|
inner[k] = v
|
||||||
|
}
|
||||||
|
cp.ModelMapping[platform] = inner
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return &cp
|
return &cp
|
||||||
|
|||||||
@@ -39,6 +39,9 @@ type ChannelRepository interface {
|
|||||||
GetChannelIDByGroupID(ctx context.Context, groupID int64) (int64, error)
|
GetChannelIDByGroupID(ctx context.Context, groupID int64) (int64, error)
|
||||||
GetGroupsInOtherChannels(ctx context.Context, channelID int64, groupIDs []int64) ([]int64, error)
|
GetGroupsInOtherChannels(ctx context.Context, channelID int64, groupIDs []int64) ([]int64, error)
|
||||||
|
|
||||||
|
// 分组平台查询
|
||||||
|
GetGroupPlatforms(ctx context.Context, groupIDs []int64) (map[int64]string, error)
|
||||||
|
|
||||||
// 模型定价
|
// 模型定价
|
||||||
ListModelPricing(ctx context.Context, channelID int64) ([]ChannelModelPricing, error)
|
ListModelPricing(ctx context.Context, channelID int64) ([]ChannelModelPricing, error)
|
||||||
CreateModelPricing(ctx context.Context, pricing *ChannelModelPricing) error
|
CreateModelPricing(ctx context.Context, pricing *ChannelModelPricing) error
|
||||||
@@ -47,18 +50,20 @@ type ChannelRepository interface {
|
|||||||
ReplaceModelPricing(ctx context.Context, channelID int64, pricingList []ChannelModelPricing) error
|
ReplaceModelPricing(ctx context.Context, channelID int64, pricingList []ChannelModelPricing) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// channelModelKey 渠道缓存复合键
|
// channelModelKey 渠道缓存复合键(显式包含 platform 防止跨平台同名模型冲突)
|
||||||
type channelModelKey struct {
|
type channelModelKey struct {
|
||||||
groupID int64
|
groupID int64
|
||||||
|
platform string // 平台标识
|
||||||
model string // lowercase
|
model string // lowercase
|
||||||
}
|
}
|
||||||
|
|
||||||
// channelCache 渠道缓存快照(扁平化哈希结构,热路径 O(1) 查找)
|
// channelCache 渠道缓存快照(扁平化哈希结构,热路径 O(1) 查找)
|
||||||
type channelCache struct {
|
type channelCache struct {
|
||||||
// 热路径查找
|
// 热路径查找
|
||||||
pricingByGroupModel map[channelModelKey]*ChannelModelPricing // (groupID, model) → 定价
|
pricingByGroupModel map[channelModelKey]*ChannelModelPricing // (groupID, platform, model) → 定价
|
||||||
mappingByGroupModel map[channelModelKey]string // (groupID, model) → 映射目标
|
mappingByGroupModel map[channelModelKey]string // (groupID, platform, model) → 映射目标
|
||||||
channelByGroupID map[int64]*Channel // groupID → 渠道
|
channelByGroupID map[int64]*Channel // groupID → 渠道
|
||||||
|
groupPlatform map[int64]string // groupID → platform
|
||||||
|
|
||||||
// 冷路径(CRUD 操作)
|
// 冷路径(CRUD 操作)
|
||||||
byID map[int64]*Channel
|
byID map[int64]*Channel
|
||||||
@@ -135,6 +140,7 @@ func (s *ChannelService) buildCache(ctx context.Context) (*channelCache, error)
|
|||||||
pricingByGroupModel: make(map[channelModelKey]*ChannelModelPricing),
|
pricingByGroupModel: make(map[channelModelKey]*ChannelModelPricing),
|
||||||
mappingByGroupModel: make(map[channelModelKey]string),
|
mappingByGroupModel: make(map[channelModelKey]string),
|
||||||
channelByGroupID: make(map[int64]*Channel),
|
channelByGroupID: make(map[int64]*Channel),
|
||||||
|
groupPlatform: make(map[int64]string),
|
||||||
byID: make(map[int64]*Channel),
|
byID: make(map[int64]*Channel),
|
||||||
loadedAt: time.Now().Add(channelCacheTTL - channelErrorTTL), // 使剩余 TTL = errorTTL
|
loadedAt: time.Now().Add(channelCacheTTL - channelErrorTTL), // 使剩余 TTL = errorTTL
|
||||||
}
|
}
|
||||||
@@ -142,10 +148,25 @@ func (s *ChannelService) buildCache(ctx context.Context) (*channelCache, error)
|
|||||||
return nil, fmt.Errorf("list all channels: %w", err)
|
return nil, fmt.Errorf("list all channels: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 收集所有 groupID,批量查询 platform
|
||||||
|
var allGroupIDs []int64
|
||||||
|
for i := range channels {
|
||||||
|
allGroupIDs = append(allGroupIDs, channels[i].GroupIDs...)
|
||||||
|
}
|
||||||
|
groupPlatforms := make(map[int64]string)
|
||||||
|
if len(allGroupIDs) > 0 {
|
||||||
|
groupPlatforms, err = s.repo.GetGroupPlatforms(dbCtx, allGroupIDs)
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("failed to load group platforms for channel cache", "error", err)
|
||||||
|
// 降级:继续构建缓存但无法按平台过滤
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
cache := &channelCache{
|
cache := &channelCache{
|
||||||
pricingByGroupModel: make(map[channelModelKey]*ChannelModelPricing),
|
pricingByGroupModel: make(map[channelModelKey]*ChannelModelPricing),
|
||||||
mappingByGroupModel: make(map[channelModelKey]string),
|
mappingByGroupModel: make(map[channelModelKey]string),
|
||||||
channelByGroupID: make(map[int64]*Channel),
|
channelByGroupID: make(map[int64]*Channel),
|
||||||
|
groupPlatform: groupPlatforms,
|
||||||
byID: make(map[int64]*Channel, len(channels)),
|
byID: make(map[int64]*Channel, len(channels)),
|
||||||
loadedAt: time.Now(),
|
loadedAt: time.Now(),
|
||||||
}
|
}
|
||||||
@@ -157,23 +178,29 @@ func (s *ChannelService) buildCache(ctx context.Context) (*channelCache, error)
|
|||||||
// 展开到分组维度
|
// 展开到分组维度
|
||||||
for _, gid := range ch.GroupIDs {
|
for _, gid := range ch.GroupIDs {
|
||||||
cache.channelByGroupID[gid] = ch
|
cache.channelByGroupID[gid] = ch
|
||||||
|
platform := groupPlatforms[gid] // e.g. "anthropic"
|
||||||
|
|
||||||
// 展开模型定价到 (groupID, model) → *ChannelModelPricing
|
// 只展开该平台的模型定价到 (groupID, platform, model) → *ChannelModelPricing
|
||||||
for j := range ch.ModelPricing {
|
for j := range ch.ModelPricing {
|
||||||
pricing := &ch.ModelPricing[j]
|
pricing := &ch.ModelPricing[j]
|
||||||
|
if pricing.Platform != platform {
|
||||||
|
continue // 跳过非本平台的定价
|
||||||
|
}
|
||||||
for _, model := range pricing.Models {
|
for _, model := range pricing.Models {
|
||||||
key := channelModelKey{groupID: gid, model: strings.ToLower(model)}
|
key := channelModelKey{groupID: gid, platform: platform, model: strings.ToLower(model)}
|
||||||
cache.pricingByGroupModel[key] = pricing
|
cache.pricingByGroupModel[key] = pricing
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 展开模型映射到 (groupID, model) → target
|
// 只展开该平台的模型映射到 (groupID, platform, model) → target
|
||||||
for src, dst := range ch.ModelMapping {
|
if platformMapping, ok := ch.ModelMapping[platform]; ok {
|
||||||
key := channelModelKey{groupID: gid, model: strings.ToLower(src)}
|
for src, dst := range platformMapping {
|
||||||
|
key := channelModelKey{groupID: gid, platform: platform, model: strings.ToLower(src)}
|
||||||
cache.mappingByGroupModel[key] = dst
|
cache.mappingByGroupModel[key] = dst
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
s.cache.Store(cache)
|
s.cache.Store(cache)
|
||||||
return cache, nil
|
return cache, nil
|
||||||
@@ -214,7 +241,8 @@ func (s *ChannelService) GetChannelModelPricing(ctx context.Context, groupID int
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
key := channelModelKey{groupID: groupID, model: strings.ToLower(model)}
|
platform := cache.groupPlatform[groupID]
|
||||||
|
key := channelModelKey{groupID: groupID, platform: platform, model: strings.ToLower(model)}
|
||||||
pricing, ok := cache.pricingByGroupModel[key]
|
pricing, ok := cache.pricingByGroupModel[key]
|
||||||
if !ok {
|
if !ok {
|
||||||
return nil
|
return nil
|
||||||
@@ -246,7 +274,8 @@ func (s *ChannelService) ResolveChannelMapping(ctx context.Context, groupID int6
|
|||||||
result.BillingModelSource = BillingModelSourceRequested
|
result.BillingModelSource = BillingModelSourceRequested
|
||||||
}
|
}
|
||||||
|
|
||||||
key := channelModelKey{groupID: groupID, model: strings.ToLower(model)}
|
platform := cache.groupPlatform[groupID]
|
||||||
|
key := channelModelKey{groupID: groupID, platform: platform, model: strings.ToLower(model)}
|
||||||
if mapped, ok := cache.mappingByGroupModel[key]; ok {
|
if mapped, ok := cache.mappingByGroupModel[key]; ok {
|
||||||
result.MappedModel = mapped
|
result.MappedModel = mapped
|
||||||
result.Mapped = true
|
result.Mapped = true
|
||||||
@@ -270,7 +299,8 @@ func (s *ChannelService) IsModelRestricted(ctx context.Context, groupID int64, m
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 检查模型是否在定价列表中
|
// 检查模型是否在定价列表中
|
||||||
key := channelModelKey{groupID: groupID, model: strings.ToLower(model)}
|
platform := cache.groupPlatform[groupID]
|
||||||
|
key := channelModelKey{groupID: groupID, platform: platform, model: strings.ToLower(model)}
|
||||||
_, exists := cache.pricingByGroupModel[key]
|
_, exists := cache.pricingByGroupModel[key]
|
||||||
return !exists
|
return !exists
|
||||||
}
|
}
|
||||||
@@ -458,7 +488,7 @@ type CreateChannelInput struct {
|
|||||||
Description string
|
Description string
|
||||||
GroupIDs []int64
|
GroupIDs []int64
|
||||||
ModelPricing []ChannelModelPricing
|
ModelPricing []ChannelModelPricing
|
||||||
ModelMapping map[string]string
|
ModelMapping map[string]map[string]string // platform → {src→dst}
|
||||||
BillingModelSource string
|
BillingModelSource string
|
||||||
RestrictModels bool
|
RestrictModels bool
|
||||||
}
|
}
|
||||||
@@ -470,7 +500,7 @@ type UpdateChannelInput struct {
|
|||||||
Status string
|
Status string
|
||||||
GroupIDs *[]int64
|
GroupIDs *[]int64
|
||||||
ModelPricing *[]ChannelModelPricing
|
ModelPricing *[]ChannelModelPricing
|
||||||
ModelMapping map[string]string
|
ModelMapping map[string]map[string]string // platform → {src→dst}
|
||||||
BillingModelSource string
|
BillingModelSource string
|
||||||
RestrictModels *bool
|
RestrictModels *bool
|
||||||
}
|
}
|
||||||
|
|||||||
21
backend/migrations/086_channel_platform_pricing.sql
Normal file
21
backend/migrations/086_channel_platform_pricing.sql
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
-- 086_channel_platform_pricing.sql
|
||||||
|
-- 渠道按平台维度:model_pricing 加 platform 列,model_mapping 改为嵌套格式
|
||||||
|
|
||||||
|
-- 1. channel_model_pricing 加 platform 列
|
||||||
|
ALTER TABLE channel_model_pricing
|
||||||
|
ADD COLUMN IF NOT EXISTS platform VARCHAR(50) NOT NULL DEFAULT 'anthropic';
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_channel_model_pricing_platform
|
||||||
|
ON channel_model_pricing (platform);
|
||||||
|
|
||||||
|
-- 2. model_mapping: 从扁平 {"src":"dst"} 迁移为嵌套 {"anthropic":{"src":"dst"}}
|
||||||
|
-- 仅迁移非空、非 '{}' 的旧格式数据(通过检查第一个 value 是否为字符串来判断是否为旧格式)
|
||||||
|
UPDATE channels
|
||||||
|
SET model_mapping = jsonb_build_object('anthropic', model_mapping)
|
||||||
|
WHERE model_mapping IS NOT NULL
|
||||||
|
AND model_mapping::text NOT IN ('{}', 'null', '')
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM jsonb_each(model_mapping) AS kv
|
||||||
|
WHERE jsonb_typeof(kv.value) = 'object'
|
||||||
|
LIMIT 1
|
||||||
|
);
|
||||||
@@ -22,6 +22,7 @@ export interface PricingInterval {
|
|||||||
|
|
||||||
export interface ChannelModelPricing {
|
export interface ChannelModelPricing {
|
||||||
id?: number
|
id?: number
|
||||||
|
platform: string
|
||||||
models: string[]
|
models: string[]
|
||||||
billing_mode: BillingMode
|
billing_mode: BillingMode
|
||||||
input_price: number | null
|
input_price: number | null
|
||||||
@@ -42,7 +43,7 @@ export interface Channel {
|
|||||||
restrict_models: boolean
|
restrict_models: boolean
|
||||||
group_ids: number[]
|
group_ids: number[]
|
||||||
model_pricing: ChannelModelPricing[]
|
model_pricing: ChannelModelPricing[]
|
||||||
model_mapping: Record<string, string>
|
model_mapping: Record<string, Record<string, string>> // platform → {src→dst}
|
||||||
created_at: string
|
created_at: string
|
||||||
updated_at: string
|
updated_at: string
|
||||||
}
|
}
|
||||||
@@ -52,7 +53,7 @@ export interface CreateChannelRequest {
|
|||||||
description?: string
|
description?: string
|
||||||
group_ids?: number[]
|
group_ids?: number[]
|
||||||
model_pricing?: ChannelModelPricing[]
|
model_pricing?: ChannelModelPricing[]
|
||||||
model_mapping?: Record<string, string>
|
model_mapping?: Record<string, Record<string, string>>
|
||||||
billing_model_source?: string
|
billing_model_source?: string
|
||||||
restrict_models?: boolean
|
restrict_models?: boolean
|
||||||
}
|
}
|
||||||
@@ -63,7 +64,7 @@ export interface UpdateChannelRequest {
|
|||||||
status?: string
|
status?: string
|
||||||
group_ids?: number[]
|
group_ids?: number[]
|
||||||
model_pricing?: ChannelModelPricing[]
|
model_pricing?: ChannelModelPricing[]
|
||||||
model_mapping?: Record<string, string>
|
model_mapping?: Record<string, Record<string, string>>
|
||||||
billing_model_source?: string
|
billing_model_source?: string
|
||||||
restrict_models?: boolean
|
restrict_models?: boolean
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1806,7 +1806,13 @@ export default {
|
|||||||
restrictModels: 'Restrict Models',
|
restrictModels: 'Restrict Models',
|
||||||
restrictModelsHint: 'When enabled, only models in the pricing list are allowed. Others will be rejected.',
|
restrictModelsHint: 'When enabled, only models in the pricing list are allowed. Others will be rejected.',
|
||||||
defaultPerRequestPrice: 'Default per-request price (fallback when no tier matches)',
|
defaultPerRequestPrice: 'Default per-request price (fallback when no tier matches)',
|
||||||
defaultImagePrice: 'Default image price (fallback when no tier matches)'
|
defaultImagePrice: 'Default image price (fallback when no tier matches)',
|
||||||
|
platformConfig: 'Platform Configuration',
|
||||||
|
addPlatform: 'Add Platform',
|
||||||
|
noPlatforms: 'Click "Add Platform" to start configuring the channel',
|
||||||
|
mappingCount: 'mappings',
|
||||||
|
pricingEntry: 'Pricing Entry',
|
||||||
|
noModels: 'No models added'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -1886,7 +1886,13 @@ export default {
|
|||||||
restrictModels: '限制模型',
|
restrictModels: '限制模型',
|
||||||
restrictModelsHint: '开启后,仅允许模型定价列表中的模型。不在列表中的模型请求将被拒绝。',
|
restrictModelsHint: '开启后,仅允许模型定价列表中的模型。不在列表中的模型请求将被拒绝。',
|
||||||
defaultPerRequestPrice: '默认单次价格(未命中层级时使用)',
|
defaultPerRequestPrice: '默认单次价格(未命中层级时使用)',
|
||||||
defaultImagePrice: '默认图片价格(未命中层级时使用)'
|
defaultImagePrice: '默认图片价格(未命中层级时使用)',
|
||||||
|
platformConfig: '平台配置',
|
||||||
|
addPlatform: '添加平台',
|
||||||
|
noPlatforms: '点击"添加平台"开始配置渠道',
|
||||||
|
mappingCount: '条映射',
|
||||||
|
pricingEntry: '定价配置',
|
||||||
|
noModels: '未添加模型'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
|
|||||||
@@ -188,86 +188,6 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Group Association -->
|
|
||||||
<div>
|
|
||||||
<label class="input-label">
|
|
||||||
{{ t('admin.channels.form.groups', 'Associated Groups') }}
|
|
||||||
<span v-if="selectedGroupCount > 0" class="ml-1 text-xs font-normal text-gray-400">
|
|
||||||
({{ t('admin.channels.form.selectedCount', { count: selectedGroupCount }, `已选 ${selectedGroupCount} 个`) }})
|
|
||||||
</span>
|
|
||||||
</label>
|
|
||||||
<div class="relative mb-2">
|
|
||||||
<Icon
|
|
||||||
name="search"
|
|
||||||
size="md"
|
|
||||||
class="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 dark:text-gray-500"
|
|
||||||
/>
|
|
||||||
<input
|
|
||||||
v-model="groupSearchQuery"
|
|
||||||
type="text"
|
|
||||||
:placeholder="t('admin.channels.form.searchGroups', 'Search groups...')"
|
|
||||||
class="input pl-10"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div
|
|
||||||
class="max-h-64 overflow-auto rounded-lg border border-gray-200 bg-white p-2 dark:border-dark-600 dark:bg-dark-800"
|
|
||||||
>
|
|
||||||
<div v-if="groupsLoading" class="py-4 text-center text-sm text-gray-500">
|
|
||||||
{{ t('common.loading', 'Loading...') }}
|
|
||||||
</div>
|
|
||||||
<div v-else-if="allGroups.length === 0" class="py-4 text-center text-sm text-gray-500">
|
|
||||||
{{ t('admin.channels.form.noGroupsAvailable', 'No groups available') }}
|
|
||||||
</div>
|
|
||||||
<div v-else-if="groupsByPlatform.length === 0" class="py-4 text-center text-sm text-gray-500">
|
|
||||||
{{ t('admin.channels.form.noGroupsMatch', 'No groups match your search') }}
|
|
||||||
</div>
|
|
||||||
<template v-else>
|
|
||||||
<div
|
|
||||||
v-for="section in groupsByPlatform"
|
|
||||||
:key="section.platform"
|
|
||||||
class="mb-2 last:mb-0"
|
|
||||||
>
|
|
||||||
<!-- Platform header -->
|
|
||||||
<div class="flex items-center gap-1.5 px-1 py-1">
|
|
||||||
<PlatformIcon :platform="section.platform" size="xs" :class="getPlatformTextColor(section.platform)" />
|
|
||||||
<span :class="['text-xs font-semibold', getPlatformTextColor(section.platform)]">
|
|
||||||
{{ t('admin.groups.platforms.' + section.platform, section.platform) }}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<!-- Groups grid -->
|
|
||||||
<div class="flex flex-wrap gap-1 pl-1">
|
|
||||||
<label
|
|
||||||
v-for="group in section.groups"
|
|
||||||
:key="group.id"
|
|
||||||
class="inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-gray-200 px-2 py-1 text-xs transition-colors hover:bg-gray-50 dark:border-dark-600 dark:hover:bg-dark-700"
|
|
||||||
:class="[
|
|
||||||
form.group_ids.includes(group.id) ? 'bg-primary-50 border-primary-300 dark:bg-primary-900/20 dark:border-primary-700' : '',
|
|
||||||
isGroupInOtherChannel(group.id) ? 'opacity-40' : ''
|
|
||||||
]"
|
|
||||||
>
|
|
||||||
<input
|
|
||||||
type="checkbox"
|
|
||||||
:checked="form.group_ids.includes(group.id)"
|
|
||||||
:disabled="isGroupInOtherChannel(group.id)"
|
|
||||||
class="h-3 w-3 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
|
|
||||||
@change="toggleGroup(group.id)"
|
|
||||||
/>
|
|
||||||
<span :class="['font-medium', getPlatformTextColor(group.platform)]">{{ group.name }}</span>
|
|
||||||
<span
|
|
||||||
:class="['rounded-full px-1 py-0 text-[10px]', getRateBadgeClass(group.platform)]"
|
|
||||||
>{{ group.rate_multiplier }}x</span>
|
|
||||||
<span class="text-[10px] text-gray-400">{{ group.account_count || 0 }}</span>
|
|
||||||
<span
|
|
||||||
v-if="isGroupInOtherChannel(group.id)"
|
|
||||||
class="text-[10px] text-gray-400"
|
|
||||||
>{{ getGroupInOtherChannelLabel(group.id) }}</span>
|
|
||||||
</label>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- Billing Basis -->
|
<!-- Billing Basis -->
|
||||||
<div>
|
<div>
|
||||||
<label class="input-label">{{ t('admin.channels.form.billingModelSource', 'Billing Basis') }}</label>
|
<label class="input-label">{{ t('admin.channels.form.billingModelSource', 'Billing Basis') }}</label>
|
||||||
@@ -277,49 +197,171 @@
|
|||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<!-- Model Mapping -->
|
<!-- Platform Sections -->
|
||||||
<div>
|
<div class="space-y-3">
|
||||||
<div class="mb-2 flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<label class="input-label mb-0">{{ t('admin.channels.form.modelMapping', 'Model Mapping') }}</label>
|
<label class="input-label mb-0">{{ t('admin.channels.form.platformConfig', '平台配置') }}</label>
|
||||||
<button type="button" @click="addMappingEntry" class="btn btn-secondary btn-sm">
|
<!-- Add Platform -->
|
||||||
|
<div class="relative" v-if="availablePlatformsToAdd.length > 0">
|
||||||
|
<button type="button" @click="showPlatformMenu = !showPlatformMenu" class="btn btn-secondary btn-sm">
|
||||||
<Icon name="plus" size="sm" class="mr-1" />
|
<Icon name="plus" size="sm" class="mr-1" />
|
||||||
{{ t('common.add', 'Add') }}
|
{{ t('admin.channels.form.addPlatform', '添加平台') }}
|
||||||
|
</button>
|
||||||
|
<div
|
||||||
|
v-if="showPlatformMenu"
|
||||||
|
class="absolute right-0 z-10 mt-1 w-40 rounded-lg border border-gray-200 bg-white shadow-lg dark:border-dark-600 dark:bg-dark-800"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-for="p in availablePlatformsToAdd"
|
||||||
|
:key="p"
|
||||||
|
type="button"
|
||||||
|
@click="addPlatformSection(p)"
|
||||||
|
class="flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-gray-50 dark:hover:bg-dark-700"
|
||||||
|
>
|
||||||
|
<PlatformIcon :platform="p" size="xs" :class="getPlatformTextColor(p)" />
|
||||||
|
<span :class="getPlatformTextColor(p)">{{ t('admin.groups.platforms.' + p, p) }}</span>
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<p class="mb-2 text-xs text-gray-400">
|
</div>
|
||||||
{{ t('admin.channels.form.modelMappingHint', 'Map request model names to actual model names. Runs before account-level mapping.') }}
|
</div>
|
||||||
</p>
|
|
||||||
<div
|
<div
|
||||||
v-if="Object.keys(form.model_mapping).length === 0"
|
v-if="form.platforms.length === 0"
|
||||||
class="rounded-lg border border-dashed border-gray-300 p-4 text-center text-sm text-gray-500 dark:border-dark-500 dark:text-gray-400"
|
class="rounded-lg border border-dashed border-gray-300 p-6 text-center text-sm text-gray-500 dark:border-dark-500 dark:text-gray-400"
|
||||||
|
>
|
||||||
|
{{ t('admin.channels.form.noPlatforms', '点击"添加平台"开始配置渠道') }}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Each Platform Section -->
|
||||||
|
<div
|
||||||
|
v-for="(section, sIdx) in form.platforms"
|
||||||
|
:key="section.platform"
|
||||||
|
class="rounded-lg border border-gray-200 bg-white dark:border-dark-600 dark:bg-dark-800"
|
||||||
|
>
|
||||||
|
<!-- Platform Header -->
|
||||||
|
<div
|
||||||
|
class="flex cursor-pointer select-none items-center justify-between rounded-t-lg border-b border-gray-100 px-3 py-2 dark:border-dark-700"
|
||||||
|
:class="section.collapsed ? 'rounded-b-lg border-b-0' : ''"
|
||||||
|
@click="section.collapsed = !section.collapsed"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<Icon
|
||||||
|
:name="section.collapsed ? 'chevronRight' : 'chevronDown'"
|
||||||
|
size="sm"
|
||||||
|
class="text-gray-400"
|
||||||
|
/>
|
||||||
|
<PlatformIcon :platform="section.platform" size="xs" :class="getPlatformTextColor(section.platform)" />
|
||||||
|
<span :class="['text-sm font-semibold', getPlatformTextColor(section.platform)]">
|
||||||
|
{{ t('admin.groups.platforms.' + section.platform, section.platform) }}
|
||||||
|
</span>
|
||||||
|
<!-- Summary badges -->
|
||||||
|
<span class="text-xs text-gray-400">
|
||||||
|
{{ section.group_ids.length }} {{ t('admin.channels.groupsUnit', 'groups') }}
|
||||||
|
</span>
|
||||||
|
<span v-if="Object.keys(section.model_mapping).length > 0" class="text-xs text-gray-400">
|
||||||
|
· {{ Object.keys(section.model_mapping).length }} {{ t('admin.channels.form.mappingCount', 'mappings') }}
|
||||||
|
</span>
|
||||||
|
<span v-if="section.model_pricing.length > 0" class="text-xs text-gray-400">
|
||||||
|
· {{ section.model_pricing.length }} {{ t('admin.channels.pricingUnit', 'pricing rules') }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
@click.stop="removePlatformSection(sIdx)"
|
||||||
|
class="rounded p-1 text-gray-400 hover:text-red-500"
|
||||||
|
:title="t('common.delete', 'Delete')"
|
||||||
|
>
|
||||||
|
<Icon name="trash" size="sm" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Platform Content -->
|
||||||
|
<div v-show="!section.collapsed" class="space-y-4 p-3">
|
||||||
|
<!-- Groups -->
|
||||||
|
<div>
|
||||||
|
<label class="input-label text-xs">
|
||||||
|
{{ t('admin.channels.form.groups', 'Associated Groups') }}
|
||||||
|
<span v-if="section.group_ids.length > 0" class="ml-1 font-normal text-gray-400">
|
||||||
|
({{ t('admin.channels.form.selectedCount', { count: section.group_ids.length }, `已选 ${section.group_ids.length} 个`) }})
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<div class="max-h-40 overflow-auto rounded-lg border border-gray-200 bg-gray-50 p-2 dark:border-dark-600 dark:bg-dark-900">
|
||||||
|
<div v-if="groupsLoading" class="py-2 text-center text-xs text-gray-500">
|
||||||
|
{{ t('common.loading', 'Loading...') }}
|
||||||
|
</div>
|
||||||
|
<div v-else-if="getGroupsForPlatform(section.platform).length === 0" class="py-2 text-center text-xs text-gray-500">
|
||||||
|
{{ t('admin.channels.form.noGroupsAvailable', 'No groups available') }}
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex flex-wrap gap-1">
|
||||||
|
<label
|
||||||
|
v-for="group in getGroupsForPlatform(section.platform)"
|
||||||
|
:key="group.id"
|
||||||
|
class="inline-flex cursor-pointer items-center gap-1.5 rounded-md border border-gray-200 px-2 py-1 text-xs transition-colors hover:bg-gray-50 dark:border-dark-600 dark:hover:bg-dark-700"
|
||||||
|
:class="[
|
||||||
|
section.group_ids.includes(group.id) ? 'bg-primary-50 border-primary-300 dark:bg-primary-900/20 dark:border-primary-700' : '',
|
||||||
|
isGroupInOtherChannel(group.id, section.platform) ? 'opacity-40' : ''
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
:checked="section.group_ids.includes(group.id)"
|
||||||
|
:disabled="isGroupInOtherChannel(group.id, section.platform)"
|
||||||
|
class="h-3 w-3 rounded border-gray-300 text-primary-600 focus:ring-primary-500"
|
||||||
|
@change="toggleGroupInSection(sIdx, group.id)"
|
||||||
|
/>
|
||||||
|
<span :class="['font-medium', getPlatformTextColor(group.platform)]">{{ group.name }}</span>
|
||||||
|
<span
|
||||||
|
:class="['rounded-full px-1 py-0 text-[10px]', getRateBadgeClass(group.platform)]"
|
||||||
|
>{{ group.rate_multiplier }}x</span>
|
||||||
|
<span class="text-[10px] text-gray-400">{{ group.account_count || 0 }}</span>
|
||||||
|
<span
|
||||||
|
v-if="isGroupInOtherChannel(group.id, section.platform)"
|
||||||
|
class="text-[10px] text-gray-400"
|
||||||
|
>{{ getGroupInOtherChannelLabel(group.id) }}</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Model Mapping -->
|
||||||
|
<div>
|
||||||
|
<div class="mb-1 flex items-center justify-between">
|
||||||
|
<label class="input-label text-xs mb-0">{{ t('admin.channels.form.modelMapping', 'Model Mapping') }}</label>
|
||||||
|
<button type="button" @click="addMappingEntry(sIdx)" class="text-xs text-primary-600 hover:text-primary-700">
|
||||||
|
+ {{ t('common.add', 'Add') }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-if="Object.keys(section.model_mapping).length === 0"
|
||||||
|
class="rounded border border-dashed border-gray-300 p-2 text-center text-xs text-gray-400 dark:border-dark-500"
|
||||||
>
|
>
|
||||||
{{ t('admin.channels.form.noMappingRules', 'No mapping rules. Click "Add" to create one.') }}
|
{{ t('admin.channels.form.noMappingRules', 'No mapping rules. Click "Add" to create one.') }}
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="space-y-2">
|
<div v-else class="space-y-1">
|
||||||
<div
|
<div
|
||||||
v-for="(_, srcModel) in form.model_mapping"
|
v-for="(_, srcModel) in section.model_mapping"
|
||||||
:key="srcModel"
|
:key="srcModel"
|
||||||
class="flex items-center gap-2"
|
class="flex items-center gap-2"
|
||||||
>
|
>
|
||||||
<input
|
<input
|
||||||
:value="srcModel"
|
:value="srcModel"
|
||||||
type="text"
|
type="text"
|
||||||
class="input flex-1 text-sm"
|
class="input flex-1 text-xs"
|
||||||
:placeholder="t('admin.channels.form.mappingSource', 'Source model')"
|
:placeholder="t('admin.channels.form.mappingSource', 'Source model')"
|
||||||
@change="renameMappingKey(srcModel, ($event.target as HTMLInputElement).value)"
|
@change="renameMappingKey(sIdx, srcModel, ($event.target as HTMLInputElement).value)"
|
||||||
/>
|
/>
|
||||||
<span class="text-gray-400">→</span>
|
<span class="text-gray-400 text-xs">→</span>
|
||||||
<input
|
<input
|
||||||
:value="form.model_mapping[srcModel]"
|
:value="section.model_mapping[srcModel]"
|
||||||
type="text"
|
type="text"
|
||||||
class="input flex-1 text-sm"
|
class="input flex-1 text-xs"
|
||||||
:placeholder="t('admin.channels.form.mappingTarget', 'Target model')"
|
:placeholder="t('admin.channels.form.mappingTarget', 'Target model')"
|
||||||
@input="form.model_mapping[srcModel] = ($event.target as HTMLInputElement).value"
|
@input="section.model_mapping[srcModel] = ($event.target as HTMLInputElement).value"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@click="removeMappingEntry(srcModel)"
|
@click="removeMappingEntry(sIdx, srcModel)"
|
||||||
class="rounded p-1 text-gray-400 hover:text-red-500"
|
class="rounded p-0.5 text-gray-400 hover:text-red-500"
|
||||||
>
|
>
|
||||||
<Icon name="trash" size="sm" />
|
<Icon name="trash" size="sm" />
|
||||||
</button>
|
</button>
|
||||||
@@ -329,31 +371,31 @@
|
|||||||
|
|
||||||
<!-- Model Pricing -->
|
<!-- Model Pricing -->
|
||||||
<div>
|
<div>
|
||||||
<div class="mb-2 flex items-center justify-between">
|
<div class="mb-1 flex items-center justify-between">
|
||||||
<label class="input-label mb-0">{{ t('admin.channels.form.modelPricing', 'Model Pricing') }} <span class="text-red-500">*</span></label>
|
<label class="input-label text-xs mb-0">{{ t('admin.channels.form.modelPricing', 'Model Pricing') }}</label>
|
||||||
<button type="button" @click="addPricingEntry" class="btn btn-secondary btn-sm">
|
<button type="button" @click="addPricingEntry(sIdx)" class="text-xs text-primary-600 hover:text-primary-700">
|
||||||
<Icon name="plus" size="sm" class="mr-1" />
|
+ {{ t('common.add', 'Add') }}
|
||||||
{{ t('common.add', 'Add') }}
|
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div
|
<div
|
||||||
v-if="form.model_pricing.length === 0"
|
v-if="section.model_pricing.length === 0"
|
||||||
class="rounded-lg border border-dashed border-gray-300 p-4 text-center text-sm text-gray-500 dark:border-dark-500 dark:text-gray-400"
|
class="rounded border border-dashed border-gray-300 p-2 text-center text-xs text-gray-400 dark:border-dark-500"
|
||||||
>
|
>
|
||||||
{{ t('admin.channels.form.noPricingRules', 'No pricing rules yet. Click "Add" to create one.') }}
|
{{ t('admin.channels.form.noPricingRules', 'No pricing rules yet. Click "Add" to create one.') }}
|
||||||
</div>
|
</div>
|
||||||
|
<div v-else class="space-y-2">
|
||||||
<div v-else class="space-y-3">
|
|
||||||
<PricingEntryCard
|
<PricingEntryCard
|
||||||
v-for="(entry, idx) in form.model_pricing"
|
v-for="(entry, idx) in section.model_pricing"
|
||||||
:key="idx"
|
:key="idx"
|
||||||
:entry="entry"
|
:entry="entry"
|
||||||
@update="updatePricingEntry(idx, $event)"
|
@update="updatePricingEntry(sIdx, idx, $event)"
|
||||||
@remove="removePricingEntry(idx)"
|
@remove="removePricingEntry(sIdx, idx)"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<template #footer>
|
<template #footer>
|
||||||
@@ -418,6 +460,15 @@ import { getPersistedPageSize } from '@/composables/usePersistedPageSize'
|
|||||||
const { t } = useI18n()
|
const { t } = useI18n()
|
||||||
const appStore = useAppStore()
|
const appStore = useAppStore()
|
||||||
|
|
||||||
|
// ── Platform Section type ──
|
||||||
|
interface PlatformSection {
|
||||||
|
platform: GroupPlatform
|
||||||
|
collapsed: boolean
|
||||||
|
group_ids: number[]
|
||||||
|
model_mapping: Record<string, string>
|
||||||
|
model_pricing: PricingFormEntry[]
|
||||||
|
}
|
||||||
|
|
||||||
// ── Table columns ──
|
// ── Table columns ──
|
||||||
const columns = computed<Column[]>(() => [
|
const columns = computed<Column[]>(() => [
|
||||||
{ key: 'name', label: t('admin.channels.columns.name', 'Name'), sortable: true },
|
{ key: 'name', label: t('admin.channels.columns.name', 'Name'), sortable: true },
|
||||||
@@ -462,11 +513,11 @@ const editingChannel = ref<Channel | null>(null)
|
|||||||
const submitting = ref(false)
|
const submitting = ref(false)
|
||||||
const showDeleteDialog = ref(false)
|
const showDeleteDialog = ref(false)
|
||||||
const deletingChannel = ref<Channel | null>(null)
|
const deletingChannel = ref<Channel | null>(null)
|
||||||
|
const showPlatformMenu = ref(false)
|
||||||
|
|
||||||
// Groups
|
// Groups
|
||||||
const allGroups = ref<AdminGroup[]>([])
|
const allGroups = ref<AdminGroup[]>([])
|
||||||
const groupsLoading = ref(false)
|
const groupsLoading = ref(false)
|
||||||
const groupSearchQuery = ref('')
|
|
||||||
|
|
||||||
// Form data
|
// Form data
|
||||||
const form = reactive({
|
const form = reactive({
|
||||||
@@ -474,22 +525,13 @@ const form = reactive({
|
|||||||
description: '',
|
description: '',
|
||||||
status: 'active',
|
status: 'active',
|
||||||
restrict_models: false,
|
restrict_models: false,
|
||||||
group_ids: [] as number[],
|
billing_model_source: 'requested' as string,
|
||||||
model_pricing: [] as PricingFormEntry[],
|
platforms: [] as PlatformSection[]
|
||||||
model_mapping: {} as Record<string, string>,
|
|
||||||
billing_model_source: 'requested' as string
|
|
||||||
})
|
})
|
||||||
|
|
||||||
let abortController: AbortController | null = null
|
let abortController: AbortController | null = null
|
||||||
|
|
||||||
// ── Helpers ──
|
// ── Platform config ──
|
||||||
function formatDate(value: string): string {
|
|
||||||
if (!value) return '-'
|
|
||||||
return new Date(value).toLocaleDateString()
|
|
||||||
}
|
|
||||||
|
|
||||||
// ── Group helpers ──
|
|
||||||
// Platform color helpers
|
|
||||||
const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'sora']
|
const platformOrder: GroupPlatform[] = ['anthropic', 'openai', 'gemini', 'antigravity', 'sora']
|
||||||
|
|
||||||
function getPlatformTextColor(platform: string): string {
|
function getPlatformTextColor(platform: string): string {
|
||||||
@@ -514,39 +556,39 @@ function getRateBadgeClass(platform: string): string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const groupsByPlatform = computed(() => {
|
// ── Helpers ──
|
||||||
const query = groupSearchQuery.value.trim().toLowerCase()
|
function formatDate(value: string): string {
|
||||||
const groups = query
|
if (!value) return '-'
|
||||||
? allGroups.value.filter(g => g.name.toLowerCase().includes(query))
|
return new Date(value).toLocaleDateString()
|
||||||
: allGroups.value
|
|
||||||
|
|
||||||
const grouped = new Map<GroupPlatform, typeof groups>()
|
|
||||||
for (const g of groups) {
|
|
||||||
const platform = g.platform
|
|
||||||
if (!platform) continue
|
|
||||||
if (!grouped.has(platform)) grouped.set(platform, [])
|
|
||||||
grouped.get(platform)!.push(g)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sort by platformOrder
|
// ── Platform section helpers ──
|
||||||
const result: Array<{ platform: GroupPlatform; groups: typeof groups }> = []
|
const activePlatforms = computed(() => form.platforms.map(s => s.platform))
|
||||||
for (const p of platformOrder) {
|
|
||||||
const list = grouped.get(p)
|
const availablePlatformsToAdd = computed(() =>
|
||||||
if (list && list.length > 0) {
|
platformOrder.filter(p => !activePlatforms.value.includes(p))
|
||||||
result.push({ platform: p, groups: list })
|
)
|
||||||
}
|
|
||||||
}
|
function addPlatformSection(platform: GroupPlatform) {
|
||||||
// Add any remaining platforms not in platformOrder
|
form.platforms.push({
|
||||||
for (const [p, list] of grouped) {
|
platform,
|
||||||
if (!platformOrder.includes(p) && list.length > 0) {
|
collapsed: false,
|
||||||
result.push({ platform: p, groups: list })
|
group_ids: [],
|
||||||
}
|
model_mapping: {},
|
||||||
}
|
model_pricing: []
|
||||||
return result
|
|
||||||
})
|
})
|
||||||
|
showPlatformMenu.value = false
|
||||||
|
}
|
||||||
|
|
||||||
const selectedGroupCount = computed(() => form.group_ids.length)
|
function removePlatformSection(idx: number) {
|
||||||
|
form.platforms.splice(idx, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGroupsForPlatform(platform: GroupPlatform): AdminGroup[] {
|
||||||
|
return allGroups.value.filter(g => g.platform === platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Group helpers ──
|
||||||
const groupToChannelMap = computed(() => {
|
const groupToChannelMap = computed(() => {
|
||||||
const map = new Map<number, Channel>()
|
const map = new Map<number, Channel>()
|
||||||
for (const ch of channels.value) {
|
for (const ch of channels.value) {
|
||||||
@@ -558,7 +600,7 @@ const groupToChannelMap = computed(() => {
|
|||||||
return map
|
return map
|
||||||
})
|
})
|
||||||
|
|
||||||
function isGroupInOtherChannel(groupId: number): boolean {
|
function isGroupInOtherChannel(groupId: number, _platform: string): boolean {
|
||||||
return groupToChannelMap.value.has(groupId)
|
return groupToChannelMap.value.has(groupId)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -580,18 +622,19 @@ const deleteConfirmMessage = computed(() => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
function toggleGroup(groupId: number) {
|
function toggleGroupInSection(sectionIdx: number, groupId: number) {
|
||||||
const idx = form.group_ids.indexOf(groupId)
|
const section = form.platforms[sectionIdx]
|
||||||
|
const idx = section.group_ids.indexOf(groupId)
|
||||||
if (idx >= 0) {
|
if (idx >= 0) {
|
||||||
form.group_ids.splice(idx, 1)
|
section.group_ids.splice(idx, 1)
|
||||||
} else {
|
} else {
|
||||||
form.group_ids.push(groupId)
|
section.group_ids.push(groupId)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Pricing helpers ──
|
// ── Pricing helpers ──
|
||||||
function addPricingEntry() {
|
function addPricingEntry(sectionIdx: number) {
|
||||||
form.model_pricing.push({
|
form.platforms[sectionIdx].model_pricing.push({
|
||||||
models: [],
|
models: [],
|
||||||
billing_mode: 'token',
|
billing_mode: 'token',
|
||||||
input_price: null,
|
input_price: null,
|
||||||
@@ -604,32 +647,105 @@ function addPricingEntry() {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
function updatePricingEntry(idx: number, updated: PricingFormEntry) {
|
function updatePricingEntry(sectionIdx: number, idx: number, updated: PricingFormEntry) {
|
||||||
form.model_pricing[idx] = updated
|
form.platforms[sectionIdx].model_pricing[idx] = updated
|
||||||
}
|
}
|
||||||
|
|
||||||
function removePricingEntry(idx: number) {
|
function removePricingEntry(sectionIdx: number, idx: number) {
|
||||||
form.model_pricing.splice(idx, 1)
|
form.platforms[sectionIdx].model_pricing.splice(idx, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
function formPricingToAPI(): ChannelModelPricing[] {
|
// ── Model Mapping helpers ──
|
||||||
return form.model_pricing
|
function addMappingEntry(sectionIdx: number) {
|
||||||
.filter(e => e.models.length > 0)
|
const mapping = form.platforms[sectionIdx].model_mapping
|
||||||
.map(e => ({
|
let key = ''
|
||||||
models: e.models,
|
let i = 1
|
||||||
billing_mode: e.billing_mode,
|
while (key === '' || key in mapping) {
|
||||||
input_price: mTokToPerToken(e.input_price),
|
key = `model-${i}`
|
||||||
output_price: mTokToPerToken(e.output_price),
|
i++
|
||||||
cache_write_price: mTokToPerToken(e.cache_write_price),
|
}
|
||||||
cache_read_price: mTokToPerToken(e.cache_read_price),
|
mapping[key] = ''
|
||||||
image_output_price: mTokToPerToken(e.image_output_price),
|
|
||||||
per_request_price: e.per_request_price != null && e.per_request_price !== '' ? Number(e.per_request_price) : null,
|
|
||||||
intervals: formIntervalsToAPI(e.intervals || [])
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function apiPricingToForm(pricing: ChannelModelPricing[]): PricingFormEntry[] {
|
function removeMappingEntry(sectionIdx: number, key: string) {
|
||||||
return pricing.map(p => ({
|
delete form.platforms[sectionIdx].model_mapping[key]
|
||||||
|
}
|
||||||
|
|
||||||
|
function renameMappingKey(sectionIdx: number, oldKey: string, newKey: string) {
|
||||||
|
newKey = newKey.trim()
|
||||||
|
if (!newKey || newKey === oldKey) return
|
||||||
|
const mapping = form.platforms[sectionIdx].model_mapping
|
||||||
|
if (newKey in mapping) return
|
||||||
|
const value = mapping[oldKey]
|
||||||
|
delete mapping[oldKey]
|
||||||
|
mapping[newKey] = value
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Form ↔ API conversion ──
|
||||||
|
function formToAPI(): { group_ids: number[], model_pricing: ChannelModelPricing[], model_mapping: Record<string, Record<string, string>> } {
|
||||||
|
const group_ids: number[] = []
|
||||||
|
const model_pricing: ChannelModelPricing[] = []
|
||||||
|
const model_mapping: Record<string, Record<string, string>> = {}
|
||||||
|
|
||||||
|
for (const section of form.platforms) {
|
||||||
|
group_ids.push(...section.group_ids)
|
||||||
|
|
||||||
|
// Model mapping per platform
|
||||||
|
if (Object.keys(section.model_mapping).length > 0) {
|
||||||
|
model_mapping[section.platform] = { ...section.model_mapping }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Model pricing with platform tag
|
||||||
|
for (const entry of section.model_pricing) {
|
||||||
|
if (entry.models.length === 0) continue
|
||||||
|
model_pricing.push({
|
||||||
|
platform: section.platform,
|
||||||
|
models: entry.models,
|
||||||
|
billing_mode: entry.billing_mode,
|
||||||
|
input_price: mTokToPerToken(entry.input_price),
|
||||||
|
output_price: mTokToPerToken(entry.output_price),
|
||||||
|
cache_write_price: mTokToPerToken(entry.cache_write_price),
|
||||||
|
cache_read_price: mTokToPerToken(entry.cache_read_price),
|
||||||
|
image_output_price: mTokToPerToken(entry.image_output_price),
|
||||||
|
per_request_price: entry.per_request_price != null && entry.per_request_price !== '' ? Number(entry.per_request_price) : null,
|
||||||
|
intervals: formIntervalsToAPI(entry.intervals || [])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { group_ids, model_pricing, model_mapping }
|
||||||
|
}
|
||||||
|
|
||||||
|
function apiToForm(channel: Channel): PlatformSection[] {
|
||||||
|
// Build a map: groupID → platform
|
||||||
|
const groupPlatformMap = new Map<number, GroupPlatform>()
|
||||||
|
for (const g of allGroups.value) {
|
||||||
|
groupPlatformMap.set(g.id, g.platform)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine which platforms are active (from groups + pricing + mapping)
|
||||||
|
const activePlatforms = new Set<GroupPlatform>()
|
||||||
|
for (const gid of channel.group_ids || []) {
|
||||||
|
const p = groupPlatformMap.get(gid)
|
||||||
|
if (p) activePlatforms.add(p)
|
||||||
|
}
|
||||||
|
for (const p of channel.model_pricing || []) {
|
||||||
|
if (p.platform) activePlatforms.add(p.platform as GroupPlatform)
|
||||||
|
}
|
||||||
|
for (const p of Object.keys(channel.model_mapping || {})) {
|
||||||
|
if (platformOrder.includes(p as GroupPlatform)) activePlatforms.add(p as GroupPlatform)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build sections in platform order
|
||||||
|
const sections: PlatformSection[] = []
|
||||||
|
for (const platform of platformOrder) {
|
||||||
|
if (!activePlatforms.has(platform)) continue
|
||||||
|
|
||||||
|
const groupIds = (channel.group_ids || []).filter(gid => groupPlatformMap.get(gid) === platform)
|
||||||
|
const mapping = (channel.model_mapping || {})[platform] || {}
|
||||||
|
const pricing = (channel.model_pricing || [])
|
||||||
|
.filter(p => (p.platform || 'anthropic') === platform)
|
||||||
|
.map(p => ({
|
||||||
models: p.models || [],
|
models: p.models || [],
|
||||||
billing_mode: p.billing_mode,
|
billing_mode: p.billing_mode,
|
||||||
input_price: perTokenToMTok(p.input_price),
|
input_price: perTokenToMTok(p.input_price),
|
||||||
@@ -639,32 +755,18 @@ function apiPricingToForm(pricing: ChannelModelPricing[]): PricingFormEntry[] {
|
|||||||
image_output_price: perTokenToMTok(p.image_output_price),
|
image_output_price: perTokenToMTok(p.image_output_price),
|
||||||
per_request_price: p.per_request_price,
|
per_request_price: p.per_request_price,
|
||||||
intervals: apiIntervalsToForm(p.intervals || [])
|
intervals: apiIntervalsToForm(p.intervals || [])
|
||||||
}))
|
} as PricingFormEntry))
|
||||||
|
|
||||||
|
sections.push({
|
||||||
|
platform,
|
||||||
|
collapsed: false,
|
||||||
|
group_ids: groupIds,
|
||||||
|
model_mapping: { ...mapping },
|
||||||
|
model_pricing: pricing
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Model Mapping helpers ──
|
return sections
|
||||||
function addMappingEntry() {
|
|
||||||
// Find a unique key
|
|
||||||
let key = ''
|
|
||||||
let i = 1
|
|
||||||
while (key === '' || key in form.model_mapping) {
|
|
||||||
key = `model-${i}`
|
|
||||||
i++
|
|
||||||
}
|
|
||||||
form.model_mapping[key] = ''
|
|
||||||
}
|
|
||||||
|
|
||||||
function removeMappingEntry(key: string) {
|
|
||||||
delete form.model_mapping[key]
|
|
||||||
}
|
|
||||||
|
|
||||||
function renameMappingKey(oldKey: string, newKey: string) {
|
|
||||||
newKey = newKey.trim()
|
|
||||||
if (!newKey || newKey === oldKey) return
|
|
||||||
if (newKey in form.model_mapping) return // prevent duplicate keys
|
|
||||||
const value = form.model_mapping[oldKey]
|
|
||||||
delete form.model_mapping[oldKey]
|
|
||||||
form.model_mapping[newKey] = value
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Load data ──
|
// ── Load data ──
|
||||||
@@ -732,11 +834,9 @@ function resetForm() {
|
|||||||
form.description = ''
|
form.description = ''
|
||||||
form.status = 'active'
|
form.status = 'active'
|
||||||
form.restrict_models = false
|
form.restrict_models = false
|
||||||
form.group_ids = []
|
|
||||||
form.model_pricing = []
|
|
||||||
form.model_mapping = {}
|
|
||||||
form.billing_model_source = 'requested'
|
form.billing_model_source = 'requested'
|
||||||
groupSearchQuery.value = ''
|
form.platforms = []
|
||||||
|
showPlatformMenu.value = false
|
||||||
}
|
}
|
||||||
|
|
||||||
function openCreateDialog() {
|
function openCreateDialog() {
|
||||||
@@ -752,11 +852,11 @@ function openEditDialog(channel: Channel) {
|
|||||||
form.description = channel.description || ''
|
form.description = channel.description || ''
|
||||||
form.status = channel.status
|
form.status = channel.status
|
||||||
form.restrict_models = channel.restrict_models || false
|
form.restrict_models = channel.restrict_models || false
|
||||||
form.group_ids = [...(channel.group_ids || [])]
|
|
||||||
form.model_pricing = apiPricingToForm(channel.model_pricing || [])
|
|
||||||
form.model_mapping = { ...(channel.model_mapping || {}) }
|
|
||||||
form.billing_model_source = channel.billing_model_source || 'requested'
|
form.billing_model_source = channel.billing_model_source || 'requested'
|
||||||
loadGroups()
|
// Must load groups first so apiToForm can map groupID → platform
|
||||||
|
loadGroups().then(() => {
|
||||||
|
form.platforms = apiToForm(channel)
|
||||||
|
})
|
||||||
showDialog.value = true
|
showDialog.value = true
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -773,14 +873,16 @@ async function handleSubmit() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查模型重复
|
// Check duplicate models across all platform sections
|
||||||
const allModels = form.model_pricing.flatMap(e => e.models.map(m => m.toLowerCase()))
|
const allModels = form.platforms.flatMap(s => s.model_pricing.flatMap(e => e.models.map(m => m.toLowerCase())))
|
||||||
const duplicates = allModels.filter((m, i) => allModels.indexOf(m) !== i)
|
const duplicates = allModels.filter((m, i) => allModels.indexOf(m) !== i)
|
||||||
if (duplicates.length > 0) {
|
if (duplicates.length > 0) {
|
||||||
appStore.showError(t('admin.channels.duplicateModels', `模型 "${duplicates[0]}" 在多个定价条目中重复`))
|
appStore.showError(t('admin.channels.duplicateModels', `模型 "${duplicates[0]}" 在多个定价条目中重复`))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const { group_ids, model_pricing, model_mapping } = formToAPI()
|
||||||
|
|
||||||
submitting.value = true
|
submitting.value = true
|
||||||
try {
|
try {
|
||||||
if (editingChannel.value) {
|
if (editingChannel.value) {
|
||||||
@@ -788,9 +890,9 @@ async function handleSubmit() {
|
|||||||
name: form.name.trim(),
|
name: form.name.trim(),
|
||||||
description: form.description.trim() || undefined,
|
description: form.description.trim() || undefined,
|
||||||
status: form.status,
|
status: form.status,
|
||||||
group_ids: form.group_ids,
|
group_ids,
|
||||||
model_pricing: formPricingToAPI(),
|
model_pricing,
|
||||||
model_mapping: Object.keys(form.model_mapping).length > 0 ? form.model_mapping : undefined,
|
model_mapping: Object.keys(model_mapping).length > 0 ? model_mapping : undefined,
|
||||||
billing_model_source: form.billing_model_source,
|
billing_model_source: form.billing_model_source,
|
||||||
restrict_models: form.restrict_models
|
restrict_models: form.restrict_models
|
||||||
}
|
}
|
||||||
@@ -800,9 +902,9 @@ async function handleSubmit() {
|
|||||||
const req: CreateChannelRequest = {
|
const req: CreateChannelRequest = {
|
||||||
name: form.name.trim(),
|
name: form.name.trim(),
|
||||||
description: form.description.trim() || undefined,
|
description: form.description.trim() || undefined,
|
||||||
group_ids: form.group_ids,
|
group_ids,
|
||||||
model_pricing: formPricingToAPI(),
|
model_pricing,
|
||||||
model_mapping: Object.keys(form.model_mapping).length > 0 ? form.model_mapping : undefined,
|
model_mapping: Object.keys(model_mapping).length > 0 ? model_mapping : undefined,
|
||||||
billing_model_source: form.billing_model_source,
|
billing_model_source: form.billing_model_source,
|
||||||
restrict_models: form.restrict_models
|
restrict_models: form.restrict_models
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user