feat(admin): 用量记录页新增"用户 Token 排行"面板
- 在 /admin/usage 新增按用户聚合的 Token 排行表(输入/输出/缓存/总 Token、请求数、费用) - 支持按列排序、邮箱搜索、Top N (20/50/100/200),点击行下钻到该用户 - 复用现有筛选(用户/时间/模型/分组等)与既有 KPI 卡片、逐条日志 - 后端对 /admin/dashboard/user-breakdown 做加法扩展(向后兼容): - UserBreakdownItem 增加 input_tokens/output_tokens/cache_tokens - 新增 sort_by(白名单排序,防注入,缺省仍按 actual_cost) - 新增 sort_by 转发单元测试;更新 UsageView.spec 稳定桩 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
64fdc11ec4
commit
b062b36646
11 files changed
+277
-11
No files matched your search
@@ -675,6 +675,9 @@ func (h *DashboardHandler) GetUserBreakdown(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// sort_by 由 repo 层 allowlist 校验;非法值静默回退默认排序(actual_cost)。
|
||||
dim.SortBy = strings.TrimSpace(c.Query("sort_by"))
|
||||
|
||||
limit := 50
|
||||
if v := c.Query("limit"); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 && n <= 200 {
|
||||
|
||||
@@ -59,7 +59,21 @@ func TestGetUserBreakdown_GroupIDFilter(t *testing.T) {
|
||||
require.Equal(t, int64(42), repo.capturedDim.GroupID)
|
||||
require.Empty(t, repo.capturedDim.Model)
|
||||
require.Empty(t, repo.capturedDim.Endpoint)
|
||||
require.Equal(t, 50, repo.capturedLimit) // default limit
|
||||
require.Equal(t, 50, repo.capturedLimit) // default limit
|
||||
require.Empty(t, repo.capturedDim.SortBy) // no sort_by => empty (repo falls back to default)
|
||||
}
|
||||
|
||||
func TestGetUserBreakdown_SortBy(t *testing.T) {
|
||||
repo := &userBreakdownRepoCapture{}
|
||||
router := newUserBreakdownRouter(repo)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet,
|
||||
"/admin/dashboard/user-breakdown?start_date=2026-03-01&end_date=2026-03-16&sort_by=total_tokens", nil)
|
||||
w := httptest.NewRecorder()
|
||||
router.ServeHTTP(w, req)
|
||||
|
||||
require.Equal(t, http.StatusOK, w.Code)
|
||||
require.Equal(t, "total_tokens", repo.capturedDim.SortBy)
|
||||
}
|
||||
|
||||
func TestGetUserBreakdown_ModelFilter(t *testing.T) {
|
||||
|
||||
@@ -164,13 +164,16 @@ type UserSpendingRankingResponse struct {
|
||||
|
||||
// UserBreakdownItem represents per-user usage breakdown within a dimension (group, model, endpoint).
|
||||
type UserBreakdownItem struct {
|
||||
UserID int64 `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Requests int64 `json:"requests"`
|
||||
TotalTokens int64 `json:"total_tokens"`
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost"` // 账号成本
|
||||
UserID int64 `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Requests int64 `json:"requests"`
|
||||
InputTokens int64 `json:"input_tokens"` // 输入 token 累计
|
||||
OutputTokens int64 `json:"output_tokens"` // 输出 token 累计
|
||||
CacheTokens int64 `json:"cache_tokens"` // 缓存创建 + 读取 token 累计
|
||||
TotalTokens int64 `json:"total_tokens"` // 输入+输出+缓存 token 累计
|
||||
Cost float64 `json:"cost"` // 标准计费
|
||||
ActualCost float64 `json:"actual_cost"` // 实际扣除
|
||||
AccountCost float64 `json:"account_cost"` // 账号成本
|
||||
}
|
||||
|
||||
// UserBreakdownDimension specifies the dimension to filter for user breakdown.
|
||||
@@ -187,6 +190,8 @@ type UserBreakdownDimension struct {
|
||||
RequestType *int16 // filter by request_type (non-nil to enable)
|
||||
Stream *bool // filter by stream flag (non-nil to enable)
|
||||
BillingType *int8 // filter by billing_type (non-nil to enable)
|
||||
// SortBy 指定排序列(空 = 默认按 actual_cost)。合法值由 repo 层 allowlist 校验。
|
||||
SortBy string
|
||||
}
|
||||
|
||||
// APIKeyUsageTrendPoint represents API key usage trend data point
|
||||
|
||||
@@ -603,6 +603,9 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
COALESCE(ul.user_id, 0) as user_id,
|
||||
COALESCE(u.email, '') as email,
|
||||
COUNT(*) as requests,
|
||||
COALESCE(SUM(ul.input_tokens), 0) as input_tokens,
|
||||
COALESCE(SUM(ul.output_tokens), 0) as output_tokens,
|
||||
COALESCE(SUM(ul.cache_creation_tokens + ul.cache_read_tokens), 0) as cache_tokens,
|
||||
COALESCE(SUM(ul.input_tokens + ul.output_tokens + ul.cache_creation_tokens + ul.cache_read_tokens), 0) as total_tokens,
|
||||
COALESCE(SUM(ul.total_cost), 0) as cost,
|
||||
COALESCE(SUM(ul.actual_cost), 0) as actual_cost,
|
||||
@@ -651,7 +654,13 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
args = append(args, *dim.BillingType)
|
||||
}
|
||||
|
||||
query += " GROUP BY ul.user_id, u.email ORDER BY actual_cost DESC"
|
||||
// ORDER BY 列来自固定 allowlist(非用户原样字符串),避免 SQL 注入。
|
||||
orderBy := "actual_cost"
|
||||
switch dim.SortBy {
|
||||
case "total_tokens", "input_tokens", "output_tokens", "cache_tokens", "requests", "cost", "actual_cost":
|
||||
orderBy = dim.SortBy
|
||||
}
|
||||
query += " GROUP BY ul.user_id, u.email ORDER BY " + orderBy + " DESC"
|
||||
if limit > 0 {
|
||||
query += fmt.Sprintf(" LIMIT %d", limit)
|
||||
}
|
||||
@@ -674,6 +683,9 @@ func (r *usageLogRepository) GetUserBreakdownStats(ctx context.Context, startTim
|
||||
&row.UserID,
|
||||
&row.Email,
|
||||
&row.Requests,
|
||||
&row.InputTokens,
|
||||
&row.OutputTokens,
|
||||
&row.CacheTokens,
|
||||
&row.TotalTokens,
|
||||
&row.Cost,
|
||||
&row.ActualCost,
|
||||
|
||||
@@ -167,6 +167,8 @@ export interface UserBreakdownParams {
|
||||
endpoint?: string
|
||||
endpoint_type?: 'inbound' | 'upstream' | 'path'
|
||||
limit?: number
|
||||
// Sort column for the ranking (allowlisted server-side; falls back to actual_cost)
|
||||
sort_by?: 'total_tokens' | 'input_tokens' | 'output_tokens' | 'cache_tokens' | 'requests' | 'cost' | 'actual_cost'
|
||||
// Additional filter conditions
|
||||
user_id?: number
|
||||
api_key_id?: number
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
<template>
|
||||
<div class="card p-4">
|
||||
<!-- Header -->
|
||||
<div class="mb-3 flex flex-wrap items-center gap-3">
|
||||
<h3 class="text-sm font-semibold text-gray-800 dark:text-gray-100">
|
||||
{{ t('admin.usage.tokenRanking.title') }}
|
||||
</h3>
|
||||
<span class="text-xs text-gray-400">{{ t('admin.usage.tokenRanking.subtitle') }}</span>
|
||||
<div class="ml-auto flex flex-wrap items-center gap-2">
|
||||
<input
|
||||
v-model="search"
|
||||
type="text"
|
||||
class="input h-8 w-44 text-sm"
|
||||
:placeholder="t('admin.usage.tokenRanking.searchPlaceholder')"
|
||||
/>
|
||||
<div class="w-28">
|
||||
<Select v-model="limit" :options="limitOptions" @change="load" />
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-secondary h-8 px-2"
|
||||
:title="t('common.refresh')"
|
||||
@click="load"
|
||||
>
|
||||
<Icon name="refresh" size="sm" :class="{ 'animate-spin': loading }" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Table -->
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-gray-100 text-xs text-gray-500 dark:border-gray-700 dark:text-gray-400">
|
||||
<th class="w-10 py-2 pr-2 text-left font-medium">#</th>
|
||||
<th class="py-2 pr-2 text-left font-medium">{{ t('admin.usage.tokenRanking.columns.user') }}</th>
|
||||
<th
|
||||
v-for="col in sortableColumns"
|
||||
:key="col.key"
|
||||
class="cursor-pointer select-none py-2 pl-2 text-right font-medium hover:text-primary-500"
|
||||
:class="{ 'text-primary-600 dark:text-primary-400': sortBy === col.key }"
|
||||
@click="setSort(col.key)"
|
||||
>
|
||||
{{ t(col.label) }}
|
||||
<span v-if="sortBy === col.key" aria-hidden="true">↓</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-if="loading">
|
||||
<td :colspan="sortableColumns.length + 2" class="py-8 text-center">
|
||||
<LoadingSpinner />
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-else-if="displayItems.length === 0">
|
||||
<td :colspan="sortableColumns.length + 2" class="py-8 text-center text-sm text-gray-400">
|
||||
{{ t('admin.dashboard.noDataAvailable') }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr
|
||||
v-for="(item, index) in displayItems"
|
||||
v-else
|
||||
:key="item.user_id"
|
||||
class="cursor-pointer border-b border-gray-50 transition-colors hover:bg-gray-50 dark:border-gray-800 dark:hover:bg-dark-700/40"
|
||||
@click="$emit('select-user', item.user_id, item.email)"
|
||||
>
|
||||
<td class="py-2 pr-2 text-gray-400">{{ index + 1 }}</td>
|
||||
<td class="max-w-[220px] truncate py-2 pr-2 text-gray-700 dark:text-gray-200" :title="item.email">
|
||||
{{ item.email || `User #${item.user_id}` }}
|
||||
</td>
|
||||
<td class="py-2 pl-2 text-right text-gray-500 dark:text-gray-400">{{ item.requests.toLocaleString() }}</td>
|
||||
<td class="py-2 pl-2 text-right text-gray-500 dark:text-gray-400">{{ fmtTokens(item.input_tokens) }}</td>
|
||||
<td class="py-2 pl-2 text-right text-gray-500 dark:text-gray-400">{{ fmtTokens(item.output_tokens) }}</td>
|
||||
<td class="py-2 pl-2 text-right text-gray-500 dark:text-gray-400">{{ fmtTokens(item.cache_tokens) }}</td>
|
||||
<td class="py-2 pl-2 text-right font-medium text-gray-800 dark:text-gray-100">{{ fmtTokens(item.total_tokens) }}</td>
|
||||
<td class="py-2 pl-2 text-right text-green-600 dark:text-green-400">${{ fmtCost(item.actual_cost) }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Footer -->
|
||||
<div v-if="!loading && items.length > 0" class="mt-2 text-right text-xs text-gray-400">
|
||||
{{ t('admin.usage.tokenRanking.userCount', { count: displayItems.length }) }}
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { getUserBreakdown, type UserBreakdownParams } from '@/api/admin/dashboard'
|
||||
import { formatCompactNumber, formatCostFixed } from '@/utils/format'
|
||||
import type { UserBreakdownItem } from '@/types'
|
||||
import Select from '@/components/common/Select.vue'
|
||||
import Icon from '@/components/icons/Icon.vue'
|
||||
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
|
||||
|
||||
const props = defineProps<{
|
||||
startDate: string
|
||||
endDate: string
|
||||
filters: Record<string, unknown>
|
||||
model?: string
|
||||
}>()
|
||||
|
||||
defineEmits<{ (e: 'select-user', userId: number, email: string): void }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
type SortKey = NonNullable<UserBreakdownParams['sort_by']>
|
||||
const sortableColumns: { key: SortKey; label: string }[] = [
|
||||
{ key: 'requests', label: 'admin.usage.tokenRanking.columns.requests' },
|
||||
{ key: 'input_tokens', label: 'admin.usage.tokenRanking.columns.inputTokens' },
|
||||
{ key: 'output_tokens', label: 'admin.usage.tokenRanking.columns.outputTokens' },
|
||||
{ key: 'cache_tokens', label: 'admin.usage.tokenRanking.columns.cacheTokens' },
|
||||
{ key: 'total_tokens', label: 'admin.usage.tokenRanking.columns.totalTokens' },
|
||||
{ key: 'actual_cost', label: 'admin.usage.tokenRanking.columns.cost' },
|
||||
]
|
||||
|
||||
const limitOptions = [
|
||||
{ value: 20, label: 'Top 20' },
|
||||
{ value: 50, label: 'Top 50' },
|
||||
{ value: 100, label: 'Top 100' },
|
||||
{ value: 200, label: 'Top 200' },
|
||||
]
|
||||
|
||||
const items = ref<UserBreakdownItem[]>([])
|
||||
const loading = ref(false)
|
||||
const sortBy = ref<SortKey>('total_tokens')
|
||||
const limit = ref(50)
|
||||
const search = ref('')
|
||||
let reqSeq = 0
|
||||
|
||||
const displayItems = computed(() => {
|
||||
const kw = search.value.trim().toLowerCase()
|
||||
if (!kw) return items.value
|
||||
return items.value.filter((u) => (u.email || `user #${u.user_id}`).toLowerCase().includes(kw))
|
||||
})
|
||||
|
||||
const fmtTokens = (v: number) => formatCompactNumber(v)
|
||||
const fmtCost = (v: number) => formatCostFixed(v, 4)
|
||||
|
||||
const setSort = (key: SortKey) => {
|
||||
if (sortBy.value === key) return
|
||||
sortBy.value = key
|
||||
load()
|
||||
}
|
||||
|
||||
const load = async () => {
|
||||
const seq = ++reqSeq
|
||||
loading.value = true
|
||||
try {
|
||||
const params: UserBreakdownParams = {
|
||||
...props.filters,
|
||||
start_date: props.startDate,
|
||||
end_date: props.endDate,
|
||||
sort_by: sortBy.value,
|
||||
limit: limit.value,
|
||||
}
|
||||
if (props.model) params.model = props.model
|
||||
const res = await getUserBreakdown(params)
|
||||
if (seq !== reqSeq) return
|
||||
items.value = res.users || []
|
||||
} catch {
|
||||
if (seq !== reqSeq) return
|
||||
items.value = []
|
||||
} finally {
|
||||
if (seq === reqSeq) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// Reload when the shared filters / date range / model change.
|
||||
watch(
|
||||
() => [props.startDate, props.endDate, props.model, JSON.stringify(props.filters)],
|
||||
() => load(),
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
defineExpose({ reload: load })
|
||||
</script>
|
||||
@@ -483,6 +483,21 @@ export default {
|
||||
clickToViewBalance: 'Click to view balance history',
|
||||
failedToLoadUser: 'Failed to load user info',
|
||||
userDeletedBadge: 'Deleted',
|
||||
tokenRanking: {
|
||||
title: 'User Token Ranking',
|
||||
subtitle: 'Per-user token usage for the current filters and time range; click a row to drill down',
|
||||
searchPlaceholder: 'Search user email...',
|
||||
userCount: '{count} users',
|
||||
columns: {
|
||||
user: 'User',
|
||||
requests: 'Requests',
|
||||
inputTokens: 'Input Tokens',
|
||||
outputTokens: 'Output Tokens',
|
||||
cacheTokens: 'Cache Tokens',
|
||||
totalTokens: 'Total Tokens',
|
||||
cost: 'Cost'
|
||||
}
|
||||
},
|
||||
cleanup: {
|
||||
button: 'Cleanup',
|
||||
title: 'Cleanup Usage Records',
|
||||
|
||||
@@ -544,6 +544,21 @@ export default {
|
||||
clickToViewBalance: '点击查看充值记录',
|
||||
failedToLoadUser: '加载用户信息失败',
|
||||
userDeletedBadge: '已删除',
|
||||
tokenRanking: {
|
||||
title: '用户 Token 排行',
|
||||
subtitle: '按当前筛选与时间范围统计每个用户的 Token 用量,点击行可下钻到该用户',
|
||||
searchPlaceholder: '搜索用户邮箱...',
|
||||
userCount: '共 {count} 位用户',
|
||||
columns: {
|
||||
user: '用户',
|
||||
requests: '请求数',
|
||||
inputTokens: '输入 Token',
|
||||
outputTokens: '输出 Token',
|
||||
cacheTokens: '缓存 Token',
|
||||
totalTokens: '总 Token',
|
||||
cost: '费用'
|
||||
}
|
||||
},
|
||||
cleanup: {
|
||||
button: '清理',
|
||||
title: '清理使用记录',
|
||||
|
||||
@@ -1594,6 +1594,9 @@ export interface UserBreakdownItem {
|
||||
user_id: number
|
||||
email: string
|
||||
requests: number
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
cache_tokens: number
|
||||
total_tokens: number
|
||||
cost: number
|
||||
actual_cost: number
|
||||
|
||||
@@ -109,6 +109,14 @@
|
||||
</button>
|
||||
</div>
|
||||
<div v-show="activeTab === 'usage'">
|
||||
<UserTokenRanking
|
||||
class="mb-4"
|
||||
:start-date="startDate"
|
||||
:end-date="endDate"
|
||||
:filters="breakdownFilters"
|
||||
:model="filters.model"
|
||||
@select-user="handleRankingSelectUser"
|
||||
/>
|
||||
<UsageTable
|
||||
:data="usageLogs"
|
||||
:loading="loading"
|
||||
@@ -167,6 +175,7 @@ import { resolveUsageRequestType, requestTypeToLegacyStream } from '@/utils/usag
|
||||
import AppLayout from '@/components/layout/AppLayout.vue'; import Pagination from '@/components/common/Pagination.vue'; import Select from '@/components/common/Select.vue'; import DateRangePicker from '@/components/common/DateRangePicker.vue'
|
||||
import UsageStatsCards from '@/components/admin/usage/UsageStatsCards.vue'; import UsageFilters from '@/components/admin/usage/UsageFilters.vue'
|
||||
import UsageTable from '@/components/admin/usage/UsageTable.vue'; import UsageExportProgress from '@/components/admin/usage/UsageExportProgress.vue'
|
||||
import UserTokenRanking from '@/components/admin/usage/UserTokenRanking.vue'
|
||||
import UsageCleanupDialog from '@/components/admin/usage/UsageCleanupDialog.vue'
|
||||
import UserBalanceHistoryModal from '@/components/admin/user/UserBalanceHistoryModal.vue'
|
||||
import OpsErrorLogTable from '@/views/admin/ops/components/OpsErrorLogTable.vue'
|
||||
@@ -235,6 +244,12 @@ const handleUserClick = async (userId: number) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Drill down from the per-user token ranking: scope the whole usage view to that user.
|
||||
const handleRankingSelectUser = (userId: number) => {
|
||||
filters.value = { ...filters.value, user_id: userId }
|
||||
applyFilters()
|
||||
}
|
||||
|
||||
const granularityOptions = computed(() => [{ value: 'day', label: t('admin.dashboard.day') }, { value: 'hour', label: t('admin.dashboard.hour') }])
|
||||
// Use local timezone to avoid UTC timezone issues
|
||||
const formatLD = (d: Date) => {
|
||||
|
||||
@@ -163,7 +163,7 @@ describe('admin UsageView distribution metric toggles', () => {
|
||||
UserBalanceHistoryModal: true, AuditLogModal: true, Pagination: true, Select: true,
|
||||
DateRangePicker: true, Icon: true, TokenUsageTrend: true,
|
||||
ModelDistributionChart: ModelDistributionChartStub, GroupDistributionChart: GroupDistributionChartStub,
|
||||
EndpointDistributionChart: true,
|
||||
EndpointDistributionChart: true, UserTokenRanking: true,
|
||||
} },
|
||||
})
|
||||
vi.advanceTimersByTime(120)
|
||||
@@ -201,6 +201,7 @@ describe('admin UsageView distribution metric toggles', () => {
|
||||
TokenUsageTrend: true,
|
||||
ModelDistributionChart: ModelDistributionChartStub,
|
||||
GroupDistributionChart: GroupDistributionChartStub,
|
||||
UserTokenRanking: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -281,6 +282,7 @@ describe('admin UsageView handleUserClick', () => {
|
||||
ModelDistributionChart: true,
|
||||
GroupDistributionChart: true,
|
||||
EndpointDistributionChart: true,
|
||||
UserTokenRanking: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -326,7 +328,7 @@ describe('admin UsageView errors tab filter forwarding', () => {
|
||||
UserBalanceHistoryModal: true, AuditLogModal: true, Pagination: true, Select: true,
|
||||
DateRangePicker: true, Icon: true, TokenUsageTrend: true,
|
||||
ModelDistributionChart: true, GroupDistributionChart: true, EndpointDistributionChart: true,
|
||||
OpsErrorLogTable: true, OpsErrorDetailModal: true,
|
||||
UserTokenRanking: true, OpsErrorLogTable: true, OpsErrorDetailModal: true,
|
||||
} },
|
||||
})
|
||||
vi.advanceTimersByTime(120)
|
||||
|
||||
Reference in new issue
Block a user