From d6120b5d8e05fe4edf54f1575c4dd6e5c7beb856 Mon Sep 17 00:00:00 2001 From: feeeei Date: Mon, 19 Oct 2026 23:31:46 +0800 Subject: [PATCH] =?UTF-8?q?feat(account):=20Vertex=20=E8=B4=A6=E5=8F=B7?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E9=85=8D=E9=A2=9D=E4=B8=8A=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 AccountTypeSupportsQuota / SupportsAccountQuota(apikey/bedrock/service_account) 作为配额账号类型的唯一判定,累加、超限停调度、额度通知、接口输出与计费仓储统一改用; 池模式等其它特性仍只看 IsAPIKeyOrBedrock - service_account 配额语义与 apikey 一致:配置了任一上限才累加,用满停调度,跨阈值发额度通知 - 计费事务中账号已删除时跳过账号配额计数,与 API Key 对称,用户扣费不再整笔回滚 - 账号额度通知只对配置了上限的账号做检查 - 前端创建/编辑弹窗对 Vertex 开放配额设置,设上限后用量列显示配额进度条; 账号类型判断收敛到 supportsAccountQuota --- .../dto/account_quota_service_account_test.go | 78 +++++++ backend/internal/handler/dto/mappers.go | 4 +- .../internal/repository/usage_billing_repo.go | 5 +- .../usage_billing_repo_integration_test.go | 102 +++++++++ .../usage_billing_repo_unit_test.go | 34 +++ backend/internal/service/account.go | 19 +- .../service/account_quota_schedulable_test.go | 42 ++++ .../account_quota_service_account_test.go | 204 ++++++++++++++++++ .../internal/service/gateway_scheduling.go | 4 +- .../internal/service/gateway_usage_billing.go | 11 +- .../account/AccountCapacityCell.vue | 3 +- .../components/account/AccountUsageCell.vue | 26 ++- .../components/account/CreateAccountModal.vue | 9 +- .../components/account/EditAccountModal.vue | 13 +- .../__tests__/AccountUsageCell.spec.ts | 65 ++++++ .../__tests__/EditAccountModal.spec.ts | 20 ++ .../admin/account/AccountActionMenu.vue | 3 +- frontend/src/utils/accountQuota.ts | 6 + 18 files changed, 624 insertions(+), 24 deletions(-) create mode 100644 backend/internal/handler/dto/account_quota_service_account_test.go create mode 100644 backend/internal/service/account_quota_service_account_test.go create mode 100644 frontend/src/utils/accountQuota.ts diff --git a/backend/internal/handler/dto/account_quota_service_account_test.go b/backend/internal/handler/dto/account_quota_service_account_test.go new file mode 100644 index 0000000000..1f6f1ae510 --- /dev/null +++ b/backend/internal/handler/dto/account_quota_service_account_test.go @@ -0,0 +1,78 @@ +package dto + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/require" + + "github.com/Wei-Shaw/sub2api/internal/service" +) + +// service_account 与 apikey 同语义:设了总额度才输出 quota_limit / quota_used。 +func TestAccountFromServiceShallow_ServiceAccountQuota(t *testing.T) { + t.Run("no limit omits quota fields", func(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 1, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{"quota_used": 12.5}, + }) + require.Nil(t, out.QuotaUsed) + require.Nil(t, out.QuotaLimit) + require.Nil(t, out.QuotaDailyLimit) + require.Nil(t, out.QuotaWeeklyLimit) + + payload, err := json.Marshal(out) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + require.NotContains(t, decoded, "quota_used") + require.NotContains(t, decoded, "quota_limit") + }) + + t.Run("with limits outputs limits and usage", func(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 3, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_used": 30.0, + "quota_limit": 100.0, + "quota_daily_limit": 10.0, + }, + }) + require.NotNil(t, out.QuotaLimit) + require.InDelta(t, 100.0, *out.QuotaLimit, 1e-9) + require.NotNil(t, out.QuotaUsed) + require.InDelta(t, 30.0, *out.QuotaUsed, 1e-9) + require.NotNil(t, out.QuotaDailyLimit) + require.NotNil(t, out.QuotaDailyUsed) + }) + + t.Run("lite list item keeps quota fields", func(t *testing.T) { + item := AccountListItemFromAccount(AccountFromServiceShallow(&service.Account{ + ID: 4, + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{"quota_used": 7.25, "quota_limit": 290.0}, + })) + payload, err := json.Marshal(item) + require.NoError(t, err) + var decoded map[string]any + require.NoError(t, json.Unmarshal(payload, &decoded)) + require.InDelta(t, 7.25, decoded["quota_used"], 1e-9) + require.InDelta(t, 290.0, decoded["quota_limit"], 1e-9) + }) +} + +// apikey 维持原语义:未设总额度时不输出 quota_used。 +func TestAccountFromServiceShallow_APIKeyWithoutLimitOmitsQuotaUsed(t *testing.T) { + out := AccountFromServiceShallow(&service.Account{ + ID: 5, + Type: service.AccountTypeAPIKey, + Extra: map[string]any{"quota_used": 5.0}, + }) + require.Nil(t, out.QuotaUsed) + require.Nil(t, out.QuotaLimit) +} diff --git a/backend/internal/handler/dto/mappers.go b/backend/internal/handler/dto/mappers.go index d0c7de939a..a84d493e52 100644 --- a/backend/internal/handler/dto/mappers.go +++ b/backend/internal/handler/dto/mappers.go @@ -341,8 +341,8 @@ func AccountFromServiceShallow(a *service.Account) *Account { } } - // 提取账号配额限制(apikey / bedrock 类型有效) - if a.IsAPIKeyOrBedrock() { + // 提取账号配额限制(apikey / bedrock / service_account 类型有效) + if a.SupportsAccountQuota() { if limit := a.GetQuotaLimit(); limit > 0 { out.QuotaLimit = &limit used := a.GetQuotaUsed() diff --git a/backend/internal/repository/usage_billing_repo.go b/backend/internal/repository/usage_billing_repo.go index bfb1bb0de5..01f5f857f5 100644 --- a/backend/internal/repository/usage_billing_repo.go +++ b/backend/internal/repository/usage_billing_repo.go @@ -202,9 +202,10 @@ func (r *usageBillingRepository) applyUsageBillingEffects(ctx context.Context, t } } - if cmd.AccountQuotaCost > 0 && (strings.EqualFold(cmd.AccountType, service.AccountTypeAPIKey) || strings.EqualFold(cmd.AccountType, service.AccountTypeBedrock)) { + // 账号已不存在时跳过其配额计数,其余结算项不受影响。 + if cmd.AccountQuotaCost > 0 && service.AccountTypeSupportsQuota(cmd.AccountType) { quotaState, err := incrementUsageBillingAccountQuota(ctx, tx, cmd.AccountID, cmd.AccountQuotaCost) - if err != nil { + if err != nil && !errors.Is(err, service.ErrAccountNotFound) { return err } result.QuotaState = quotaState diff --git a/backend/internal/repository/usage_billing_repo_integration_test.go b/backend/internal/repository/usage_billing_repo_integration_test.go index 9f2f0169dc..c7f2e6c528 100644 --- a/backend/internal/repository/usage_billing_repo_integration_test.go +++ b/backend/internal/repository/usage_billing_repo_integration_test.go @@ -217,6 +217,54 @@ func TestUsageBillingRepositoryApply_DeletedAPIKeyStillBillsBalance(t *testing.T require.Equal(t, 1, dedupCount) } +func TestUsageBillingRepositoryApply_DeletedAccountStillBillsBalance(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("usage-billing-deleted-account-user-%d@example.com", time.Now().UnixNano()), + PasswordHash: "hash", + Balance: 100, + }) + apiKey := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, + Key: "sk-usage-billing-deleted-account-" + uuid.NewString(), + Name: "billing-deleted-account", + }) + account := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-deleted-account-" + uuid.NewString(), + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + }) + + _, err := integrationDB.ExecContext(ctx, "UPDATE accounts SET deleted_at = NOW() WHERE id = $1", account.ID) + require.NoError(t, err) + + requestID := uuid.NewString() + result, err := repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: requestID, + APIKeyID: apiKey.ID, + UserID: user.ID, + AccountID: account.ID, + AccountType: service.AccountTypeServiceAccount, + BalanceCost: 1.25, + AccountQuotaCost: 1.25, + }) + require.NoError(t, err) + require.NotNil(t, result) + require.True(t, result.Applied) + require.Nil(t, result.QuotaState) + + var balance float64 + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT balance FROM users WHERE id = $1", user.ID).Scan(&balance)) + require.InDelta(t, 98.75, balance, 0.000001) + + var dedupCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, "SELECT COUNT(*) FROM usage_billing_dedup WHERE request_id = $1 AND api_key_id = $2", requestID, apiKey.ID).Scan(&dedupCount)) + require.Equal(t, 1, dedupCount) +} + func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) { ctx := context.Background() client := testEntClient(t) @@ -254,6 +302,60 @@ func TestUsageBillingRepositoryApply_UpdatesAccountQuota(t *testing.T) { require.InDelta(t, 3.5, quotaUsed, 0.000001) } +// service_account 只设总上限:累加 quota_used;日/周用量只在设置了对应 limit 时累加,未跨越上限不入队调度 outbox。 +func TestUsageBillingRepositoryApply_UpdatesServiceAccountQuota(t *testing.T) { + ctx := context.Background() + client := testEntClient(t) + repo := NewUsageBillingRepository(client, integrationDB) + + user := mustCreateUser(t, client, &service.User{ + Email: fmt.Sprintf("usage-billing-sa-user-%d@example.com", time.Now().UnixNano()), + PasswordHash: "hash", + }) + apiKey := mustCreateApiKey(t, client, &service.APIKey{ + UserID: user.ID, + Key: "sk-usage-billing-sa-" + uuid.NewString(), + Name: "billing-sa", + }) + account := mustCreateAccount(t, client, &service.Account{ + Name: "usage-billing-sa-quota-" + uuid.NewString(), + Platform: service.PlatformGemini, + Type: service.AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_limit": 100.0, + }, + }) + + for _, cost := range []float64{2.25, 1.5} { + _, err := repo.Apply(ctx, &service.UsageBillingCommand{ + RequestID: uuid.NewString(), + APIKeyID: apiKey.ID, + UserID: user.ID, + AccountID: account.ID, + AccountType: service.AccountTypeServiceAccount, + AccountQuotaCost: cost, + }) + require.NoError(t, err) + } + + var quotaUsed float64 + var hasDailyUsed, hasWeeklyUsed bool + require.NoError(t, integrationDB.QueryRowContext(ctx, + "SELECT COALESCE((extra->>'quota_used')::numeric, 0), extra ? 'quota_daily_used', extra ? 'quota_weekly_used' FROM accounts WHERE id = $1", + account.ID, + ).Scan("aUsed, &hasDailyUsed, &hasWeeklyUsed)) + require.InDelta(t, 3.75, quotaUsed, 0.000001) + require.False(t, hasDailyUsed) + require.False(t, hasWeeklyUsed) + + var outboxCount int + require.NoError(t, integrationDB.QueryRowContext(ctx, + "SELECT COUNT(*) FROM scheduler_outbox WHERE event_type = $1 AND account_id = $2", + service.SchedulerOutboxEventAccountChanged, account.ID, + ).Scan(&outboxCount)) + require.Zero(t, outboxCount, "service_account under its limit must not enqueue scheduler outbox") +} + func TestUsageBillingRepositoryApply_EnqueuesSchedulerOutboxOnQuotaCrossing(t *testing.T) { ctx := context.Background() client := testEntClient(t) diff --git a/backend/internal/repository/usage_billing_repo_unit_test.go b/backend/internal/repository/usage_billing_repo_unit_test.go index 40394d819c..a745eb8d73 100644 --- a/backend/internal/repository/usage_billing_repo_unit_test.go +++ b/backend/internal/repository/usage_billing_repo_unit_test.go @@ -22,6 +22,7 @@ const ( userExistsForBillingSQL = `(?s)SELECT 1\s+FROM users\s+WHERE id = \$1 AND deleted_at IS NULL` apiKeyQuotaIncrementSQL = `(?s)UPDATE api_keys\s+SET quota_used = quota_used \+ \$1,.*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` apiKeyRateLimitIncrementSQL = `(?s)UPDATE api_keys SET\s+usage_5h = .*WHERE id = \$2 AND deleted_at IS NULL` + accountQuotaIncrementSQL = `(?s)UPDATE accounts SET extra = .*WHERE id = \$2 AND deleted_at IS NULL\s+RETURNING` ) func TestDeductUsageBillingBalance_UsesSufficientBalanceGuard(t *testing.T) { @@ -137,6 +138,39 @@ func TestApplyUsageBillingEffects_DeletedAPIKeyStillBillsBalance(t *testing.T) { require.NoError(t, mock.ExpectationsWereMet()) } +func TestApplyUsageBillingEffects_DeletedAccountStillBillsBalance(t *testing.T) { + ctx := context.Background() + db, mock, err := sqlmock.New() + require.NoError(t, err) + defer func() { _ = db.Close() }() + + mock.ExpectBegin() + tx, err := db.BeginTx(ctx, nil) + require.NoError(t, err) + mock.ExpectQuery(conditionalBalanceDeductSQL). + WithArgs(10.0, int64(42)). + WillReturnRows(sqlmock.NewRows([]string{"balance"}).AddRow(90.0)) + mock.ExpectQuery(accountQuotaIncrementSQL). + WithArgs(4.0, int64(9)). + WillReturnRows(sqlmock.NewRows([]string{"quota_used", "quota_limit", "quota_daily_used", "quota_daily_limit", "quota_weekly_used", "quota_weekly_limit"})) + mock.ExpectCommit() + + result := &service.UsageBillingApplyResult{Applied: true} + err = (&usageBillingRepository{}).applyUsageBillingEffects(ctx, tx, &service.UsageBillingCommand{ + UserID: 42, + AccountID: 9, + AccountType: service.AccountTypeServiceAccount, + BalanceCost: 10, + AccountQuotaCost: 4, + }, result) + require.NoError(t, err) + require.NotNil(t, result.NewBalance) + require.InDelta(t, 90.0, *result.NewBalance, 0.000001) + require.Nil(t, result.QuotaState) + require.NoError(t, tx.Commit()) + require.NoError(t, mock.ExpectationsWereMet()) +} + func TestApplyUsageBillingEffects_APIKeyCounterErrorStillFails(t *testing.T) { ctx := context.Background() db, mock, err := sqlmock.New() diff --git a/backend/internal/service/account.go b/backend/internal/service/account.go index 06b94b754e..ebc07b8c5c 100644 --- a/backend/internal/service/account.go +++ b/backend/internal/service/account.go @@ -206,7 +206,7 @@ func (a *Account) IsSchedulable() bool { if a.TempUnschedulableUntil != nil && now.Before(*a.TempUnschedulableUntil) { return false } - if a.IsAPIKeyOrBedrock() && a.IsQuotaExceeded() { + if a.SupportsAccountQuota() && a.IsQuotaExceeded() { return false } return true @@ -1378,11 +1378,26 @@ func (a *Account) IsBedrockAPIKey() bool { return a.IsBedrock() && a.GetCredential("auth_mode") == "apikey" } -// IsAPIKeyOrBedrock 返回账号类型是否支持配额和池模式等特性 +// IsAPIKeyOrBedrock 返回账号类型是否支持池模式等特性(账号配额判定见 SupportsAccountQuota) func (a *Account) IsAPIKeyOrBedrock() bool { return a.Type == AccountTypeAPIKey || a.Type == AccountTypeBedrock } +// AccountTypeSupportsQuota 返回账号类型是否支持账号配额(quota_limit 及日/周额度、quota_used 累加、超限停调度)。 +// 在 apikey/bedrock 之外额外放开 Vertex service_account;池模式等其它特性仍只看 IsAPIKeyOrBedrock。 +func AccountTypeSupportsQuota(accountType string) bool { + switch strings.ToLower(accountType) { + case AccountTypeAPIKey, AccountTypeBedrock, AccountTypeServiceAccount: + return true + } + return false +} + +// SupportsAccountQuota 返回账号是否支持账号配额,类型集合见 AccountTypeSupportsQuota。 +func (a *Account) SupportsAccountQuota() bool { + return AccountTypeSupportsQuota(a.Type) +} + func (a *Account) IsOpenAI() bool { return a.Platform == PlatformOpenAI } diff --git a/backend/internal/service/account_quota_schedulable_test.go b/backend/internal/service/account_quota_schedulable_test.go index 2895b34c88..dfe34c4fc5 100644 --- a/backend/internal/service/account_quota_schedulable_test.go +++ b/backend/internal/service/account_quota_schedulable_test.go @@ -113,6 +113,48 @@ func TestAccountIsSchedulable_QuotaExceeded(t *testing.T) { }, want: false, }, + { + name: "service_account total quota exceeded", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_limit": 50.0, + "quota_used": 50.0, + }, + }, + want: false, + }, + { + name: "service_account daily quota exceeded", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_daily_limit": 10.0, + "quota_daily_used": 12.0, + "quota_daily_start": now.Add(-1 * time.Hour).Format(time.RFC3339), + }, + }, + want: false, + }, + { + name: "service_account without limit stays schedulable regardless of quota_used", + account: &Account{ + Status: StatusActive, + Schedulable: true, + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Extra: map[string]any{ + "quota_used": 9999.0, + }, + }, + want: true, + }, } for _, tt := range tests { diff --git a/backend/internal/service/account_quota_service_account_test.go b/backend/internal/service/account_quota_service_account_test.go new file mode 100644 index 0000000000..6358f32024 --- /dev/null +++ b/backend/internal/service/account_quota_service_account_test.go @@ -0,0 +1,204 @@ +package service + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestAccountSupportsAccountQuota(t *testing.T) { + tests := []struct { + accountType string + want bool + }{ + {AccountTypeAPIKey, true}, + {AccountTypeBedrock, true}, + {AccountTypeServiceAccount, true}, + {AccountTypeOAuth, false}, + {AccountTypeSetupToken, false}, + {AccountTypeUpstream, false}, + } + for _, tt := range tests { + t.Run(tt.accountType, func(t *testing.T) { + account := &Account{Type: tt.accountType} + require.Equal(t, tt.want, account.SupportsAccountQuota()) + }) + } +} + +// 配额专用判定放开 service_account,不能连带放开池模式等其它 IsAPIKeyOrBedrock 特性。 +func TestServiceAccountQuotaDoesNotWidenPoolMode(t *testing.T) { + account := &Account{ + Platform: PlatformGemini, + Type: AccountTypeServiceAccount, + Credentials: map[string]any{"pool_mode": true}, + } + require.True(t, account.SupportsAccountQuota()) + require.False(t, account.IsAPIKeyOrBedrock()) + require.False(t, account.IsPoolMode()) +} + +func TestShouldUpdateAccountQuota(t *testing.T) { + tests := []struct { + name string + account *Account + totalCost float64 + want bool + }{ + { + name: "apikey without limit does not accumulate", + account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{}}, + totalCost: 1.5, + want: false, + }, + { + name: "apikey with total limit accumulates", + account: &Account{Type: AccountTypeAPIKey, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "bedrock with daily limit accumulates", + account: &Account{Type: AccountTypeBedrock, Extra: map[string]any{"quota_daily_limit": 10.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "service_account without limit does not accumulate", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_used": 30.0}}, + totalCost: 1.5, + want: false, + }, + { + name: "service_account with limit accumulates", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_weekly_limit": 50.0}}, + totalCost: 1.5, + want: true, + }, + { + name: "service_account zero cost does not accumulate", + account: &Account{Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 0, + want: false, + }, + { + name: "oauth with limit is not quota eligible", + account: &Account{Type: AccountTypeOAuth, Extra: map[string]any{"quota_limit": 100.0}}, + totalCost: 1.5, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + p := &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: tt.totalCost}, + Account: tt.account, + } + require.Equal(t, tt.want, p.shouldUpdateAccountQuota()) + }) + } +} + +func TestBuildUsageBillingCommandAccountQuotaCostForServiceAccount(t *testing.T) { + build := func(account *Account) *UsageBillingCommand { + return buildUsageBillingCommand("req-sa-quota", nil, &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2, ActualCost: 3}, + User: &User{ID: 7}, + APIKey: &APIKey{ID: 13}, + Account: account, + AccountRateMultiplier: 1.5, + }) + } + + // service_account 设了上限:AccountQuotaCost = TotalCost × 账号倍率 + cmd := build(&Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}) + require.NotNil(t, cmd) + require.Equal(t, AccountTypeServiceAccount, cmd.AccountType) + require.InDelta(t, 3.0, cmd.AccountQuotaCost, 1e-9) + + // service_account 不设上限:与 apikey 一致不累加 + cmd = build(&Account{ID: 10, Platform: PlatformGemini, Type: AccountTypeServiceAccount}) + require.NotNil(t, cmd) + require.Zero(t, cmd.AccountQuotaCost) +} + +type accountQuotaIncrementRepoStub struct { + AccountRepository + calls []float64 +} + +func (s *accountQuotaIncrementRepoStub) IncrementQuotaUsed(_ context.Context, _ int64, amount float64) error { + s.calls = append(s.calls, amount) + return nil +} + +func TestPostUsageBillingLegacyAccumulatesServiceAccountQuota(t *testing.T) { + repo := &accountQuotaIncrementRepoStub{} + postUsageBilling(context.Background(), &postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + User: &User{ID: 7}, + APIKey: &APIKey{ID: 13}, + Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + AccountRateMultiplier: 1.25, + }, &billingDeps{accountRepo: repo}) + + require.Len(t, repo.calls, 1) + require.InDelta(t, 2.5, repo.calls[0], 1e-9) +} + +type settingGetValueCounter struct { + SettingRepository + calls int +} + +func (s *settingGetValueCounter) GetValue(context.Context, string) (string, error) { + s.calls++ + return "false", nil +} + +// 未设任何上限的账号没有可跨越的阈值,不应逐请求读取通知设置。 +func TestNotifyAccountQuotaSkipsAccountWithoutLimit(t *testing.T) { + tests := []struct { + name string + account *Account + wantCalls int + }{ + { + name: "service_account without limit", + account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount}, + wantCalls: 0, + }, + { + name: "service_account with total limit", + account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + wantCalls: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + settings := &settingGetValueCounter{} + notifyAccountQuota(&postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + Account: tt.account, + AccountRateMultiplier: 1, + }, &billingDeps{ + balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil), + }, nil) + require.Equal(t, tt.wantCalls, settings.calls) + }) + } +} + +// 账号已删除时计数被跳过、无递增后状态,不应回退到快照做阈值判定。 +func TestNotifyAccountQuotaSkipsWhenQuotaIncrementSkipped(t *testing.T) { + settings := &settingGetValueCounter{} + notifyAccountQuota(&postUsageBillingParams{ + Cost: &CostBreakdown{TotalCost: 2}, + Account: &Account{ID: 9, Platform: PlatformGemini, Type: AccountTypeServiceAccount, Extra: map[string]any{"quota_limit": 100.0}}, + AccountRateMultiplier: 1, + }, &billingDeps{ + balanceNotifyService: NewBalanceNotifyService(NewEmailService(settings, nil), settings, nil), + }, &UsageBillingApplyResult{Applied: true}) + require.Zero(t, settings.calls) +} diff --git a/backend/internal/service/gateway_scheduling.go b/backend/internal/service/gateway_scheduling.go index 059d7e2b2c..46df448245 100644 --- a/backend/internal/service/gateway_scheduling.go +++ b/backend/internal/service/gateway_scheduling.go @@ -1309,9 +1309,9 @@ func (s *GatewayService) withWindowCostPrefetch(ctx context.Context, accounts [] } // isAccountSchedulableForQuota 检查账号是否在配额限制内 -// 适用于配置了 quota_limit 的 apikey 和 bedrock 类型账号 +// 适用于配置了 quota_limit 的 apikey、bedrock 和 service_account 类型账号 func (s *GatewayService) isAccountSchedulableForQuota(account *Account) bool { - if !account.IsAPIKeyOrBedrock() { + if !account.SupportsAccountQuota() { return true } return !account.IsQuotaExceeded() diff --git a/backend/internal/service/gateway_usage_billing.go b/backend/internal/service/gateway_usage_billing.go index 84c604fd04..426209b296 100644 --- a/backend/internal/service/gateway_usage_billing.go +++ b/backend/internal/service/gateway_usage_billing.go @@ -137,7 +137,7 @@ func (p *postUsageBillingParams) shouldUpdateRateLimits() bool { } func (p *postUsageBillingParams) shouldUpdateAccountQuota() bool { - return p.Cost.TotalCost > 0 && p.Account.IsAPIKeyOrBedrock() && p.Account.HasAnyQuotaLimit() + return p.Cost.TotalCost > 0 && p.Account.SupportsAccountQuota() && p.Account.HasAnyQuotaLimit() } // postUsageBilling is the legacy fallback billing path used when the unified @@ -541,11 +541,12 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us slog.Error("panic in notifyAccountQuota", "recover", r) } }() - if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.IsAPIKeyOrBedrock() || deps.balanceNotifyService == nil { + if p.Cost.TotalCost <= 0 || p.Account == nil || !p.Account.SupportsAccountQuota() || !p.Account.HasAnyQuotaLimit() || deps.balanceNotifyService == nil { slog.Debug("notifyAccountQuota: skipped", "total_cost", p.Cost.TotalCost, "account_nil", p.Account == nil, - "is_apikey_or_bedrock", p.Account != nil && p.Account.IsAPIKeyOrBedrock(), + "supports_account_quota", p.Account != nil && p.Account.SupportsAccountQuota(), + "has_quota_limit", p.Account != nil && p.Account.HasAnyQuotaLimit(), "service_nil", deps.balanceNotifyService == nil, ) return @@ -554,6 +555,10 @@ func notifyAccountQuota(p *postUsageBillingParams, deps *billingDeps, result *Us var quotaState *AccountQuotaState if result != nil { quotaState = result.QuotaState + // 本应累加却无递增后状态(账号已删除,计数被跳过):没有新用量,不做阈值判定。 + if quotaState == nil && p.shouldUpdateAccountQuota() { + return + } } slog.Debug("notifyAccountQuota: calling CheckAccountQuotaAfterIncrement", "account_id", p.Account.ID, diff --git a/frontend/src/components/account/AccountCapacityCell.vue b/frontend/src/components/account/AccountCapacityCell.vue index 3df5b24b4f..4e89708d87 100644 --- a/frontend/src/components/account/AccountCapacityCell.vue +++ b/frontend/src/components/account/AccountCapacityCell.vue @@ -39,6 +39,7 @@ import { computed } from 'vue' import { useI18n } from 'vue-i18n' import type { Account } from '@/types' +import { supportsAccountQuota } from '@/utils/accountQuota' import CapacityBadge from '@/components/account/CapacityBadge.vue' import QuotaBadge from '@/components/account/QuotaBadge.vue' @@ -176,7 +177,7 @@ const formatCost = (value: number | null | undefined) => { } // ====== 配额 ====== -const isQuotaEligible = computed(() => props.account.type === 'apikey' || props.account.type === 'bedrock') +const isQuotaEligible = computed(() => supportsAccountQuota(props.account.type)) const showDailyQuota = computed(() => isQuotaEligible.value && props.account.quota_daily_limit != null && props.account.quota_daily_limit > 0 diff --git a/frontend/src/components/account/AccountUsageCell.vue b/frontend/src/components/account/AccountUsageCell.vue index 6bf5f12af5..a12527b82b 100644 --- a/frontend/src/components/account/AccountUsageCell.vue +++ b/frontend/src/components/account/AccountUsageCell.vue @@ -554,6 +554,29 @@
+ +
@@ -684,6 +707,7 @@ import { buildOpenAIUsageRefreshKey } from '@/utils/accountUsageRefresh' import { enqueueUsageRequest } from '@/utils/usageLoadQueue' import { formatCompactNumber } from '@/utils/format' import { isOfficialGeminiBaseUrl } from '@/utils/geminiExplicitCache' +import { supportsAccountQuota } from '@/utils/accountQuota' import UsageProgressBar from './UsageProgressBar.vue' import AccountQuotaInfo from './AccountQuotaInfo.vue' import ClaudeResetCreditsCell from './ClaudeResetCreditsCell.vue' @@ -1572,7 +1596,7 @@ const makeQuotaBar = ( } const hasApiKeyQuota = computed(() => { - if (props.account.type !== 'apikey' && props.account.type !== 'bedrock') return false + if (!supportsAccountQuota(props.account.type)) return false return ( (props.account.quota_daily_limit ?? 0) > 0 || (props.account.quota_weekly_limit ?? 0) > 0 || diff --git a/frontend/src/components/account/CreateAccountModal.vue b/frontend/src/components/account/CreateAccountModal.vue index 93deb2f4c3..cb013a4dd3 100644 --- a/frontend/src/components/account/CreateAccountModal.vue +++ b/frontend/src/components/account/CreateAccountModal.vue @@ -2347,9 +2347,9 @@ />
- +
@@ -4203,6 +4203,7 @@ import { parseDateTimeLocalInput } from '@/utils/format' import { createStableObjectKeyResolver } from '@/utils/stableObjectKey' +import { supportsAccountQuota } from '@/utils/accountQuota' import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry' import { VERTEX_LOCATION_OPTIONS } from '@/constants/account' import { @@ -6282,9 +6283,9 @@ const createAccountAndFinish = async ( if (!applyTempUnschedConfig(credentials)) { return } - // Inject quota limits for apikey/bedrock accounts + // Inject quota limits for apikey/bedrock/service_account accounts let finalExtra = withUpstreamRequestIdHeader(extra) - if (type === 'apikey' || type === 'bedrock') { + if (supportsAccountQuota(type)) { const quotaExtra: Record = { ...(finalExtra || {}) } if (editQuotaLimit.value != null && editQuotaLimit.value > 0) { quotaExtra.quota_limit = editQuotaLimit.value diff --git a/frontend/src/components/account/EditAccountModal.vue b/frontend/src/components/account/EditAccountModal.vue index bbddaaf44e..288abd793e 100644 --- a/frontend/src/components/account/EditAccountModal.vue +++ b/frontend/src/components/account/EditAccountModal.vue @@ -2319,9 +2319,9 @@ @update:quotaNotifyTotalThresholdType="quotaNotifyState.total.thresholdType = $event" />
- +
@@ -3316,6 +3316,7 @@ import { } from '@/utils/format' import { extractApiErrorMessage, extractI18nErrorMessage } from '@/utils/apiError' import { createStableObjectKeyResolver } from '@/utils/stableObjectKey' +import { supportsAccountQuota } from '@/utils/accountQuota' import { getAccountExpiryTimestamp } from '@/components/account/accountExpiry' import { allSelectedGroupsEnableLongContextPricing } from '@/components/account/longContextBilling' import { VERTEX_LOCATION_OPTIONS } from '@/constants/account' @@ -4438,8 +4439,8 @@ const syncFormFromAccount = (newAccount: Account | null) => { } } - // Load quota limit for apikey/bedrock accounts (bedrock quota is also loaded in its own branch above) - if (newAccount.type === 'apikey' || newAccount.type === 'bedrock') { + // Load quota limit for apikey/bedrock/service_account accounts (bedrock quota is also loaded in its own branch above) + if (supportsAccountQuota(newAccount.type)) { const quotaVal = extra?.quota_limit as number | undefined editQuotaLimit.value = (quotaVal && quotaVal > 0) ? quotaVal : null const dailyVal = extra?.quota_daily_limit as number | undefined @@ -6016,8 +6017,8 @@ const handleSubmit = async () => { updatePayload.extra = newExtra } - // For apikey/bedrock accounts, handle quota_limit in extra - if (props.account.type === 'apikey' || props.account.type === 'bedrock') { + // For apikey/bedrock/service_account accounts, handle quota_limit in extra + if (supportsAccountQuota(props.account.type)) { const currentExtra = (updatePayload.extra as Record) || (props.account.extra as Record) || {} const newExtra: Record = { ...currentExtra } diff --git a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts index d595102f66..acbf0884ca 100644 --- a/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts +++ b/frontend/src/components/account/__tests__/AccountUsageCell.spec.ts @@ -1715,6 +1715,71 @@ describe('AccountUsageCell', () => { expect(getUsage).not.toHaveBeenCalled() }) + it('Vertex 账号不设上限时不显示配额进度条', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 4011, + platform: 'gemini', + type: 'service_account', + credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' }, + extra: {} + }), + todayStats: { + requests: 3, + tokens: 1200, + cost: 0.42, + standard_cost: 0.42, + user_cost: 0.5 + } + }, + global: { + stubs: { + UsageProgressBar: true, + AccountQuotaInfo: true + } + } + }) + + await flushPromises() + + expect(wrapper.text()).toContain('A $0.42') + expect(wrapper.findAll('usage-progress-bar-stub')).toHaveLength(0) + expect(getUsage).not.toHaveBeenCalled() + }) + + it('Vertex 账号设置了配额上限时显示配额进度条', async () => { + const wrapper = mount(AccountUsageCell, { + props: { + account: makeAccount({ + id: 4012, + platform: 'gemini', + type: 'service_account', + credentials: { tier_id: 'vertex', project_id: 'vertex-proj', location: 'global' }, + extra: { quota_daily_start: new Date().toISOString() }, + quota_used: 123.456, + quota_limit: 500, + quota_daily_limit: 50, + quota_daily_used: 12.5 + }), + todayStats: null, + todayStatsLoading: false + }, + global: { + stubs: { + UsageProgressBar: true, + AccountQuotaInfo: true + } + } + }) + + await flushPromises() + + const bars = wrapper.findAll('usage-progress-bar-stub') + expect(bars.map((bar) => bar.attributes('label'))).toEqual(['1d', 'total']) + expect(getUsage).not.toHaveBeenCalled() + }) + it('Gemini 第三方上游 API Key 按普通 Key 账号展示今日统计与额度,不显示 Gemini 徽章', async () => { const wrapper = mount(AccountUsageCell, { props: { diff --git a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts index 7061bc84d6..9e786042f2 100644 --- a/frontend/src/components/account/__tests__/EditAccountModal.spec.ts +++ b/frontend/src/components/account/__tests__/EditAccountModal.spec.ts @@ -1715,6 +1715,26 @@ describe('EditAccountModal', () => { expect(updateAccountMock).toHaveBeenCalledTimes(1) }) + it('shows quota limit card for Vertex SA account and keeps quota limits on save', async () => { + const account = buildVertexAccount() + account.extra = { quota_limit: 200, quota_daily_limit: 20, quota_used: 35.5 } + updateAccountMock.mockReset() + checkMixedChannelRiskMock.mockReset() + checkMixedChannelRiskMock.mockResolvedValue({ has_risk: false }) + updateAccountMock.mockResolvedValue(account) + + const wrapper = mountModal(account) + expect(wrapper.findComponent({ name: 'QuotaLimitCard' }).exists()).toBe(true) + + await wrapper.get('form#edit-account-form').trigger('submit.prevent') + + expect(updateAccountMock).toHaveBeenCalledTimes(1) + const extra = updateAccountMock.mock.calls[0]?.[1]?.extra + expect(extra?.quota_limit).toBe(200) + expect(extra?.quota_daily_limit).toBe(20) + expect(extra?.quota_weekly_limit).toBeUndefined() + }) + it('blocks Vertex SA save when neither credentials_status nor legacy json indicates existence', async () => { const account = buildVertexAccount() account.credentials = { diff --git a/frontend/src/components/admin/account/AccountActionMenu.vue b/frontend/src/components/admin/account/AccountActionMenu.vue index 0523dcad02..f376cce12d 100644 --- a/frontend/src/components/admin/account/AccountActionMenu.vue +++ b/frontend/src/components/admin/account/AccountActionMenu.vue @@ -68,6 +68,7 @@ import { useResizeObserver, useWindowSize } from '@vueuse/core' import { useI18n } from 'vue-i18n' import { Icon } from '@/components/icons' import type { Account } from '@/types' +import { supportsAccountQuota } from '@/utils/accountQuota' const props = defineProps<{ show: boolean; account: Account | null; anchorRect: DOMRect | null }>() const emit = defineEmits(['close', 'test', 'stats', 'schedule', 'duplicate', 'reauth', 'refresh-token', 'recover-state', 'reset-quota', 'set-privacy', 'create-spark-shadow']) @@ -135,7 +136,7 @@ const isShadow = computed(() => props.account?.parent_account_id != null) const isOpenAIOAuthParent = computed(() => isOpenAIOAuth.value && !isShadow.value) const supportsPrivacy = computed(() => (isAntigravityOAuth.value || isOpenAIOAuth.value) && !isShadow.value) const hasQuotaLimit = computed(() => { - return (props.account?.type === 'apikey' || props.account?.type === 'bedrock') && ( + return supportsAccountQuota(props.account?.type) && ( (props.account?.quota_limit ?? 0) > 0 || (props.account?.quota_daily_limit ?? 0) > 0 || (props.account?.quota_weekly_limit ?? 0) > 0 diff --git a/frontend/src/utils/accountQuota.ts b/frontend/src/utils/accountQuota.ts new file mode 100644 index 0000000000..22c54ccbe2 --- /dev/null +++ b/frontend/src/utils/accountQuota.ts @@ -0,0 +1,6 @@ +import type { AccountType } from '@/types' + +/** 支持账号配额(总/日/周上限、quota_used 累加、超限停调度)的账号类型,与后端 AccountTypeSupportsQuota 一致。 */ +export function supportsAccountQuota(type?: AccountType | null): boolean { + return type === 'apikey' || type === 'bedrock' || type === 'service_account' +}