diff --git a/backend/cmd/server/wire_gen.go b/backend/cmd/server/wire_gen.go index 2835089f9c..33650eed3b 100644 --- a/backend/cmd/server/wire_gen.go +++ b/backend/cmd/server/wire_gen.go @@ -208,7 +208,7 @@ func initializeApplication(buildInfo handler.BuildInfo) (*Application, error) { openAIReferralClient := repository.NewOpenAIReferralClient(privacyClientFactory) openAIQuotaService := service.ProvideOpenAIQuotaService(accountRepository, proxyRepository, openAITokenProvider, privacyClientFactory, openAIReferralClient, openAIGatewayService) usageCache := service.NewUsageCache() - accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService) + accountUsageService := service.ProvideAccountUsageService(accountRepository, usageLogRepository, claudeUsageFetcher, geminiQuotaService, antigravityQuotaFetcher, grokQuotaFetcher, grokQuotaService, openAIQuotaService, usageCache, identityCache, tlsFingerprintProfileService, openAIGatewayService, opsService) pluginRepository := repository.NewPluginRepository(db) pluginHostInfo := providePluginHostInfo(buildInfo) pluginKVStore := repository.NewPluginKVStore(redisClient) diff --git a/backend/internal/pkg/usagestats/usage_log_types.go b/backend/internal/pkg/usagestats/usage_log_types.go index 9b9c4cb668..7141a9d862 100644 --- a/backend/internal/pkg/usagestats/usage_log_types.go +++ b/backend/internal/pkg/usagestats/usage_log_types.go @@ -340,6 +340,8 @@ type AccountUsageHistory struct { Cost float64 `json:"cost"` // 标准计费(total_cost) ActualCost float64 `json:"actual_cost"` // 账号口径费用(total_cost * account_rate_multiplier) UserCost float64 `json:"user_cost"` // 用户口径费用(actual_cost,受分组倍率影响) + // UpstreamErrors 当日上游错误次数;运维监控关闭时为 nil。 + UpstreamErrors *int64 `json:"upstream_errors,omitempty"` } // AccountUsageSummary represents summary statistics for an account @@ -356,7 +358,10 @@ type AccountUsageSummary struct { AvgDailyRequests float64 `json:"avg_daily_requests"` AvgDailyTokens float64 `json:"avg_daily_tokens"` AvgDurationMs float64 `json:"avg_duration_ms"` - Today *struct { + // 上游错误次数;运维监控关闭时为 nil。 + TotalUpstreamErrors *int64 `json:"total_upstream_errors,omitempty"` + TodayUpstreamErrors *int64 `json:"today_upstream_errors,omitempty"` + Today *struct { Date string `json:"date"` Cost float64 `json:"cost"` UserCost float64 `json:"user_cost"` diff --git a/backend/internal/repository/usage_log_repo_integration_test.go b/backend/internal/repository/usage_log_repo_integration_test.go index e0798b2fb7..e60046b425 100644 --- a/backend/internal/repository/usage_log_repo_integration_test.go +++ b/backend/internal/repository/usage_log_repo_integration_test.go @@ -947,6 +947,43 @@ func (s *UsageLogRepoSuite) TestGetAccountTodayStats() { s.Require().InEpsilon(3.0, stats.UserCost, 0.0001) } +func (s *UsageLogRepoSuite) TestAccountUpstreamErrorCounts() { + account := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-upstream-errors"}) + other := mustCreateAccount(s.T(), s.client, &service.Account{Name: "acc-upstream-errors-other"}) + + today := timezone.Today().Add(1 * time.Hour) + yesterday := today.Add(-24 * time.Hour) + insert := func(accountID int64, owner string, businessLimited bool, statusCode int, createdAt time.Time) { + _, err := s.tx.ExecContext(s.ctx, ` + INSERT INTO ops_error_logs ( + account_id, error_phase, error_type, severity, status_code, error_owner, is_business_limited, created_at + ) VALUES ($1, 'upstream', 'upstream_error', 'P2', $2, $3, $4, $5)`, + accountID, statusCode, owner, businessLimited, createdAt, + ) + s.Require().NoError(err) + } + insert(account.ID, "provider", false, 502, today) + insert(account.ID, "provider", false, 429, today) + // 故障转移后恢复的请求:最终状态码 < 400,仍计为上游错误。 + insert(account.ID, "provider", false, 200, today) + insert(account.ID, "provider", false, 500, yesterday) + insert(account.ID, "client", false, 400, today) + insert(account.ID, "provider", true, 503, today) + insert(other.ID, "provider", false, 500, today) + + counts, err := s.repo.GetAccountUpstreamErrorCountsBatch(s.ctx, []int64{account.ID, 999999}, timezone.Today()) + s.Require().NoError(err) + s.Require().Equal(int64(3), counts[account.ID]) + s.Require().Contains(counts, int64(999999)) + s.Require().Equal(int64(0), counts[999999]) + s.Require().NotContains(counts, other.ID) + + daily, err := s.repo.GetAccountDailyUpstreamErrorCounts(s.ctx, account.ID, timezone.Today().Add(-24*time.Hour), timezone.Today().Add(24*time.Hour)) + s.Require().NoError(err) + s.Require().Equal(int64(3), daily[today.Format("2006-01-02")]) + s.Require().Equal(int64(1), daily[yesterday.Format("2006-01-02")]) +} + func (s *UsageLogRepoSuite) TestDashboardAggregationConsistency() { now := time.Now().UTC().Truncate(time.Second) // 使用固定的时间偏移确保 hour1 和 hour2 在同一天且都在过去 diff --git a/backend/internal/repository/usage_log_repo_stats.go b/backend/internal/repository/usage_log_repo_stats.go index 5dfb74646f..203cb9170d 100644 --- a/backend/internal/repository/usage_log_repo_stats.go +++ b/backend/internal/repository/usage_log_repo_stats.go @@ -387,6 +387,81 @@ func (r *usageLogRepository) GetAccountWindowStatsBatch(ctx context.Context, acc return result, nil } +// accountUpstreamErrorPredicate 与运维看板的上游错误口径一致(不区分 429/529)。 +// ops_error_logs 每个请求一行,account_id 为最终(或最后失败的)账号,故障转移中间尝试不单独计入。 +const accountUpstreamErrorPredicate = `error_owner = 'provider' AND NOT is_business_limited` + +// GetAccountUpstreamErrorCountsBatch 批量统计多个账号自 startTime 起的上游错误次数。 +// 未命中的账号返回 0。 +func (r *usageLogRepository) GetAccountUpstreamErrorCountsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]int64, error) { + result := make(map[int64]int64, len(accountIDs)) + if len(accountIDs) == 0 { + return result, nil + } + + query := ` + SELECT account_id, COUNT(*) + FROM ops_error_logs + WHERE account_id = ANY($1) AND created_at >= $2 + AND ` + accountUpstreamErrorPredicate + ` + GROUP BY account_id + ` + rows, err := r.sql.QueryContext(ctx, query, pq.Array(accountIDs), startTime) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + for rows.Next() { + var accountID, count int64 + if err := rows.Scan(&accountID, &count); err != nil { + return nil, err + } + result[accountID] = count + } + if err := rows.Err(); err != nil { + return nil, err + } + + for _, accountID := range accountIDs { + if _, ok := result[accountID]; !ok { + result[accountID] = 0 + } + } + return result, nil +} + +// GetAccountDailyUpstreamErrorCounts 按日统计账号在 [startTime, endTime) 内的上游错误次数,key 为 YYYY-MM-DD。 +// 日期分组口径与 GetAccountUsageStats 保持一致。 +func (r *usageLogRepository) GetAccountDailyUpstreamErrorCounts(ctx context.Context, accountID int64, startTime, endTime time.Time) (map[string]int64, error) { + query := ` + SELECT TO_CHAR(created_at, 'YYYY-MM-DD') as date, COUNT(*) + FROM ops_error_logs + WHERE account_id = $1 AND created_at >= $2 AND created_at < $3 + AND ` + accountUpstreamErrorPredicate + ` + GROUP BY date + ` + rows, err := r.sql.QueryContext(ctx, query, accountID, startTime, endTime) + if err != nil { + return nil, err + } + defer func() { _ = rows.Close() }() + + result := make(map[string]int64) + for rows.Next() { + var date string + var count int64 + if err := rows.Scan(&date, &count); err != nil { + return nil, err + } + result[date] = count + } + if err := rows.Err(); err != nil { + return nil, err + } + return result, nil +} + // GetGeminiUsageTotalsBatch 批量聚合 Gemini 账号在窗口内的 Pro/Flash 请求与用量。 // 模型分类规则与 service.geminiModelClassFromName 一致:model 包含 flash/lite 视为 flash,其余视为 pro。 func (r *usageLogRepository) GetGeminiUsageTotalsBatch(ctx context.Context, accountIDs []int64, startTime, endTime time.Time) (map[int64]service.GeminiUsageTotals, error) { diff --git a/backend/internal/service/account_usage_service.go b/backend/internal/service/account_usage_service.go index 07272f5bf1..153e1cab4d 100644 --- a/backend/internal/service/account_usage_service.go +++ b/backend/internal/service/account_usage_service.go @@ -9,6 +9,7 @@ import ( "log/slog" "math/rand/v2" "net/http" + "sort" "strings" "sync" "time" @@ -85,6 +86,16 @@ type accountWindowStatsBatchReader interface { GetAccountWindowStatsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]*usagestats.AccountStats, error) } +// accountUpstreamErrorStatsReader 读取 ops_error_logs 中按账号归属的上游错误次数。 +type accountUpstreamErrorStatsReader interface { + GetAccountUpstreamErrorCountsBatch(ctx context.Context, accountIDs []int64, startTime time.Time) (map[int64]int64, error) + GetAccountDailyUpstreamErrorCounts(ctx context.Context, accountID int64, startTime, endTime time.Time) (map[string]int64, error) +} + +type opsMonitoringStatusReader interface { + IsMonitoringEnabled(ctx context.Context) bool +} + // apiUsageCache 缓存从 Anthropic API 获取的使用率数据(utilization, resets_at) // 同时支持缓存错误响应(负缓存),防止 429 等错误导致的重试风暴 type apiUsageCache struct { @@ -150,6 +161,8 @@ type WindowStats struct { Cost float64 `json:"cost"` StandardCost float64 `json:"standard_cost"` UserCost float64 `json:"user_cost"` + // UpstreamErrors 仅今日统计填充;运维监控关闭时为 nil。 + UpstreamErrors *int64 `json:"upstream_errors,omitempty"` } // UsageProgress 使用量进度 @@ -342,6 +355,7 @@ type AccountUsageService struct { tlsFPProfileService *TLSFingerprintProfileService agentIdentityTaskMu sync.Mutex agentIdentityWS agentIdentityWSConnectionInvalidator + opsMonitoring opsMonitoringStatusReader } // NewAccountUsageService 创建AccountUsageService实例 @@ -1535,13 +1549,49 @@ func (s *AccountUsageService) GetTodayStats(ctx context.Context, accountID int64 return nil, fmt.Errorf("get today stats failed: %w", err) } - return &WindowStats{ + result := &WindowStats{ Requests: stats.Requests, Tokens: stats.Tokens, Cost: stats.Cost, StandardCost: stats.StandardCost, UserCost: stats.UserCost, - }, nil + } + s.attachTodayUpstreamErrors(ctx, map[int64]*WindowStats{accountID: result}, []int64{accountID}) + return result, nil +} + +// upstreamErrorStatsReader 返回上游错误统计读取器;运维监控关闭(不再写入错误日志)时返回 nil, +// 调用方据此不下发错误次数,避免前端把“未记录”误显示为 0。 +func (s *AccountUsageService) upstreamErrorStatsReader(ctx context.Context) accountUpstreamErrorStatsReader { + if s.opsMonitoring == nil || !s.opsMonitoring.IsMonitoringEnabled(ctx) { + return nil + } + reader, ok := s.usageLogRepo.(accountUpstreamErrorStatsReader) + if !ok { + return nil + } + return reader +} + +// attachTodayUpstreamErrors 为今日统计补充上游错误次数;查询失败仅记录日志,不影响主统计。 +func (s *AccountUsageService) attachTodayUpstreamErrors(ctx context.Context, result map[int64]*WindowStats, accountIDs []int64) { + reader := s.upstreamErrorStatsReader(ctx) + if reader == nil || len(accountIDs) == 0 { + return + } + counts, err := reader.GetAccountUpstreamErrorCountsBatch(ctx, accountIDs, timezone.Today()) + if err != nil { + slog.Warn("account_today_upstream_errors_query_failed", "accounts", len(accountIDs), "error", err) + return + } + for _, accountID := range accountIDs { + stats := result[accountID] + if stats == nil { + continue + } + count := counts[accountID] + stats.UpstreamErrors = &count + } } // GetTodayStatsBatch 批量获取账号今日统计,优先走批量 SQL,失败时回退单账号查询。 @@ -1581,6 +1631,7 @@ func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs for _, accountID := range uniqueIDs { result[accountID] = windowStatsFromAccountStats(statsByAccount[accountID]) } + s.attachTodayUpstreamErrors(ctx, result, uniqueIDs) return result, nil } } @@ -1610,6 +1661,7 @@ func (s *AccountUsageService) GetTodayStatsBatch(ctx context.Context, accountIDs result[accountID] = &WindowStats{} } } + s.attachTodayUpstreamErrors(ctx, result, uniqueIDs) return result, nil } @@ -1705,9 +1757,52 @@ func (s *AccountUsageService) GetAccountUsageStats(ctx context.Context, accountI if err != nil { return nil, fmt.Errorf("get account usage stats failed: %w", err) } + if reader := s.upstreamErrorStatsReader(ctx); reader != nil && stats != nil { + counts, err := reader.GetAccountDailyUpstreamErrorCounts(ctx, accountID, startTime, endTime) + if err != nil { + slog.Warn("account_daily_upstream_errors_query_failed", "account_id", accountID, "error", err) + } else { + mergeAccountDailyUpstreamErrors(stats, counts, timezone.Now().Format("2006-01-02")) + } + } return stats, nil } +// mergeAccountDailyUpstreamErrors 将按日上游错误次数并入 history:已有日期直接填充, +// 只有错误没有成功请求的日期补入空用量行,保证趋势图不丢点。 +func mergeAccountDailyUpstreamErrors(stats *usagestats.AccountUsageStatsResponse, counts map[string]int64, todayStr string) { + seen := make(map[string]struct{}, len(stats.History)) + for i := range stats.History { + h := &stats.History[i] + count := counts[h.Date] + h.UpstreamErrors = &count + seen[h.Date] = struct{}{} + } + for date, count := range counts { + if _, ok := seen[date]; ok { + continue + } + t, err := time.Parse("2006-01-02", date) + if err != nil { + continue + } + stats.History = append(stats.History, usagestats.AccountUsageHistory{ + Date: date, + Label: t.Format("01/02"), + UpstreamErrors: &count, + }) + } + sort.Slice(stats.History, func(i, j int) bool { return stats.History[i].Date < stats.History[j].Date }) + + var total int64 + for _, count := range counts { + total += count + } + today := counts[todayStr] + stats.Summary.TotalUpstreamErrors = &total + stats.Summary.TodayUpstreamErrors = &today +} + // fetchOAuthUsageRaw 从 Anthropic API 获取原始响应(不构建 UsageInfo) // 如果账号开启了 TLS 指纹,则使用 TLS 指纹伪装 // 如果有缓存的 Fingerprint,则使用缓存的 User-Agent 等信息 diff --git a/backend/internal/service/account_usage_upstream_errors_test.go b/backend/internal/service/account_usage_upstream_errors_test.go new file mode 100644 index 0000000000..3205e686d6 --- /dev/null +++ b/backend/internal/service/account_usage_upstream_errors_test.go @@ -0,0 +1,153 @@ +package service + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/Wei-Shaw/sub2api/internal/pkg/timezone" + "github.com/Wei-Shaw/sub2api/internal/pkg/usagestats" + "github.com/stretchr/testify/require" +) + +type upstreamErrorUsageLogRepoStub struct { + usageBatchLogRepoStub + windowStats map[int64]*usagestats.AccountStats + usageStats *usagestats.AccountUsageStatsResponse + errorCounts map[int64]int64 + dailyCounts map[string]int64 + errorsErr error + batchCalls int + dailyCalls int + batchStartAt time.Time +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountWindowStatsBatch(_ context.Context, _ []int64, _ time.Time) (map[int64]*usagestats.AccountStats, error) { + return r.windowStats, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountTodayStats(context.Context, int64) (*usagestats.AccountStats, error) { + return &usagestats.AccountStats{Requests: 3}, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountUsageStats(context.Context, int64, time.Time, time.Time) (*usagestats.AccountUsageStatsResponse, error) { + return r.usageStats, nil +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountUpstreamErrorCountsBatch(_ context.Context, _ []int64, startTime time.Time) (map[int64]int64, error) { + r.batchCalls++ + r.batchStartAt = startTime + return r.errorCounts, r.errorsErr +} + +func (r *upstreamErrorUsageLogRepoStub) GetAccountDailyUpstreamErrorCounts(context.Context, int64, time.Time, time.Time) (map[string]int64, error) { + r.dailyCalls++ + return r.dailyCounts, r.errorsErr +} + +type opsMonitoringStatusStub bool + +func (s opsMonitoringStatusStub) IsMonitoringEnabled(context.Context) bool { return bool(s) } + +func TestGetTodayStatsBatch_AttachesUpstreamErrorsWhenMonitoringEnabled(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + windowStats: map[int64]*usagestats.AccountStats{1: {Requests: 10}, 2: {Requests: 5}}, + errorCounts: map[int64]int64{1: 4}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + result, err := svc.GetTodayStatsBatch(context.Background(), []int64{1, 2}) + require.NoError(t, err) + require.Equal(t, 1, repo.batchCalls) + require.Equal(t, timezone.Today(), repo.batchStartAt) + require.NotNil(t, result[1].UpstreamErrors) + require.Equal(t, int64(4), *result[1].UpstreamErrors) + require.NotNil(t, result[2].UpstreamErrors) + require.Equal(t, int64(0), *result[2].UpstreamErrors) + require.Equal(t, int64(10), result[1].Requests) +} + +func TestGetTodayStatsBatch_OmitsUpstreamErrorsWhenMonitoringDisabled(t *testing.T) { + for name, monitoring := range map[string]opsMonitoringStatusReader{ + "disabled": opsMonitoringStatusStub(false), + "unwired": nil, + } { + t.Run(name, func(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + windowStats: map[int64]*usagestats.AccountStats{1: {Requests: 10}}, + errorCounts: map[int64]int64{1: 4}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: monitoring} + + result, err := svc.GetTodayStatsBatch(context.Background(), []int64{1}) + require.NoError(t, err) + require.Zero(t, repo.batchCalls) + require.Nil(t, result[1].UpstreamErrors) + }) + } +} + +func TestGetTodayStats_UpstreamErrorQueryFailureKeepsUsageStats(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{errorsErr: errors.New("boom")} + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + result, err := svc.GetTodayStats(context.Background(), 1) + require.NoError(t, err) + require.Equal(t, int64(3), result.Requests) + require.Nil(t, result.UpstreamErrors) +} + +func TestGetAccountUsageStats_MergesDailyUpstreamErrors(t *testing.T) { + today := timezone.Now().Format("2006-01-02") + yesterday := timezone.Now().AddDate(0, 0, -1).Format("2006-01-02") + twoDaysAgo := timezone.Now().AddDate(0, 0, -2).Format("2006-01-02") + + repo := &upstreamErrorUsageLogRepoStub{ + usageStats: &usagestats.AccountUsageStatsResponse{ + History: []usagestats.AccountUsageHistory{ + {Date: twoDaysAgo, Requests: 7}, + {Date: today, Requests: 2}, + }, + Summary: usagestats.AccountUsageSummary{ActualDaysUsed: 2}, + }, + // yesterday 只有错误、没有成功请求。 + dailyCounts: map[string]int64{yesterday: 5, today: 1}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(true)} + + stats, err := svc.GetAccountUsageStats(context.Background(), 1, time.Now().AddDate(0, 0, -3), time.Now()) + require.NoError(t, err) + require.Len(t, stats.History, 3) + + require.Equal(t, twoDaysAgo, stats.History[0].Date) + require.Equal(t, int64(0), *stats.History[0].UpstreamErrors) + require.Equal(t, yesterday, stats.History[1].Date) + require.Equal(t, int64(0), stats.History[1].Requests) + require.Equal(t, int64(5), *stats.History[1].UpstreamErrors) + require.NotEmpty(t, stats.History[1].Label) + require.Equal(t, today, stats.History[2].Date) + require.Equal(t, int64(1), *stats.History[2].UpstreamErrors) + + require.Equal(t, int64(6), *stats.Summary.TotalUpstreamErrors) + require.Equal(t, int64(1), *stats.Summary.TodayUpstreamErrors) + // 补入的纯错误日期不计入活跃天数。 + require.Equal(t, 2, stats.Summary.ActualDaysUsed) +} + +func TestGetAccountUsageStats_OmitsUpstreamErrorsWhenMonitoringDisabled(t *testing.T) { + repo := &upstreamErrorUsageLogRepoStub{ + usageStats: &usagestats.AccountUsageStatsResponse{ + History: []usagestats.AccountUsageHistory{{Date: "2026-01-01", Requests: 1}}, + }, + dailyCounts: map[string]int64{"2026-01-02": 3}, + } + svc := &AccountUsageService{usageLogRepo: repo, opsMonitoring: opsMonitoringStatusStub(false)} + + stats, err := svc.GetAccountUsageStats(context.Background(), 1, time.Now().AddDate(0, 0, -3), time.Now()) + require.NoError(t, err) + require.Zero(t, repo.dailyCalls) + require.Len(t, stats.History, 1) + require.Nil(t, stats.History[0].UpstreamErrors) + require.Nil(t, stats.Summary.TotalUpstreamErrors) +} diff --git a/backend/internal/service/wire.go b/backend/internal/service/wire.go index efa0c2587e..97ca115e4e 100644 --- a/backend/internal/service/wire.go +++ b/backend/internal/service/wire.go @@ -238,6 +238,7 @@ func ProvideAccountUsageService( identityCache IdentityCache, tlsFPProfileService *TLSFingerprintProfileService, openAIGatewayService *OpenAIGatewayService, + opsService *OpsService, ) *AccountUsageService { service := NewAccountUsageService( accountRepo, @@ -253,6 +254,9 @@ func ProvideAccountUsageService( tlsFPProfileService, ) service.agentIdentityWS = openAIGatewayService + if opsService != nil { + service.opsMonitoring = opsService + } return service } diff --git a/frontend/src/components/account/AccountTodayStatsCell.vue b/frontend/src/components/account/AccountTodayStatsCell.vue index a422d1f000..158bc38a1c 100644 --- a/frontend/src/components/account/AccountTodayStatsCell.vue +++ b/frontend/src/components/account/AccountTodayStatsCell.vue @@ -46,6 +46,25 @@ formatCurrency(props.stats.user_cost) }} + +
+ {{ t('admin.accounts.stats.upstreamErrors') }}: + {{ formatNumber(props.stats.upstream_errors) }} +
diff --git a/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts b/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts new file mode 100644 index 0000000000..6f0d060e05 --- /dev/null +++ b/frontend/src/components/account/__tests__/AccountTodayStatsCell.spec.ts @@ -0,0 +1,46 @@ +import { mount } from '@vue/test-utils' +import { describe, expect, it, vi } from 'vitest' +import AccountTodayStatsCell from '../AccountTodayStatsCell.vue' +import type { WindowStats } from '@/types' + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +const baseStats: WindowStats = { + requests: 10, + tokens: 1000, + cost: 1, + standard_cost: 1, + user_cost: 1 +} + +const mountCell = (stats: WindowStats) => mount(AccountTodayStatsCell, { props: { stats } }) + +describe('AccountTodayStatsCell upstream errors', () => { + it('highlights a non-zero upstream error count', () => { + const row = mountCell({ ...baseStats, upstream_errors: 12 }).get('[data-testid="today-upstream-errors"]') + expect(row.text()).toContain('admin.accounts.stats.upstreamErrors') + expect(row.text()).toContain('12') + expect(row.find('.text-red-600').exists()).toBe(true) + }) + + it('shows zero without highlighting', () => { + const row = mountCell({ ...baseStats, upstream_errors: 0 }).get('[data-testid="today-upstream-errors"]') + expect(row.text()).toContain('0') + expect(row.find('.text-red-600').exists()).toBe(false) + }) + + it('hides the row when the backend omits the count', () => { + expect(mountCell(baseStats).find('[data-testid="today-upstream-errors"]').exists()).toBe(false) + expect( + mountCell({ ...baseStats, upstream_errors: null }).find('[data-testid="today-upstream-errors"]').exists() + ).toBe(false) + }) +}) diff --git a/frontend/src/components/admin/account/AccountStatsModal.vue b/frontend/src/components/admin/account/AccountStatsModal.vue index 4dc84d5e93..1c30e8a3fe 100644 --- a/frontend/src/components/admin/account/AccountStatsModal.vue +++ b/frontend/src/components/admin/account/AccountStatsModal.vue @@ -195,6 +195,24 @@ formatTokens(stats.summary.today?.tokens || 0) }} +
+ {{ + t('admin.accounts.stats.upstreamErrors') + }} + {{ formatNumber(stats.summary.today_upstream_errors) }} +
@@ -346,6 +364,18 @@ >{{ stats.summary.actual_days_used }} / {{ stats.summary.days }} +
+ {{ + t('admin.accounts.stats.totalUpstreamErrors') + }} + {{ + formatNumber(stats.summary.total_upstream_errors) + }} +
@@ -510,6 +540,22 @@ const chartColors = computed(() => ({ const trendChartData = computed(() => { if (!stats.value?.history?.length) return null + // 运维监控关闭时后端不下发 upstream_errors,此时不画这条线。 + const hasUpstreamErrors = stats.value.summary.total_upstream_errors != null + const upstreamErrorDatasets = hasUpstreamErrors + ? [ + { + label: t('admin.accounts.stats.upstreamErrors'), + data: stats.value.history.map((h) => h.upstream_errors ?? 0), + borderColor: '#ef4444', + backgroundColor: 'rgba(239, 68, 68, 0.1)', + fill: false, + tension: 0.3, + yAxisID: 'y1' + } + ] + : [] + return { labels: stats.value.history.map((h) => h.label), datasets: [ @@ -540,7 +586,8 @@ const trendChartData = computed(() => { fill: false, tension: 0.3, yAxisID: 'y1' - } + }, + ...upstreamErrorDatasets ] } }) diff --git a/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts b/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts new file mode 100644 index 0000000000..b1cb5041ac --- /dev/null +++ b/frontend/src/components/admin/account/__tests__/AccountStatsModal.spec.ts @@ -0,0 +1,117 @@ +import { flushPromises, mount } from '@vue/test-utils' +import { beforeEach, describe, expect, it, vi } from 'vitest' +import AccountStatsModal from '../AccountStatsModal.vue' +import type { Account, AccountUsageStatsResponse } from '@/types' + +const { getStats } = vi.hoisted(() => ({ + getStats: vi.fn() +})) + +vi.mock('@/api/admin', () => ({ + adminAPI: { + accounts: { + getStats + } + } +})) + +vi.mock('vue-chartjs', () => ({ + Line: { + props: ['data', 'options'], + template: '
{{ JSON.stringify(data) }}
' + } +})) + +vi.mock('vue-i18n', async () => { + const actual = await vi.importActual('vue-i18n') + return { + ...actual, + useI18n: () => ({ + t: (key: string) => key + }) + } +}) + +function makeStats(withUpstreamErrors: boolean): AccountUsageStatsResponse { + const errors = (value: number) => (withUpstreamErrors ? { upstream_errors: value } : {}) + return { + history: [ + { date: '2026-11-10', label: '11/10', requests: 5, tokens: 100, cost: 1, actual_cost: 1, user_cost: 1, ...errors(0) }, + { date: '2026-11-11', label: '11/11', requests: 0, tokens: 0, cost: 0, actual_cost: 0, user_cost: 0, ...errors(4) }, + { date: '2026-11-12', label: '11/12', requests: 3, tokens: 50, cost: 1, actual_cost: 1, user_cost: 1, ...errors(2) } + ], + summary: { + days: 30, + actual_days_used: 2, + total_cost: 2, + total_user_cost: 2, + total_standard_cost: 2, + total_requests: 8, + total_tokens: 150, + avg_daily_cost: 1, + avg_daily_user_cost: 1, + avg_daily_requests: 4, + avg_daily_tokens: 75, + avg_duration_ms: 100, + ...(withUpstreamErrors ? { total_upstream_errors: 6, today_upstream_errors: 2 } : {}), + today: { date: '2026-11-12', cost: 1, user_cost: 1, requests: 3, tokens: 50 }, + highest_cost_day: null, + highest_request_day: null + }, + models: [], + endpoints: [], + upstream_endpoints: [] + } as AccountUsageStatsResponse +} + +const mountModal = async () => { + const wrapper = mount(AccountStatsModal, { + props: { show: false, account: { id: 1, name: 'acc', status: 'active' } as Account }, + global: { + stubs: { + BaseDialog: { template: '
' }, + ModelDistributionChart: true, + EndpointDistributionChart: true, + LoadingSpinner: true, + Icon: true + } + } + }) + await wrapper.setProps({ show: true }) + await flushPromises() + return wrapper +} + +describe('AccountStatsModal upstream errors', () => { + beforeEach(() => { + getStats.mockReset() + }) + + it('adds an upstream error trend line and summary rows when reported', async () => { + getStats.mockResolvedValue(makeStats(true)) + const wrapper = await mountModal() + + const chartData = JSON.parse(wrapper.get('.chart-data').text()) as { + datasets: Array<{ label: string; data: number[]; yAxisID: string }> + } + const errorDataset = chartData.datasets.find((d) => d.label === 'admin.accounts.stats.upstreamErrors') + expect(errorDataset).toBeDefined() + expect(errorDataset!.data).toEqual([0, 4, 2]) + expect(errorDataset!.yAxisID).toBe('y1') + + expect(wrapper.get('[data-testid="today-upstream-errors"]').text()).toContain('2') + expect(wrapper.get('[data-testid="total-upstream-errors"]').text()).toContain('6') + }) + + it('hides upstream errors when the backend omits them', async () => { + getStats.mockResolvedValue(makeStats(false)) + const wrapper = await mountModal() + + const chartData = JSON.parse(wrapper.get('.chart-data').text()) as { + datasets: Array<{ label: string }> + } + expect(chartData.datasets.map((d) => d.label)).not.toContain('admin.accounts.stats.upstreamErrors') + expect(wrapper.find('[data-testid="today-upstream-errors"]').exists()).toBe(false) + expect(wrapper.find('[data-testid="total-upstream-errors"]').exists()).toBe(false) + }) +}) diff --git a/frontend/src/i18n/locales/en/admin/accounts.ts b/frontend/src/i18n/locales/en/admin/accounts.ts index 469e60210e..bfdfec7f55 100644 --- a/frontend/src/i18n/locales/en/admin/accounts.ts +++ b/frontend/src/i18n/locales/en/admin/accounts.ts @@ -1739,6 +1739,8 @@ export default { todayRequests: 'Today Requests', todayTokens: 'Today Tokens', todayCost: 'Today Cost', + upstreamErrors: 'Upstream Errors', + totalUpstreamErrors: '30-Day Upstream Errors', usageTrend: '30-Day Cost & Request Trend', noData: 'No usage data available for this account' }, diff --git a/frontend/src/i18n/locales/zh/admin/accounts.ts b/frontend/src/i18n/locales/zh/admin/accounts.ts index 1af0ea3644..0d35c23776 100644 --- a/frontend/src/i18n/locales/zh/admin/accounts.ts +++ b/frontend/src/i18n/locales/zh/admin/accounts.ts @@ -1837,6 +1837,8 @@ export default { todayRequests: '今日请求', todayTokens: '今日 Token', todayCost: '今日费用', + upstreamErrors: '上游错误', + totalUpstreamErrors: '30天上游错误', usageTrend: '30天费用与请求趋势', noData: '该账号暂无使用数据' } diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.ts index 25ecc4f66b..ecc221a6da 100644 --- a/frontend/src/types/index.ts +++ b/frontend/src/types/index.ts @@ -1434,6 +1434,7 @@ export interface WindowStats { cost: number // Account cost (account multiplier) standard_cost?: number user_cost?: number + upstream_errors?: number | null // Today stats only; absent when ops monitoring is disabled } export interface UsageProgress { @@ -2317,6 +2318,7 @@ export interface AccountUsageHistory { cost: number actual_cost: number // Account cost (account multiplier) user_cost: number // User/API key billed cost (group multiplier) + upstream_errors?: number | null // Absent when ops monitoring is disabled } export interface AccountUsageSummary { @@ -2332,6 +2334,8 @@ export interface AccountUsageSummary { avg_daily_requests: number avg_daily_tokens: number avg_duration_ms: number + total_upstream_errors?: number | null // Absent when ops monitoring is disabled + today_upstream_errors?: number | null today: { date: string cost: number