Merge pull request #3869 from Birditch/feat/admin-user-role-and-token-ranking

feat(admin): 用户角色管理 + 用户 Token 排行
This commit is contained in:
Wesley Liddick
2026-07-09 19:50:01 +08:00
committed by GitHub
18 changed files with 423 additions and 17 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>
@@ -25,6 +25,13 @@
<label class="input-label">{{ t('admin.users.username') }}</label>
<input v-model="form.username" type="text" class="input" :placeholder="t('admin.users.enterUsername')" />
</div>
<div>
<label class="input-label">{{ t('admin.users.form.roleLabel') }}</label>
<select v-model="form.role" class="input">
<option value="user">{{ t('admin.users.roles.user') }}</option>
<option value="admin">{{ t('admin.users.roles.admin') }}</option>
</select>
</div>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label class="input-label">{{ t('admin.users.columns.balance') }}</label>
@@ -69,7 +76,7 @@ import Icon from '@/components/icons/Icon.vue'
const props = defineProps<{ show: boolean }>()
const emit = defineEmits(['close', 'success']); const { t } = useI18n()
const form = reactive({ email: '', password: '', username: '', notes: '', balance: '', concurrency: 1, rpm_limit: 0 })
const form = reactive({ email: '', password: '', username: '', notes: '', role: 'user' as 'user' | 'admin', balance: '', concurrency: 1, rpm_limit: 0 })
const { loading, submit } = useForm({
form,
@@ -86,7 +93,7 @@ const { loading, submit } = useForm({
successMsg: t('admin.users.userCreated')
})
watch(() => props.show, (v) => { if(v) Object.assign(form, { email: '', password: '', username: '', notes: '', balance: '', concurrency: 1, rpm_limit: 0 }) })
watch(() => props.show, (v) => { if(v) Object.assign(form, { email: '', password: '', username: '', notes: '', role: 'user', balance: '', concurrency: 1, rpm_limit: 0 }) })
const generateRandomPassword = () => {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789!@#$%^&*'
@@ -29,6 +29,13 @@
<label class="input-label">{{ t('admin.users.username') }}</label>
<input v-model="form.username" type="text" class="input" />
</div>
<div>
<label class="input-label">{{ t('admin.users.form.roleLabel') }}</label>
<select v-model="form.role" class="input">
<option value="user">{{ t('admin.users.roles.user') }}</option>
<option value="admin">{{ t('admin.users.roles.admin') }}</option>
</select>
</div>
<div>
<label class="input-label">{{ t('admin.users.notes') }}</label>
<textarea v-model="form.notes" rows="3" class="input"></textarea>
@@ -78,11 +85,11 @@ const emit = defineEmits(['close', 'success'])
const { t } = useI18n(); const appStore = useAppStore(); const { copyToClipboard } = useClipboard()
const submitting = ref(false); const passwordCopied = ref(false)
const form = reactive({ email: '', password: '', username: '', notes: '', concurrency: 1, rpm_limit: 0, customAttributes: {} as UserAttributeValuesMap })
const form = reactive({ email: '', password: '', username: '', notes: '', role: 'user', concurrency: 1, rpm_limit: 0, customAttributes: {} as UserAttributeValuesMap })
watch(() => props.user, (u) => {
if (u) {
Object.assign(form, { email: u.email, password: '', username: u.username || '', notes: u.notes || '', concurrency: u.concurrency, rpm_limit: u.rpm_limit ?? 0, customAttributes: {} })
Object.assign(form, { email: u.email, password: '', username: u.username || '', notes: u.notes || '', role: u.role || 'user', concurrency: u.concurrency, rpm_limit: u.rpm_limit ?? 0, customAttributes: {} })
passwordCopied.value = false
}
}, { immediate: true })
@@ -109,7 +116,7 @@ const handleUpdateUser = async () => {
}
submitting.value = true
try {
const data: any = { email: form.email, username: form.username, notes: form.notes, concurrency: form.concurrency, rpm_limit: form.rpm_limit }
const data: any = { email: form.email, username: form.username, notes: form.notes, role: form.role, concurrency: form.concurrency, rpm_limit: form.rpm_limit }
if (form.password.trim()) data.password = form.password.trim()
await adminAPI.users.update(props.user.id, data)
if (Object.keys(form.customAttributes).length > 0) await adminAPI.userAttributes.updateUserAttributeValues(props.user.id, form.customAttributes)