refactor: 重新设计用量页布局并新增延迟健康列

- /admin/usage 明细区收进单卡片:三个下划线 tab(用量明细/错误请求/用户排行) + 自适应筛选栏 + 内容
- 用户 Token 排行收编为第三个 tab:去掉独立邮箱搜索,懒挂载,点击行下钻回用量明细并回显用户
- 首Token/耗时合并为延迟列(首字/总耗时):阈值 10s/30s/60s 与 1min/3min/5min 四档配色,色条上下两段短渐变过渡(from-40% to-60%),管理端与用户端 /usage 共用
- 时长格式 ≥1min 简化为 Xm Ys、≥1h 为 Xh Ym
- UsageFilters/UsageTable/OpsErrorLogTable 增加 flat 嵌入模式(默认关闭不影响其他使用方)
This commit is contained in:
shaw
2026-07-09 21:09:40 +08:00
parent e2c731abe4
commit 1a3cc2a787
14 changed files with 478 additions and 169 deletions
@@ -1,5 +1,5 @@
<template>
<div class="card p-6">
<div :class="flat ? 'p-4 sm:p-6' : 'card p-6'">
<!-- Toolbar: left filters (multi-line) + right actions -->
<div class="flex flex-wrap items-end justify-between gap-4">
<!-- Left: filters (allowed to wrap to multiple rows) -->
@@ -133,8 +133,8 @@
<Select v-model="filters.billing_type" :options="billingTypeOptions" @change="emitChange" />
</div>
<!-- Billing Mode Filter (usage only) -->
<div v-if="mode !== 'errors'" class="w-full sm:w-auto sm:min-w-[200px]">
<!-- Billing Mode Filter (usage only;用户排行的 user-breakdown 接口不支持该维度) -->
<div v-if="mode === 'usage'" class="w-full sm:w-auto sm:min-w-[200px]">
<label class="input-label">{{ t('admin.usage.billingMode') }}</label>
<Select v-model="filters.billing_mode" :options="billingModeOptions" @change="emitChange" />
</div>
@@ -174,7 +174,7 @@
{{ t('common.reset') }}
</button>
<slot name="after-reset" />
<template v-if="mode !== 'errors'">
<template v-if="mode === 'usage'">
<button type="button" @click="$emit('cleanup')" class="btn btn-danger">
{{ t('admin.usage.cleanup.button') }}
</button>
@@ -204,13 +204,19 @@ interface Props {
endDate: string
showActions?: boolean
modelOptions?: string[]
/** errors 模式:隐藏用量专属字段/按钮,显示错误类型+状态码(错误请求 tab 用) */
mode?: 'usage' | 'errors'
/**
* errors 模式:隐藏用量专属字段/按钮,显示错误类型+状态码(错误请求 tab 用)
* ranking 模式:同 usage 但隐藏计费模式筛选与清理/导出按钮(用户排行 tab 用)
*/
mode?: 'usage' | 'errors' | 'ranking'
/** 嵌入统一卡片内使用:去掉自身卡片外观 */
flat?: boolean
}
const props = withDefaults(defineProps<Props>(), {
showActions: true,
mode: 'usage'
mode: 'usage',
flat: false
})
const emit = defineEmits([
'update:modelValue',
@@ -485,4 +491,13 @@ onMounted(async () => {
onUnmounted(() => {
document.removeEventListener('click', onDocumentClick)
})
// 供外部(如用户排行下钻)在程序化设置 user_id 后回显选中的用户邮箱
const setUserKeyword = (email: string) => {
userKeyword.value = email
userResults.value = []
showUserDropdown.value = false
}
defineExpose({ setUserKeyword })
</script>
@@ -1,5 +1,5 @@
<template>
<div class="card overflow-hidden">
<div :class="flat ? '' : 'card overflow-hidden'">
<div
v-if="showIpGeoToolbar"
class="flex items-center justify-end gap-2 border-b border-gray-200 px-4 py-2 dark:border-dark-700"
@@ -185,13 +185,24 @@
</div>
</template>
<template #cell-first_token="{ row }">
<span v-if="row.first_token_ms != null" class="text-sm text-gray-600 dark:text-gray-400">{{ formatDuration(row.first_token_ms) }}</span>
<span v-else class="text-sm text-gray-400 dark:text-gray-500">-</span>
</template>
<template #cell-duration="{ row }">
<span class="text-sm text-gray-600 dark:text-gray-400">{{ formatDuration(row.duration_ms) }}</span>
<!-- 合并首字/总耗时的健康度列:左侧色条上端随首字档、下端随总耗时档,中段(40%-60%)短渐变过渡,便于纵向扫视整体健康状况 -->
<template #cell-latency="{ row }">
<div class="flex items-stretch gap-2">
<span
class="w-1 shrink-0 rounded-full"
:class="row.first_token_ms != null
? ['bg-gradient-to-b from-40% to-60%', LATENCY_BAR_FROM_CLASSES[firstTokenSeverity(row.first_token_ms)], LATENCY_BAR_TO_CLASSES[durationSeverity(row.duration_ms ?? 0)]]
: LATENCY_BAR_CLASSES[durationSeverity(row.duration_ms ?? 0)]"
aria-hidden="true"
></span>
<div class="grid grid-cols-[max-content_max-content] items-baseline gap-x-2 gap-y-0.5 text-xs">
<span class="text-gray-400 dark:text-gray-500">{{ t('usage.latencyFirstToken') }}</span>
<span v-if="row.first_token_ms != null" class="font-medium tabular-nums" :class="LATENCY_TEXT_CLASSES[firstTokenSeverity(row.first_token_ms)]">{{ formatDuration(row.first_token_ms) }}</span>
<span v-else class="text-gray-400 dark:text-gray-500">-</span>
<span class="text-gray-400 dark:text-gray-500">{{ t('usage.latencyDuration') }}</span>
<span class="font-medium tabular-nums" :class="LATENCY_TEXT_CLASSES[durationSeverity(row.duration_ms ?? 0)]">{{ formatDuration(row.duration_ms) }}</span>
</div>
</div>
</template>
<template #cell-created_at="{ value }">
@@ -430,6 +441,14 @@ import { formatCacheTokens, formatMultiplier } from '@/utils/formatters'
import { formatTokenPricePerMillion } from '@/utils/usagePricing'
import { getUsageServiceTierLabel } from '@/utils/usageServiceTier'
import { resolveUsageRequestType } from '@/utils/usageRequestType'
import {
LATENCY_BAR_CLASSES,
LATENCY_BAR_FROM_CLASSES,
LATENCY_BAR_TO_CLASSES,
LATENCY_TEXT_CLASSES,
durationSeverity,
firstTokenSeverity,
} from '@/utils/latencyHealth'
import {
BILLING_MODE_TOKEN,
getBillingModeLabel,
@@ -474,6 +493,8 @@ interface Props {
defaultSortOrder?: 'asc' | 'desc'
showAccountBilling?: boolean
showUpstreamEndpoint?: boolean
/** 嵌入统一卡片内使用:去掉自身卡片外观 */
flat?: boolean
}
const props = withDefaults(defineProps<Props>(), {
@@ -482,7 +503,8 @@ const props = withDefaults(defineProps<Props>(), {
defaultSortKey: '',
defaultSortOrder: 'asc',
showAccountBilling: true,
showUpstreamEndpoint: true
showUpstreamEndpoint: true,
flat: false
})
const emit = defineEmits<{
userClick: [userID: number, email?: string]
@@ -552,10 +574,14 @@ const formatUserAgent = (ua: string): string => {
return ua
}
// 超过 1 分钟简化为 "Xm Ys",免去人工换算(超过 1 小时再进位为 "Xh Ym")
const formatDuration = (ms: number | null | undefined): string => {
if (ms == null) return '-'
if (ms < 1000) return `${ms}ms`
return `${(ms / 1000).toFixed(2)}s`
if (ms < 60_000) return `${(ms / 1000).toFixed(2)}s`
const totalSec = Math.round(ms / 1000)
if (totalSec < 3600) return `${Math.floor(totalSec / 60)}m ${totalSec % 60}s`
return `${Math.floor(totalSec / 3600)}h ${Math.floor((totalSec % 3600) / 60)}m`
}
// Cost tooltip functions
@@ -1,44 +1,33 @@
<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')"
/>
<!-- 用量页"用户排行"tab 内容:无卡片外观,依赖父级统一卡片;筛选/时间范围复用页面级筛选栏 -->
<div>
<!-- Toolbar -->
<div class="flex flex-wrap items-center justify-between gap-3 border-b border-gray-100 px-4 py-3 dark:border-dark-700/50 sm:px-6">
<p class="text-xs text-gray-400 dark:text-gray-500">{{ t('admin.usage.tokenRanking.subtitle') }}</p>
<div class="flex items-center gap-3">
<span v-if="!loading && items.length > 0" class="text-xs text-gray-400 dark:text-gray-500">
{{ t('admin.usage.tokenRanking.userCount', { count: items.length }) }}
</span>
<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>
<table class="w-full min-w-max divide-y divide-gray-200 dark:divide-dark-700">
<thead class="bg-gray-50 dark:bg-dark-800">
<tr>
<th class="w-16 px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-dark-400 sm:px-6">#</th>
<th class="px-4 py-3 text-left text-xs font-medium uppercase tracking-wider text-gray-500 dark:text-dark-400">
{{ 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 }"
class="cursor-pointer select-none whitespace-nowrap px-4 py-3 text-right text-xs font-medium uppercase tracking-wider transition-colors hover:bg-gray-100 dark:hover:bg-dark-700"
:class="sortBy === col.key ? 'text-primary-600 dark:text-primary-400' : 'text-gray-500 dark:text-dark-400'"
@click="setSort(col.key)"
>
{{ t(col.label) }}
@@ -46,54 +35,57 @@
</th>
</tr>
</thead>
<tbody>
<tbody class="divide-y divide-gray-200 bg-white dark:divide-dark-700 dark:bg-dark-900">
<tr v-if="loading">
<td :colspan="sortableColumns.length + 2" class="py-8 text-center">
<td :colspan="sortableColumns.length + 2" class="py-12 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">
<tr v-else-if="items.length === 0">
<td :colspan="sortableColumns.length + 2" class="py-12 text-center text-sm text-gray-400">
{{ t('admin.dashboard.noDataAvailable') }}
</td>
</tr>
<tr
v-for="(item, index) in displayItems"
v-for="(item, index) in items"
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"
class="cursor-pointer transition-colors hover:bg-gray-50 dark:hover:bg-dark-700/40"
:title="t('admin.usage.tokenRanking.rowHint')"
@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 class="px-4 py-3 sm:px-6">
<span
v-if="index < 3"
class="inline-flex h-6 w-6 items-center justify-center rounded-full text-xs font-semibold"
:class="RANK_BADGE_CLASSES[index]"
>{{ index + 1 }}</span>
<span v-else class="inline-block w-6 text-center text-sm tabular-nums text-gray-400">{{ index + 1 }}</span>
</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>
<td class="max-w-[260px] truncate px-4 py-3 text-sm font-medium text-gray-700 dark:text-gray-200" :title="item.email">
{{ item.email || `User #${item.user_id}` }}
<span class="ml-1 font-normal text-gray-400 dark:text-gray-500">#{{ item.user_id }}</span>
</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm tabular-nums text-gray-500 dark:text-gray-400">{{ item.requests.toLocaleString() }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm tabular-nums text-gray-500 dark:text-gray-400">{{ fmtTokens(item.input_tokens) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm tabular-nums text-gray-500 dark:text-gray-400">{{ fmtTokens(item.output_tokens) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm tabular-nums text-gray-500 dark:text-gray-400">{{ fmtTokens(item.cache_tokens) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm font-medium tabular-nums text-gray-900 dark:text-gray-100">{{ fmtTokens(item.total_tokens) }}</td>
<td class="whitespace-nowrap px-4 py-3 text-right text-sm font-medium tabular-nums 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 { ref, 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<{
@@ -124,19 +116,19 @@ const limitOptions = [
{ value: 200, label: 'Top 200' },
]
// 前三名金/银/铜徽章
const RANK_BADGE_CLASSES = [
'bg-amber-100 text-amber-700 dark:bg-amber-500/20 dark:text-amber-400',
'bg-gray-200 text-gray-600 dark:bg-gray-500/20 dark:text-gray-300',
'bg-orange-100 text-orange-700 dark:bg-orange-500/20 dark:text-orange-400',
]
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)
@@ -0,0 +1,81 @@
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { mount, flushPromises } from '@vue/test-utils'
import UserTokenRanking from '../UserTokenRanking.vue'
const getUserBreakdown = vi.fn()
vi.mock('@/api/admin/dashboard', () => ({
getUserBreakdown: (...args: unknown[]) => getUserBreakdown(...args),
}))
vi.mock('vue-i18n', async () => {
const actual = await vi.importActual<typeof import('vue-i18n')>('vue-i18n')
return {
...actual,
useI18n: () => ({
t: (key: string) => key,
}),
}
})
const item = (id: number, tokens: number) => ({
user_id: id,
email: `u${id}@test.com`,
requests: 1,
input_tokens: tokens,
output_tokens: 0,
cache_tokens: 0,
total_tokens: tokens,
actual_cost: 0.5,
})
const mountRanking = (props: Record<string, unknown> = {}) =>
mount(UserTokenRanking, {
props: {
startDate: '2026-07-01',
endDate: '2026-07-08',
filters: {},
...props,
},
global: { stubs: { Select: true, LoadingSpinner: true } },
})
describe('UserTokenRanking', () => {
beforeEach(() => {
getUserBreakdown.mockReset()
getUserBreakdown.mockResolvedValue({ users: [item(1, 100), item(2, 50)] })
})
it('loads on mount with shared filters and emits select-user with id + email on row click', async () => {
const wrapper = mountRanking({ filters: { group_id: 3 }, model: 'claude-fable-5' })
await flushPromises()
expect(getUserBreakdown).toHaveBeenCalledWith(expect.objectContaining({
group_id: 3,
model: 'claude-fable-5',
start_date: '2026-07-01',
end_date: '2026-07-08',
sort_by: 'total_tokens',
limit: 50,
}))
const rows = wrapper.findAll('tbody tr')
expect(rows).toHaveLength(2)
await rows[0].trigger('click')
expect(wrapper.emitted('select-user')![0]).toEqual([1, 'u1@test.com'])
})
it('reloads when shared filters change', async () => {
const wrapper = mountRanking()
await flushPromises()
expect(getUserBreakdown).toHaveBeenCalledTimes(1)
await wrapper.setProps({ filters: { user_id: 9 } })
await flushPromises()
expect(getUserBreakdown).toHaveBeenCalledTimes(2)
expect(getUserBreakdown).toHaveBeenLastCalledWith(expect.objectContaining({ user_id: 9 }))
})
})