feat(frontend): 前端界面优化与使用统计功能增强 (#46)

* feat(frontend): 前端界面优化与使用统计功能增强

主要改动:

1. 表格布局统一优化
   - 新增 TablePageLayout 通用布局组件
   - 统一所有管理页面的表格样式和交互
   - 优化 DataTable、Pagination、Select 等通用组件

2. 使用统计功能增强
   - 管理端: 添加完整的筛选和显示功能
   - 用户端: 完善 API Key 列显示
   - 后端: 优化使用统计数据结构和查询

3. 账户组件优化
   - 优化 AccountStatsModal、AccountUsageCell 等组件
   - 统一进度条和统计显示样式

4. 其他改进
   - 完善中英文国际化
   - 统一页面样式和交互体验
   - 优化各视图页面的响应式布局

* fix(test): 修复 stubUsageLogRepo.ListWithFilters 测试 stub

测试用例 GET /api/v1/usage 返回 500 是因为 stub 方法未实现,
现在正确返回基于 UserID 过滤的日志数据。

* feat(frontend): 统一日期时间显示格式

**主要改动**:
1. 增强 utils/format.ts:
   - 新增 formatDateOnly() - 格式: YYYY-MM-DD
   - 新增 formatDateTime() - 格式: YYYY-MM-DD HH:mm:ss

2. 全局替换视图中的格式化函数:
   - 移除各视图中的自定义 formatDate 函数
   - 统一导入使用 @/utils/format 中的函数
   - created_at/updated_at 使用 formatDateTime
   - expires_at 使用 formatDateOnly

3. 受影响的视图 (8个):
   - frontend/src/views/user/KeysView.vue
   - frontend/src/views/user/DashboardView.vue
   - frontend/src/views/user/UsageView.vue
   - frontend/src/views/user/RedeemView.vue
   - frontend/src/views/admin/UsersView.vue
   - frontend/src/views/admin/UsageView.vue
   - frontend/src/views/admin/RedeemView.vue
   - frontend/src/views/admin/SubscriptionsView.vue

**效果**:
- 日期统一显示为 YYYY-MM-DD
- 时间统一显示为 YYYY-MM-DD HH:mm:ss
- 提升可维护性,避免格式不一致

* fix(frontend): 补充遗漏的时间格式化统一

**补充修复**(基于 code review 发现的遗漏):

1. 增强 utils/format.ts:
   - 新增 formatTime() - 格式: HH:mm

2. 修复 4 个遗漏的文件:
   - src/views/admin/UsersView.vue
     * 删除 formatExpiresAt(),改用 formatDateTime()
     * 修复订阅过期时间 tooltip 显示格式不一致问题

   - src/views/user/ProfileView.vue
     * 删除 formatMemberSince(),改用 formatDate(date, 'YYYY-MM')
     * 统一会员起始时间显示格式

   - src/views/user/SubscriptionsView.vue
     * 修改 formatExpirationDate() 使用 formatDateOnly()
     * 保留天数计算逻辑

   - src/components/account/AccountStatusIndicator.vue
     * 删除本地 formatTime(),改用 utils/format 中的统一函数
     * 修复 rate limit 和 overload 重置时间显示

**验证**:
- TypeScript 类型检查通过 ✓
- 前端构建成功 ✓
- 所有剩余的 toLocaleString() 都是数字格式化,属于正确用法 ✓

**效果**:
- 订阅过期时间统一为 YYYY-MM-DD HH:mm:ss
- 会员起始时间统一为 YYYY-MM
- 重置时间统一为 HH:mm
- 消除所有不规范的原生 locale 方法调用
This commit is contained in:
IanShaw
2025-12-27 10:50:25 +08:00
committed by GitHub
parent cf8a64528c
commit 254f12543c
43 changed files with 1673 additions and 692 deletions

View File

@@ -1,10 +1,10 @@
<template>
<AppLayout>
<div class="space-y-6">
<!-- Summary Stats Cards -->
<!-- Stats Cards -->
<div class="grid grid-cols-2 gap-4 lg:grid-cols-4">
<!-- Total Requests -->
<div class="card p-4">
<!-- Total Requests -->
<div class="card p-4">
<div class="flex items-center gap-3">
<div class="rounded-lg bg-blue-100 p-2 dark:bg-blue-900/30">
<svg
@@ -130,10 +130,10 @@
</div>
</div>
</div>
</div>
</div>
<!-- Charts Section -->
<div class="space-y-4">
<!-- Charts Section -->
<div class="space-y-4">
<!-- Chart Controls -->
<div class="card p-4">
<div class="flex items-center gap-4">
@@ -157,9 +157,9 @@
</div>
</div>
<!-- Filters -->
<!-- Filters Section -->
<div class="card">
<div class="px-6 py-4">
<div class="px-6 py-4">
<div class="flex flex-wrap items-end gap-4">
<!-- User Search -->
<div class="min-w-[200px]">
@@ -229,6 +229,61 @@
/>
</div>
<!-- Model Filter -->
<div class="min-w-[180px]">
<label class="input-label">{{ t('usage.model') }}</label>
<Select
v-model="filters.model"
:options="modelOptions"
:placeholder="t('admin.usage.allModels')"
@change="applyFilters"
/>
</div>
<!-- Account Filter -->
<div class="min-w-[180px]">
<label class="input-label">{{ t('admin.usage.account') }}</label>
<Select
v-model="filters.account_id"
:options="accountOptions"
:placeholder="t('admin.usage.allAccounts')"
@change="applyFilters"
/>
</div>
<!-- Stream Type Filter -->
<div class="min-w-[150px]">
<label class="input-label">{{ t('usage.type') }}</label>
<Select
v-model="filters.stream"
:options="streamOptions"
:placeholder="t('admin.usage.allTypes')"
@change="applyFilters"
/>
</div>
<!-- Billing Type Filter -->
<div class="min-w-[150px]">
<label class="input-label">{{ t('usage.billingType') }}</label>
<Select
v-model="filters.billing_type"
:options="billingTypeOptions"
:placeholder="t('admin.usage.allBillingTypes')"
@change="applyFilters"
/>
</div>
<!-- Group Filter -->
<div class="min-w-[150px]">
<label class="input-label">{{ t('admin.usage.group') }}</label>
<Select
v-model="filters.group_id"
:options="groupOptions"
:placeholder="t('admin.usage.allGroups')"
@change="applyFilters"
/>
</div>
<!-- Date Range Filter -->
<div>
<label class="input-label">{{ t('usage.timeRange') }}</label>
@@ -252,9 +307,10 @@
</div>
</div>
<!-- Usage Table -->
<!-- Table Section -->
<div class="card overflow-hidden">
<DataTable :columns="columns" :data="usageLogs" :loading="loading">
<div class="overflow-auto">
<DataTable :columns="columns" :data="usageLogs" :loading="loading">
<template #cell-user="{ row }">
<div class="text-sm">
<span class="font-medium text-gray-900 dark:text-white">{{
@@ -270,10 +326,26 @@
}}</span>
</template>
<template #cell-account="{ row }">
<span class="text-sm text-gray-900 dark:text-white">{{
row.account?.name || '-'
}}</span>
</template>
<template #cell-model="{ value }">
<span class="font-medium text-gray-900 dark:text-white">{{ value }}</span>
</template>
<template #cell-group="{ row }">
<span
v-if="row.group"
class="inline-flex items-center rounded px-2 py-0.5 text-xs font-medium bg-indigo-100 text-indigo-800 dark:bg-indigo-900 dark:text-indigo-200"
>
{{ row.group.name }}
</span>
<span v-else class="text-sm text-gray-400 dark:text-gray-500">-</span>
</template>
<template #cell-stream="{ row }">
<span
class="inline-flex items-center rounded px-2 py-0.5 text-xs font-medium"
@@ -407,6 +479,27 @@
class="whitespace-nowrap rounded-lg border border-gray-700 bg-gray-900 px-3 py-2.5 text-xs text-white shadow-xl dark:border-gray-600 dark:bg-gray-800"
>
<div class="space-y-1.5">
<!-- Cost Breakdown -->
<div class="mb-2 border-b border-gray-700 pb-1.5">
<div class="text-xs font-semibold text-gray-300 mb-1">成本明细</div>
<div v-if="row.input_cost > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400">{{ t('admin.usage.inputCost') }}</span>
<span class="font-medium text-white">${{ row.input_cost.toFixed(6) }}</span>
</div>
<div v-if="row.output_cost > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400">{{ t('admin.usage.outputCost') }}</span>
<span class="font-medium text-white">${{ row.output_cost.toFixed(6) }}</span>
</div>
<div v-if="row.cache_creation_cost > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400">{{ t('admin.usage.cacheCreationCost') }}</span>
<span class="font-medium text-white">${{ row.cache_creation_cost.toFixed(6) }}</span>
</div>
<div v-if="row.cache_read_cost > 0" class="flex items-center justify-between gap-4">
<span class="text-gray-400">{{ t('admin.usage.cacheReadCost') }}</span>
<span class="font-medium text-white">${{ row.cache_read_cost.toFixed(6) }}</span>
</div>
</div>
<!-- Rate and Summary -->
<div class="flex items-center justify-between gap-6">
<span class="text-gray-400">{{ t('usage.rate') }}</span>
<span class="font-semibold text-blue-400"
@@ -471,10 +564,17 @@
}}</span>
</template>
<template #cell-request_id="{ row }">
<span class="font-mono text-xs text-gray-500 dark:text-gray-400">{{
row.request_id || '-'
}}</span>
</template>
<template #empty>
<EmptyState :message="t('usage.noRecords')" />
</template>
</DataTable>
</div>
</div>
<!-- Pagination -->
@@ -498,6 +598,7 @@ import AppLayout from '@/components/layout/AppLayout.vue'
import DataTable from '@/components/common/DataTable.vue'
import Pagination from '@/components/common/Pagination.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import { formatDateTime } from '@/utils/format'
import Select from '@/components/common/Select.vue'
import DateRangePicker from '@/components/common/DateRangePicker.vue'
import ModelDistributionChart from '@/components/charts/ModelDistributionChart.vue'
@@ -532,17 +633,23 @@ const granularityOptions = computed(() => [
const columns = computed<Column[]>(() => [
{ key: 'user', label: t('admin.usage.user'), sortable: false },
{ key: 'api_key', label: t('usage.apiKeyFilter'), sortable: false },
{ key: 'account', label: t('admin.usage.account'), sortable: false },
{ key: 'model', label: t('usage.model'), sortable: true },
{ key: 'group', label: t('admin.usage.group'), sortable: false },
{ key: 'stream', label: t('usage.type'), sortable: false },
{ key: 'tokens', label: t('usage.tokens'), sortable: false },
{ key: 'cost', label: t('usage.cost'), sortable: false },
{ key: 'billing_type', label: t('usage.billingType'), sortable: false },
{ key: 'duration', label: t('usage.duration'), sortable: false },
{ key: 'created_at', label: t('usage.time'), sortable: true }
{ key: 'created_at', label: t('usage.time'), sortable: true },
{ key: 'request_id', label: t('admin.usage.requestId'), sortable: false }
])
const usageLogs = ref<UsageLog[]>([])
const apiKeys = ref<SimpleApiKey[]>([])
const models = ref<string[]>([])
const accounts = ref<any[]>([])
const groups = ref<any[]>([])
const loading = ref(false)
// User search state
@@ -564,6 +671,53 @@ const apiKeyOptions = computed(() => {
]
})
// Model options
const modelOptions = computed(() => {
return [
{ value: null, label: t('admin.usage.allModels') },
...models.value.map((model) => ({
value: model,
label: model
}))
]
})
// Account options
const accountOptions = computed(() => {
return [
{ value: null, label: t('admin.usage.allAccounts') },
...accounts.value.map((account) => ({
value: account.id,
label: account.name
}))
]
})
// Stream type options
const streamOptions = computed(() => [
{ value: null, label: t('admin.usage.allTypes') },
{ value: true, label: t('usage.stream') },
{ value: false, label: t('usage.sync') }
])
// Billing type options
const billingTypeOptions = computed(() => [
{ value: null, label: t('admin.usage.allBillingTypes') },
{ value: 0, label: t('usage.balance') },
{ value: 1, label: t('usage.subscription') }
])
// Group options
const groupOptions = computed(() => {
return [
{ value: null, label: t('admin.usage.allGroups') },
...groups.value.map((group) => ({
value: group.id,
label: group.name
}))
]
})
// Date range state
const startDate = ref('')
const endDate = ref('')
@@ -571,6 +725,11 @@ const endDate = ref('')
const filters = ref<AdminUsageQueryParams>({
user_id: undefined,
api_key_id: undefined,
account_id: undefined,
group_id: undefined,
model: undefined,
stream: undefined,
billing_type: undefined,
start_date: undefined,
end_date: undefined
})
@@ -689,17 +848,6 @@ const formatCacheTokens = (value: number): string => {
return value.toLocaleString()
}
const formatDateTime = (dateString: string): string => {
const date = new Date(dateString)
return date.toLocaleString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})
}
const loadUsageLogs = async () => {
loading.value = true
try {
@@ -713,6 +861,9 @@ const loadUsageLogs = async () => {
usageLogs.value = response.items
pagination.value.total = response.total
pagination.value.pages = response.pages
// Extract models from loaded logs for filter options
extractModelsFromLogs()
} catch (error) {
appStore.showError(t('usage.failedToLoad'))
} finally {
@@ -775,6 +926,32 @@ const applyFilters = () => {
loadChartData()
}
// Load filter options
const loadFilterOptions = async () => {
try {
// Load accounts
const accountsResponse = await adminAPI.accounts.list(1, 1000)
accounts.value = accountsResponse.items || []
// Load groups
const groupsResponse = await adminAPI.groups.list(1, 1000)
groups.value = groupsResponse.items || []
} catch (error) {
console.error('Failed to load filter options:', error)
}
}
// Extract unique models from usage logs
const extractModelsFromLogs = () => {
const uniqueModels = new Set<string>()
usageLogs.value.forEach(log => {
if (log.model) {
uniqueModels.add(log.model)
}
})
models.value = Array.from(uniqueModels).sort()
}
const resetFilters = () => {
selectedUser.value = null
userSearchKeyword.value = ''
@@ -783,6 +960,11 @@ const resetFilters = () => {
filters.value = {
user_id: undefined,
api_key_id: undefined,
account_id: undefined,
group_id: undefined,
model: undefined,
stream: undefined,
billing_type: undefined,
start_date: undefined,
end_date: undefined
}
@@ -858,6 +1040,7 @@ const handleClickOutside = (event: MouseEvent) => {
onMounted(() => {
initializeDateRange()
loadFilterOptions()
loadUsageLogs()
loadUsageStats()
loadChartData()