diff --git a/.github/scripts/upstream-v0222-red-fixtures.txt b/.github/scripts/upstream-v0222-red-fixtures.txt index 1ce6e1af0098..598e6c463cec 100644 --- a/.github/scripts/upstream-v0222-red-fixtures.txt +++ b/.github/scripts/upstream-v0222-red-fixtures.txt @@ -200,3 +200,8 @@ backend/internal/handler/request_body_read_log_test.go # Probe penalty tests use receipt types absent from historical WS sources. backend/internal/handler/probe_penalty_response_test.go backend/internal/service/account_probe_penalty_test.go + +# Model plaza display currency tests require the candidate display configuration. +backend/internal/service/model_plaza_currency_test.go +backend/internal/service/model_plaza_currency_update_test.go +backend/internal/handler/model_plaza_currency_test.go diff --git a/Makefile b/Makefile index a455b210269c..75004f36c0e3 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,12 @@ .PHONY: build build-backend build-frontend test test-backend test-frontend test-frontend-critical FRONTEND_CRITICAL_VITEST := \ + src/components/settings/ModelPlazaCurrencySettings.spec.ts \ + src/utils/__tests__/plazaCurrency.spec.ts \ + src/components/modelPlaza/__tests__/ModelPlazaContent.currency.spec.ts \ + src/components/modelPlaza/__tests__/PlazaModelPricingTable.spec.ts \ + src/components/modelPlaza/__tests__/PlazaModelPricingTable.video.spec.ts \ + src/components/modelPlaza/__tests__/PlazaGroupSection.spec.ts \ src/components/common/__tests__/Select.spec.ts \ src/components/account/__tests__/AccountUsageCell.spec.ts \ src/views/admin/__tests__/ChannelsView.bedrockCompat.spec.ts \ diff --git a/backend/internal/handler/admin/setting_handler.go b/backend/internal/handler/admin/setting_handler.go index 18ddb5f6ebe2..9c78db852b1d 100644 --- a/backend/internal/handler/admin/setting_handler.go +++ b/backend/internal/handler/admin/setting_handler.go @@ -428,6 +428,8 @@ func (h *SettingHandler) GetSettings(c *gin.Context) { ModelPlazaRequireAuth: settings.ModelPlazaRequireAuth, PluginManagementEnabled: settings.PluginManagementEnabled, ModelPlazaDescription: settings.ModelPlazaDescription, + ModelPlazaUSDToCNYRate: settings.ModelPlazaUSDToCNYRate, + ModelPlazaCurrency: settings.ModelPlazaCurrency, SupportTicketEnabled: settings.SupportTicketEnabled, SupportTicket: settings.SupportTicket, diff --git a/backend/internal/handler/admin/setting_handler_audit.go b/backend/internal/handler/admin/setting_handler_audit.go index 7b606e63e769..7151458b89ca 100644 --- a/backend/internal/handler/admin/setting_handler_audit.go +++ b/backend/internal/handler/admin/setting_handler_audit.go @@ -653,6 +653,12 @@ func diffSettings(before *service.SystemSettings, after *service.SystemSettings, if before.ModelPlazaRequireAuth != after.ModelPlazaRequireAuth { changed = append(changed, "model_plaza_require_auth") } + if !reflect.DeepEqual(before.ModelPlazaCurrency, after.ModelPlazaCurrency) { + changed = append(changed, "model_plaza_currency") + } + if before.ModelPlazaUSDToCNYRate != after.ModelPlazaUSDToCNYRate { + changed = append(changed, "model_plaza_usd_to_cny_rate") + } if before.ModelPlazaDescription != after.ModelPlazaDescription { changed = append(changed, "model_plaza_description") } diff --git a/backend/internal/handler/admin/setting_handler_update.go b/backend/internal/handler/admin/setting_handler_update.go index eefd0f7f95b7..b63d8ee36839 100644 --- a/backend/internal/handler/admin/setting_handler_update.go +++ b/backend/internal/handler/admin/setting_handler_update.go @@ -382,9 +382,11 @@ type UpdateSettingsRequest struct { SubscriptionEnabled *bool `json:"subscription_enabled"` // Model Plaza feature switches + description - ModelPlazaEnabled *bool `json:"model_plaza_enabled"` - ModelPlazaRequireAuth *bool `json:"model_plaza_require_auth"` - ModelPlazaDescription *string `json:"model_plaza_description"` + ModelPlazaEnabled *bool `json:"model_plaza_enabled"` + ModelPlazaRequireAuth *bool `json:"model_plaza_require_auth"` + ModelPlazaDescription *string `json:"model_plaza_description"` + ModelPlazaUSDToCNYRate *float64 `json:"model_plaza_usd_to_cny_rate" binding:"omitempty,gt=0"` + ModelPlazaCurrency *service.ModelPlazaCurrencySettings `json:"model_plaza_currency"` // Plugin management menu visibility switch; plugin runtime is unaffected. PluginManagementEnabled *bool `json:"plugin_management_enabled"` @@ -2397,6 +2399,18 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) { } return previousSettings.ModelPlazaRequireAuth }(), + ModelPlazaCurrency: func() service.ModelPlazaCurrencySettings { + if req.ModelPlazaCurrency != nil { + return *req.ModelPlazaCurrency + } + return previousSettings.ModelPlazaCurrency + }(), + ModelPlazaUSDToCNYRate: func() float64 { + if req.ModelPlazaUSDToCNYRate != nil { + return *req.ModelPlazaUSDToCNYRate + } + return previousSettings.ModelPlazaUSDToCNYRate + }(), ModelPlazaDescription: func() string { if req.ModelPlazaDescription != nil { return *req.ModelPlazaDescription @@ -2890,6 +2904,8 @@ func (h *SettingHandler) UpdateSettings(c *gin.Context) { ModelPlazaEnabled: updatedSettings.ModelPlazaEnabled, ModelPlazaRequireAuth: updatedSettings.ModelPlazaRequireAuth, ModelPlazaDescription: updatedSettings.ModelPlazaDescription, + ModelPlazaUSDToCNYRate: updatedSettings.ModelPlazaUSDToCNYRate, + ModelPlazaCurrency: updatedSettings.ModelPlazaCurrency, PluginManagementEnabled: updatedSettings.PluginManagementEnabled, SupportTicketEnabled: updatedSettings.SupportTicketEnabled, diff --git a/backend/internal/handler/dto/settings.go b/backend/internal/handler/dto/settings.go index 60775ce8e330..c8617cbe1eef 100644 --- a/backend/internal/handler/dto/settings.go +++ b/backend/internal/handler/dto/settings.go @@ -358,10 +358,12 @@ type SystemSettings struct { SubscriptionEnabled bool `json:"subscription_enabled"` // Model Plaza feature (public group/model pricing showcase) - ModelPlazaEnabled bool `json:"model_plaza_enabled"` - ModelPlazaRequireAuth bool `json:"model_plaza_require_auth"` - ModelPlazaDescription string `json:"model_plaza_description"` - PluginManagementEnabled bool `json:"plugin_management_enabled"` + ModelPlazaEnabled bool `json:"model_plaza_enabled"` + ModelPlazaRequireAuth bool `json:"model_plaza_require_auth"` + ModelPlazaDescription string `json:"model_plaza_description"` + ModelPlazaUSDToCNYRate float64 `json:"model_plaza_usd_to_cny_rate"` + ModelPlazaCurrency service.ModelPlazaCurrencySettings `json:"model_plaza_currency"` + PluginManagementEnabled bool `json:"plugin_management_enabled"` // Support tickets ("网站工单") switch + form config SupportTicketEnabled bool `json:"support_ticket_enabled"` diff --git a/backend/internal/handler/model_plaza_currency_test.go b/backend/internal/handler/model_plaza_currency_test.go new file mode 100644 index 000000000000..646a73b1689c --- /dev/null +++ b/backend/internal/handler/model_plaza_currency_test.go @@ -0,0 +1,20 @@ +package handler + +import ( + "github.com/Wei-Shaw/sub2api/internal/service" + "github.com/stretchr/testify/require" + "testing" +) + +func TestModelPlazaCurrencyRulesRespectVisibleModels(t *testing.T) { + settings, err := service.NormalizeModelPlazaCurrency(service.ModelPlazaCurrencySettings{ + OfficialPlatformCurrencies: map[string]string{"visible-platform": "CNY", "hidden-platform": "USD"}, + OfficialModelCurrencies: map[string]string{"visible-model": "CNY", "hidden-model": "USD"}, + }) + require.NoError(t, err) + out := visiblePlazaCurrency(settings, []modelPlazaGroup{{Models: []modelPlazaModel{{Name: "VISIBLE-MODEL", Platform: "visible-platform"}}}}) + require.Equal(t, map[string]string{"visible-platform": "CNY"}, out.OfficialPlatformCurrencies) + require.Equal(t, map[string]string{"visible-model": "CNY"}, out.OfficialModelCurrencies) + require.Len(t, settings.OfficialModelCurrencies, 2, "filtering must not mutate stored rules") + require.Empty(t, visiblePlazaCurrency(settings, nil).OfficialModelCurrencies) +} diff --git a/backend/internal/handler/model_plaza_handler.go b/backend/internal/handler/model_plaza_handler.go index 0dd524360a0e..dd16231c978a 100644 --- a/backend/internal/handler/model_plaza_handler.go +++ b/backend/internal/handler/model_plaza_handler.go @@ -2,6 +2,7 @@ package handler import ( "log/slog" + "strings" "github.com/Wei-Shaw/sub2api/internal/pkg/response" "github.com/Wei-Shaw/sub2api/internal/server/middleware" @@ -102,8 +103,10 @@ type modelPlazaGroup struct { // modelPlazaResponse 广场页响应。 type modelPlazaResponse struct { - Description string `json:"description"` - Groups []modelPlazaGroup `json:"groups"` + Description string `json:"description"` + USDToCNYRate float64 `json:"usd_to_cny_rate"` + Currency service.ModelPlazaCurrencySettings `json:"currency"` + Groups []modelPlazaGroup `json:"groups"` } // Get 返回模型广场数据。 @@ -163,8 +166,10 @@ func (h *ModelPlazaHandler) Get(c *gin.Context) { c.Writer.Header().Add("Vary", "Accept-Language") out := toLocalizedModelPlazaGroups(visible, userRates, c.GetHeader("Accept-Language"), deniedModels) response.Success(c, modelPlazaResponse{ - Description: rt.Description, - Groups: out, + Description: rt.Description, + USDToCNYRate: rt.USDToCNYRate, + Currency: visiblePlazaCurrency(rt.Currency, out), + Groups: out, }) } @@ -280,3 +285,23 @@ func toModelPlazaOfficialPricing(p *service.PlazaOfficialPricing) *modelPlazaOff Intervals: toUserPricingIntervals(p.Intervals), } } + +// Currency override IDs follow the same visibility boundary as the model list. +func visiblePlazaCurrency(settings service.ModelPlazaCurrencySettings, groups []modelPlazaGroup) service.ModelPlazaCurrencySettings { + result := settings + result.OfficialPlatformCurrencies = map[string]string{} + result.OfficialModelCurrencies = map[string]string{} + for _, group := range groups { + for _, model := range group.Models { + platform := strings.ToLower(strings.TrimSpace(model.Platform)) + name := strings.ToLower(strings.TrimSpace(model.Name)) + if currency, ok := settings.OfficialPlatformCurrencies[platform]; ok { + result.OfficialPlatformCurrencies[platform] = currency + } + if currency, ok := settings.OfficialModelCurrencies[name]; ok { + result.OfficialModelCurrencies[name] = currency + } + } + } + return result +} diff --git a/backend/internal/handler/model_plaza_handler_test.go b/backend/internal/handler/model_plaza_handler_test.go index f70edb01e52e..cf718ded6b16 100644 --- a/backend/internal/handler/model_plaza_handler_test.go +++ b/backend/internal/handler/model_plaza_handler_test.go @@ -269,7 +269,7 @@ func TestFilterPlazaVisibleGroups_SubscribedExclusiveGroup(t *testing.T) { type plazaVarySettingRepo struct{ service.SettingRepository } func (plazaVarySettingRepo) GetMultiple(context.Context, []string) (map[string]string, error) { - return map[string]string{service.SettingKeyModelPlazaEnabled: "true"}, nil + return map[string]string{service.SettingKeyModelPlazaEnabled: "true", "model_plaza_usd_to_cny_rate": "7.2"}, nil } type plazaVaryChannelRepo struct{ service.ChannelRepository } @@ -303,5 +303,7 @@ func TestModelPlazaHandler_VaryKeepsCORSOrigin(t *testing.T) { require.Equal(t, origin, w.Header().Get("Access-Control-Allow-Origin")) // 共享缓存需同时按来源与语言区分,否则 A 来源的响应可能被复用给 B。 require.Equal(t, []string{"Origin", "Accept-Language"}, w.Header().Values("Vary")) + require.Contains(t, w.Body.String(), `"usd_to_cny_rate":7.2`) + require.Contains(t, w.Body.String(), `"wallet_currency":"USD"`) } } diff --git a/backend/internal/server/api_contract_test.go b/backend/internal/server/api_contract_test.go index 5cae3b3f9c13..abb2952074ff 100644 --- a/backend/internal/server/api_contract_test.go +++ b/backend/internal/server/api_contract_test.go @@ -1064,6 +1064,8 @@ func TestAPIContracts(t *testing.T) { "model_plaza_enabled": false, "model_plaza_require_auth": false, "model_plaza_description": "", + "model_plaza_usd_to_cny_rate": 7, + "model_plaza_currency": {"wallet_currency":"USD","wallet_unit_value":1,"customer_currency":"USD","official_currency":"USD","official_platform_currencies":{},"official_model_currencies":{}}, "plugin_management_enabled": false, "support_ticket_enabled": false, "support_ticket_config": { @@ -1440,6 +1442,8 @@ func TestAPIContracts(t *testing.T) { "model_plaza_enabled": false, "model_plaza_require_auth": false, "model_plaza_description": "", + "model_plaza_usd_to_cny_rate": 7, + "model_plaza_currency": {"wallet_currency":"USD","wallet_unit_value":1,"customer_currency":"USD","official_currency":"USD","official_platform_currencies":{},"official_model_currencies":{}}, "plugin_management_enabled": false, "support_ticket_enabled": false, "support_ticket_config": { diff --git a/backend/internal/service/domain_constants.go b/backend/internal/service/domain_constants.go index 821323431165..eabfb8b97d2a 100644 --- a/backend/internal/service/domain_constants.go +++ b/backend/internal/service/domain_constants.go @@ -592,7 +592,9 @@ const ( // SettingKeyModelPlazaDescription stores the Markdown blurb rendered at the top of // the Model Plaza page (global pricing notes, exchange rate, promotions, ...). - SettingKeyModelPlazaDescription = "model_plaza_description" + SettingKeyModelPlazaDescription = "model_plaza_description" + SettingKeyModelPlazaUSDToCNYRate = "model_plaza_usd_to_cny_rate" + SettingKeyModelPlazaCurrency = "model_plaza_currency" // SettingKeyPluginManagementEnabled controls sidebar visibility only; it does // not stop or otherwise change already loaded plugin runtimes. diff --git a/backend/internal/service/model_plaza_currency.go b/backend/internal/service/model_plaza_currency.go new file mode 100644 index 000000000000..be14c84b0488 --- /dev/null +++ b/backend/internal/service/model_plaza_currency.go @@ -0,0 +1,105 @@ +package service + +import ( + "encoding/json" + "fmt" + "math" + "strconv" + "strings" +) + +// A configurable display reference, not a live FX quote or a billing rate. +const defaultModelPlazaUSDToCNYRate = 7.0 + +func modelPlazaUSDToCNYRate(raw string) float64 { + rate, err := strconv.ParseFloat(strings.TrimSpace(raw), 64) + if err != nil || rate <= 0 || math.IsNaN(rate) || math.IsInf(rate, 0) { + return defaultModelPlazaUSDToCNYRate + } + return rate +} + +// ModelPlazaCurrencySettings describes display values only. It does not configure payments. +type ModelPlazaCurrencySettings struct { + WalletCurrency string `json:"wallet_currency"` + WalletUnitValue float64 `json:"wallet_unit_value"` + CustomerCurrency string `json:"customer_currency"` + OfficialCurrency string `json:"official_currency"` + OfficialPlatformCurrencies map[string]string `json:"official_platform_currencies"` + OfficialModelCurrencies map[string]string `json:"official_model_currencies"` +} + +func NormalizeModelPlazaCurrency(v ModelPlazaCurrencySettings) (ModelPlazaCurrencySettings, error) { + if strings.TrimSpace(v.WalletCurrency) != "" && v.WalletUnitValue == 0 { + return v, fmt.Errorf("wallet reference value must be positive when its currency is specified") + } + currency := func(raw string) (string, error) { + value := strings.ToUpper(strings.TrimSpace(raw)) + if value == "" { + value = "USD" + } + if value != "USD" && value != "CNY" { + return "", fmt.Errorf("unsupported display currency %q", value) + } + return value, nil + } + var err error + if v.WalletCurrency, err = currency(v.WalletCurrency); err != nil { + return v, err + } + if v.CustomerCurrency, err = currency(v.CustomerCurrency); err != nil { + return v, err + } + if v.OfficialCurrency, err = currency(v.OfficialCurrency); err != nil { + return v, err + } + if v.WalletUnitValue == 0 { + v.WalletUnitValue = 1 + } + if v.WalletUnitValue < 0 || math.IsNaN(v.WalletUnitValue) || math.IsInf(v.WalletUnitValue, 0) { + return v, fmt.Errorf("wallet reference value must be finite and positive") + } + normalizeOverrides := func(input map[string]string) (map[string]string, error) { + if len(input) > 1000 { + return nil, fmt.Errorf("too many currency overrides") + } + out := make(map[string]string, len(input)) + for key, raw := range input { + normalized := strings.ToLower(strings.TrimSpace(key)) + if normalized == "" || len(normalized) > 256 { + return nil, fmt.Errorf("invalid currency override key") + } + if _, exists := out[normalized]; exists { + return nil, fmt.Errorf("duplicate currency override key") + } + if strings.TrimSpace(raw) == "" { + return nil, fmt.Errorf("currency override requires a currency") + } + value, err := currency(raw) + if err != nil { + return nil, err + } + out[normalized] = value + } + return out, nil + } + if v.OfficialPlatformCurrencies, err = normalizeOverrides(v.OfficialPlatformCurrencies); err != nil { + return v, err + } + if v.OfficialModelCurrencies, err = normalizeOverrides(v.OfficialModelCurrencies); err != nil { + return v, err + } + return v, nil +} + +func parseModelPlazaCurrency(raw string) ModelPlazaCurrencySettings { + var v ModelPlazaCurrencySettings + if strings.TrimSpace(raw) != "" && json.Unmarshal([]byte(raw), &v) != nil { + v = ModelPlazaCurrencySettings{} + } + normalized, err := NormalizeModelPlazaCurrency(v) + if err != nil { + normalized, _ = NormalizeModelPlazaCurrency(ModelPlazaCurrencySettings{}) + } + return normalized +} diff --git a/backend/internal/service/model_plaza_currency_test.go b/backend/internal/service/model_plaza_currency_test.go new file mode 100644 index 000000000000..bc10d81479ea --- /dev/null +++ b/backend/internal/service/model_plaza_currency_test.go @@ -0,0 +1,48 @@ +package service + +import ( + "context" + "errors" + "github.com/stretchr/testify/require" + "testing" +) + +func TestModelPlazaCurrencyRuntime(t *testing.T) { + repo := &showcaseRuntimeSettingRepo{values: map[string]string{SettingKeyModelPlazaEnabled: "true"}} + svc := &SettingService{settingRepo: repo} + got := svc.GetModelPlazaRuntime(context.Background()) + require.Equal(t, float64(7), got.USDToCNYRate) + require.Equal(t, "USD", got.Currency.CustomerCurrency) + require.Equal(t, "USD", got.Currency.WalletCurrency) + require.Equal(t, float64(1), got.Currency.WalletUnitValue) + require.Empty(t, got.Currency.OfficialPlatformCurrencies) + repo.values[SettingKeyModelPlazaUSDToCNYRate] = "7.2" + repo.values[SettingKeyModelPlazaCurrency] = `{"wallet_currency":"CNY","wallet_unit_value":0.5,"customer_currency":"CNY","official_currency":"USD","official_platform_currencies":{"DeepSeek":"CNY"},"official_model_currencies":{"Custom/Model":"USD"}}` + repo.values[SettingBalanceRechargeMult] = "100" + got = svc.GetModelPlazaRuntime(context.Background()) + require.Equal(t, float64(7.2), got.USDToCNYRate) + require.Equal(t, float64(0.5), got.Currency.WalletUnitValue, "payment multiplier is not a display valuation") + require.Equal(t, "CNY", got.Currency.OfficialPlatformCurrencies["deepseek"]) + require.Equal(t, "USD", got.Currency.OfficialModelCurrencies["custom/model"]) + require.Nil(t, repo.saved) + repo.readErr = errors.New("unavailable") + require.False(t, svc.GetModelPlazaRuntime(context.Background()).Enabled) +} + +func TestModelPlazaCurrencyValidation(t *testing.T) { + for _, v := range []ModelPlazaCurrencySettings{ + {WalletCurrency: "EUR"}, {WalletCurrency: "USD", WalletUnitValue: 0}, {CustomerCurrency: "invalid"}, {WalletUnitValue: -1}, + {OfficialPlatformCurrencies: map[string]string{"": "CNY"}}, + {OfficialModelCurrencies: map[string]string{"model": "invalid"}}, + {OfficialModelCurrencies: map[string]string{"model": "USD", " Model ": "CNY"}}, + } { + _, err := NormalizeModelPlazaCurrency(v) + require.Error(t, err) + } + for _, raw := range []string{"", "-1", "NaN", "+Inf", "0"} { + require.Equal(t, float64(7), modelPlazaUSDToCNYRate(raw)) + } + for _, raw := range []string{"broken", `{"customer_currency":"invalid"}`} { + require.Equal(t, "USD", parseModelPlazaCurrency(raw).CustomerCurrency) + } +} diff --git a/backend/internal/service/model_plaza_currency_update_test.go b/backend/internal/service/model_plaza_currency_update_test.go new file mode 100644 index 000000000000..7212b7c0f080 --- /dev/null +++ b/backend/internal/service/model_plaza_currency_update_test.go @@ -0,0 +1,28 @@ +//go:build unit + +package service + +import ( + "context" + "github.com/Wei-Shaw/sub2api/internal/config" + "github.com/stretchr/testify/require" + "math" + "strconv" + "testing" +) + +func TestModelPlazaDisplayRateDoesNotWritePaymentSettings(t *testing.T) { + repo := &settingUpdateRepoStub{} + svc := NewSettingService(repo, &config.Config{}) + for _, rate := range []float64{7, 7.2} { + updates, err := svc.buildSystemSettingsUpdates(context.Background(), &SystemSettings{ModelPlazaUSDToCNYRate: rate}) + require.NoError(t, err) + require.Equal(t, strconv.FormatFloat(rate, 'f', -1, 64), updates[SettingKeyModelPlazaUSDToCNYRate]) + require.NotContains(t, updates, SettingBalanceRechargeMult) + require.NotContains(t, updates, SettingSubscriptionUSDToCNYRate) + } + for _, rate := range []float64{-1, math.NaN(), math.Inf(1)} { + _, err := svc.buildSystemSettingsUpdates(context.Background(), &SystemSettings{ModelPlazaUSDToCNYRate: rate}) + require.ErrorContains(t, err, "display rate") + } +} diff --git a/backend/internal/service/setting_parse.go b/backend/internal/service/setting_parse.go index 41fe848f5c26..855374640a3d 100644 --- a/backend/internal/service/setting_parse.go +++ b/backend/internal/service/setting_parse.go @@ -237,6 +237,7 @@ func (s *SettingService) InitializeDefaultSettings(ctx context.Context) error { SettingKeyModelPlazaEnabled: "false", SettingKeyModelPlazaRequireAuth: "false", SettingKeyModelPlazaDescription: "", + SettingKeyModelPlazaUSDToCNYRate: strconv.FormatFloat(defaultModelPlazaUSDToCNYRate, 'f', -1, 64), SettingKeyPluginManagementEnabled: "false", // Support tickets (default disabled; opt-in). A missing config means the defaults. @@ -912,6 +913,8 @@ func (s *SettingService) parseSettings(settings map[string]string) *SystemSettin result.ModelPlazaEnabled = settings[SettingKeyModelPlazaEnabled] == "true" result.ModelPlazaRequireAuth = settings[SettingKeyModelPlazaRequireAuth] == "true" result.ModelPlazaDescription = settings[SettingKeyModelPlazaDescription] + result.ModelPlazaUSDToCNYRate = modelPlazaUSDToCNYRate(settings[SettingKeyModelPlazaUSDToCNYRate]) + result.ModelPlazaCurrency = parseModelPlazaCurrency(settings[SettingKeyModelPlazaCurrency]) result.PluginManagementEnabled = settings[SettingKeyPluginManagementEnabled] == "true" // Support tickets (default: disabled; strict true). A corrupt config is shown as the diff --git a/backend/internal/service/setting_public.go b/backend/internal/service/setting_public.go index 9b5c9095f2b3..c7ee69492574 100644 --- a/backend/internal/service/setting_public.go +++ b/backend/internal/service/setting_public.go @@ -563,9 +563,11 @@ func (s *SettingService) GetAvailableChannelsRuntime(ctx context.Context) Availa // ModelPlazaRuntime is the lightweight view of the model-plaza feature consumed // by the public plaza handler. type ModelPlazaRuntime struct { - Enabled bool - RequireAuth bool - Description string + Enabled bool + RequireAuth bool + Description string + USDToCNYRate float64 + Currency ModelPlazaCurrencySettings } // GetModelPlazaRuntime reads the model-plaza feature switches directly from the @@ -576,14 +578,18 @@ func (s *SettingService) GetModelPlazaRuntime(ctx context.Context) ModelPlazaRun SettingKeyModelPlazaEnabled, SettingKeyModelPlazaRequireAuth, SettingKeyModelPlazaDescription, + SettingKeyModelPlazaUSDToCNYRate, + SettingKeyModelPlazaCurrency, }) if err != nil { return ModelPlazaRuntime{Enabled: false} } return ModelPlazaRuntime{ - Enabled: vals[SettingKeyModelPlazaEnabled] == "true", - RequireAuth: vals[SettingKeyModelPlazaRequireAuth] == "true", - Description: vals[SettingKeyModelPlazaDescription], + Enabled: vals[SettingKeyModelPlazaEnabled] == "true", + RequireAuth: vals[SettingKeyModelPlazaRequireAuth] == "true", + Description: vals[SettingKeyModelPlazaDescription], + USDToCNYRate: modelPlazaUSDToCNYRate(vals[SettingKeyModelPlazaUSDToCNYRate]), + Currency: parseModelPlazaCurrency(vals[SettingKeyModelPlazaCurrency]), } } diff --git a/backend/internal/service/setting_update.go b/backend/internal/service/setting_update.go index 0c45cfa4d883..68cf1a89d766 100644 --- a/backend/internal/service/setting_update.go +++ b/backend/internal/service/setting_update.go @@ -527,6 +527,20 @@ func (s *SettingService) buildSystemSettingsUpdates(ctx context.Context, setting updates[SettingKeyModelPlazaEnabled] = strconv.FormatBool(settings.ModelPlazaEnabled) updates[SettingKeyModelPlazaRequireAuth] = strconv.FormatBool(settings.ModelPlazaRequireAuth) updates[SettingKeyModelPlazaDescription] = settings.ModelPlazaDescription + if settings.ModelPlazaUSDToCNYRate == 0 { + settings.ModelPlazaUSDToCNYRate = defaultModelPlazaUSDToCNYRate + } + if settings.ModelPlazaUSDToCNYRate < 0 || math.IsNaN(settings.ModelPlazaUSDToCNYRate) || math.IsInf(settings.ModelPlazaUSDToCNYRate, 0) { + return nil, infraerrors.BadRequest("INVALID_MODEL_PLAZA_DISPLAY_RATE", "model plaza USD to CNY display rate must be finite and positive") + } + plazaCurrency, err := NormalizeModelPlazaCurrency(settings.ModelPlazaCurrency) + if err != nil { + return nil, infraerrors.BadRequest("INVALID_MODEL_PLAZA_CURRENCY", err.Error()) + } + settings.ModelPlazaCurrency = plazaCurrency + plazaCurrencyJSON, _ := json.Marshal(plazaCurrency) + updates[SettingKeyModelPlazaCurrency] = string(plazaCurrencyJSON) + updates[SettingKeyModelPlazaUSDToCNYRate] = strconv.FormatFloat(settings.ModelPlazaUSDToCNYRate, 'f', -1, 64) updates[SettingKeyPluginManagementEnabled] = strconv.FormatBool(settings.PluginManagementEnabled) // Support tickets switch + form config diff --git a/backend/internal/service/settings_view.go b/backend/internal/service/settings_view.go index f604961b8b44..11afeefd057e 100644 --- a/backend/internal/service/settings_view.go +++ b/backend/internal/service/settings_view.go @@ -242,10 +242,12 @@ type SystemSettings struct { SubscriptionEnabled bool `json:"subscription_enabled"` // Model Plaza feature (public group/model pricing showcase) - ModelPlazaEnabled bool `json:"model_plaza_enabled"` - ModelPlazaRequireAuth bool `json:"model_plaza_require_auth"` - ModelPlazaDescription string `json:"model_plaza_description"` - PluginManagementEnabled bool `json:"plugin_management_enabled"` + ModelPlazaEnabled bool `json:"model_plaza_enabled"` + ModelPlazaRequireAuth bool `json:"model_plaza_require_auth"` + ModelPlazaDescription string `json:"model_plaza_description"` + ModelPlazaUSDToCNYRate float64 `json:"model_plaza_usd_to_cny_rate"` + ModelPlazaCurrency ModelPlazaCurrencySettings `json:"model_plaza_currency"` + PluginManagementEnabled bool `json:"plugin_management_enabled"` // Support tickets ("网站工单") switch + form config SupportTicketEnabled bool `json:"support_ticket_enabled"` diff --git a/docs/model-plaza-currency.md b/docs/model-plaza-currency.md new file mode 100644 index 000000000000..2c7c2f87616d --- /dev/null +++ b/docs/model-plaza-currency.md @@ -0,0 +1,25 @@ +# 模型广场币种展示 + +在「系统设置 → 功能设置 → 模型广场」配置客户折后价币种、官方参考价默认币种、站内额度参考价值,以及 USD/CNY 展示参考汇率。所有字段只影响广场展示,不修改渠道原价、分组或专属倍率、充值、订阅和实际扣费。 + +## 默认与换算 + +未配置时,1 站内额度的参考价值为 1 USD,客户价和官方价都显示美元,保持原有美元价卡的数值。USD/CNY 展示参考汇率默认 7.00,可改为站点采用的值;该值是固定参考值,不是实时外汇报价。 + +客户参考价 = 原价 × 生效倍率 × 每额度参考价值,再在参考价值币种和客户展示币种不同时转换。实际采用分时、阶梯、图片/视频独立倍率等现有规则。官方参考价来源为美元目录,显示人民币时乘展示汇率。 + +例如站点按 ¥1 获得 1 额度运营,可将每额度参考价值设为 1 CNY,客户价币种设为 CNY。账面单价 4.5、分组倍率 0.5 时显示 ¥2.25;不会再乘 7。充值赠送、券和手续费会影响用户购入额度的成本,参考值不代表每位用户实际支付成本。 + +如果站点按真实美元运营,保持默认 1 USD 即可。无需调整充值倍率来改变广场展示。 + +## 官方参考价覆盖规则 + +官方价可以按平台 ID 或模型 ID 单独指定 USD/CNY。模型规则优先于平台规则,其余使用官方默认币种。ID 完整匹配,忽略大小写及首尾空白;不支持通配符,没有预置国家、站点或供应商名单。混合分组使用每个模型实际返回的平台字段。 + +例如保留官方默认 USD,再添加平台 `deepseek` → CNY,该平台官方价显示人民币,其他平台仍显示美元。也可为特定完整模型 ID 设为 USD,覆盖其平台规则。其余平台由站点自行选择,系统不自动推断“国产模型”。 + +## 兼容与回滚 + +设置存储在已有 settings 中:`model_plaza_usd_to_cny_rate` 和 `model_plaza_currency`,不需要数据库迁移。旧客户端省略新字段时保留配置;旧前端忽略广场新增元数据。新前端遇到缺少元数据的旧后端时保留原始数值,并明确区分站内额度和官方 USD。 + +回退应用代码恢复旧展示,新增设置可以保留。修改配置后刷新广场核对金额符号、列标题、参考汇率和额度价值;真实扣费验证应独立进行。 diff --git a/frontend/src/api/admin/settings.ts b/frontend/src/api/admin/settings.ts index 79f4f693e2f2..3733c5aa9429 100644 --- a/frontend/src/api/admin/settings.ts +++ b/frontend/src/api/admin/settings.ts @@ -1,3 +1,4 @@ +import type { PlazaCurrencySettings } from '@/api/modelPlaza'; /** * Admin Settings API endpoints * Handles system settings management for administrators @@ -777,6 +778,8 @@ export interface SystemSettings { model_plaza_enabled: boolean; model_plaza_require_auth: boolean; model_plaza_description: string; + model_plaza_usd_to_cny_rate?: number; + model_plaza_currency?: PlazaCurrencySettings; plugin_management_enabled: boolean; // Support tickets (网站工单) switch + form config @@ -1139,6 +1142,8 @@ export interface UpdateSettingsRequest { model_plaza_enabled?: boolean; model_plaza_require_auth?: boolean; model_plaza_description?: string; + model_plaza_usd_to_cny_rate?: number; + model_plaza_currency?: PlazaCurrencySettings; plugin_management_enabled?: boolean; // Support tickets (网站工单) switch + form config diff --git a/frontend/src/api/modelPlaza.ts b/frontend/src/api/modelPlaza.ts index a390107ce3c1..93025898725c 100644 --- a/frontend/src/api/modelPlaza.ts +++ b/frontend/src/api/modelPlaza.ts @@ -82,7 +82,20 @@ export interface ModelPlazaGroup { models: PlazaModel[] } +export interface PlazaCurrencySettings { + wallet_currency: 'CNY' | 'USD' + wallet_unit_value: number + customer_currency: 'CNY' | 'USD' + official_currency: 'CNY' | 'USD' + official_platform_currencies: Record + official_model_currencies: Record +} + export interface ModelPlazaResponse { + /** Display reference only: CNY per real USD, independent of wallet credits. */ + usd_to_cny_rate?: number + /** Display-only wallet valuation and currency rules, independent of payments. */ + currency?: PlazaCurrencySettings /** 管理员配置的全局价格说明(Markdown)。 */ description: string groups: ModelPlazaGroup[] diff --git a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts index 7f64a9cef5eb..af3d6a4b7f7f 100644 --- a/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts +++ b/frontend/src/components/common/__tests__/NewFeatureBadge.spec.ts @@ -23,6 +23,7 @@ describe('NewFeatureBadge', () => { it.each([ + ['model plaza currency', NEW_FEATURE_NOTICES.modelPlazaCurrency], ['image usage billing', NEW_FEATURE_NOTICES.imageUsageBilling], ['channel UltraFast pricing', NEW_FEATURE_NOTICES.channelUltrafastPricing], ['user live load', NEW_FEATURE_NOTICES.userLiveLoad], diff --git a/frontend/src/components/modelPlaza/ModelPlazaContent.vue b/frontend/src/components/modelPlaza/ModelPlazaContent.vue index 8ae7da49b551..2a25dcb6f369 100644 --- a/frontend/src/components/modelPlaza/ModelPlazaContent.vue +++ b/frontend/src/components/modelPlaza/ModelPlazaContent.vue @@ -6,6 +6,16 @@

