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:
Birditch
2026-07-09 06:04:22 -04:00
co-authored by Claude Opus 4.8
parent 64fdc11ec4
commit b062b36646
11 changed files with 277 additions and 11 deletions
@@ -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>