Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/scripts/upstream-v0222-red-fixtures.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
6 changes: 6 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -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 \
Expand Down
2 changes: 2 additions & 0 deletions backend/internal/handler/admin/setting_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 6 additions & 0 deletions backend/internal/handler/admin/setting_handler_audit.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
22 changes: 19 additions & 3 deletions backend/internal/handler/admin/setting_handler_update.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 6 additions & 4 deletions backend/internal/handler/dto/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand Down
20 changes: 20 additions & 0 deletions backend/internal/handler/model_plaza_currency_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
33 changes: 29 additions & 4 deletions backend/internal/handler/model_plaza_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 返回模型广场数据。
Expand Down Expand Up @@ -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,
})
}

Expand Down Expand Up @@ -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
}
4 changes: 3 additions & 1 deletion backend/internal/handler/model_plaza_handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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"`)
}
}
4 changes: 4 additions & 0 deletions backend/internal/server/api_contract_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down Expand Up @@ -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": {
Expand Down
4 changes: 3 additions & 1 deletion backend/internal/service/domain_constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
105 changes: 105 additions & 0 deletions backend/internal/service/model_plaza_currency.go
Original file line number Diff line number Diff line change
@@ -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
}
48 changes: 48 additions & 0 deletions backend/internal/service/model_plaza_currency_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
Loading
Loading