{{ t('modelPlaza.description') }}

+
+
+ {{ t('modelPlaza.currency.customerLabel', { currency: priceDisplay.settings.customer_currency }) }} + {{ t('modelPlaza.currency.reference', { rate: exchangeRateLabel }) }} +
+

+ {{ priceDisplay ? t('modelPlaza.currency.explanation', { value: priceDisplay.settings.wallet_unit_value, currency: priceDisplay.settings.wallet_currency }) : t('modelPlaza.currency.unavailable') }} +

+
+
- +
authStore.isAuthenticated) +const priceDisplay = computed(() => { + const usdToCny = props.response?.usd_to_cny_rate + const settings = props.response?.currency + if (!hasPlazaCurrencyRates(usdToCny, settings)) return undefined + return { usdToCny: usdToCny!, settings: settings! } +}) +const exchangeRateLabel = computed(() => priceDisplay.value?.usdToCny.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 6 })) + const selectedPlatform = ref('all') const selectedGroupId = ref('all') const selectedRate = ref('all') diff --git a/frontend/src/components/modelPlaza/PlazaGroupSection.vue b/frontend/src/components/modelPlaza/PlazaGroupSection.vue index f748781fccb8..ccbe4ca868f7 100644 --- a/frontend/src/components/modelPlaza/PlazaGroupSection.vue +++ b/frontend/src/components/modelPlaza/PlazaGroupSection.vue @@ -56,6 +56,7 @@ () const { t } = useI18n() diff --git a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue index 2f149cd3531c..5eab39fc037d 100644 --- a/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue +++ b/frontend/src/components/modelPlaza/PlazaModelPricingTable.vue @@ -23,7 +23,7 @@
- {{ t('modelPlaza.table.paidPrice') }} + {{ t('modelPlaza.table.paidPrice') }} · {{ paidCurrencyLabel }} {{ t('modelPlaza.table.unitPerMillion') }}
@@ -32,7 +32,7 @@ class="border-l border-gray-100 pt-2 text-center dark:border-dark-700/60" >
- {{ t('modelPlaza.table.officialPrice') }} + {{ t('modelPlaza.table.officialPrice') }} · {{ officialCurrencyLabel }} {{ t('modelPlaza.table.unitPerMillion') }}
@@ -80,7 +80,7 @@ - {{ t('imageUsage.minimumBadge', { amount: m.pricing?.image_minimum_charge }) }} + {{ t('modelPlaza.currency.minimumCharge', { amount: formatPlazaPrice(m.pricing?.image_minimum_charge, 1, 'credit', props.priceDisplay) }) }} {{ tierLabel(iv) }} - {{ official(iv.input_price) }} + {{ official(m, iv.input_price) }}
- + - +