mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-06 00:05:30 +00:00
fix(frontend): keep usage displays tied to the current request
This commit is contained in:
1 parent
f53641e53c
commit
ef3649aafe
6 files changed
+97
-11
No files matched your search
@@ -451,6 +451,7 @@ export default {
|
||||
original: 'Original',
|
||||
billed: 'Billed',
|
||||
noRecords: 'No usage records found. Try adjusting your filters.',
|
||||
statsUnavailable: 'Usage statistics unavailable',
|
||||
failedToLoad: 'Failed to load usage logs',
|
||||
noDataToExport: 'No data to export',
|
||||
exportSuccess: 'Usage data exported successfully',
|
||||
|
||||
@@ -456,6 +456,7 @@ export default {
|
||||
original: '原始',
|
||||
billed: '计费',
|
||||
noRecords: '未找到使用记录,请尝试调整筛选条件。',
|
||||
statsUnavailable: '用量统计暂不可用',
|
||||
failedToLoad: '加载使用记录失败',
|
||||
noDataToExport: '没有可导出的数据',
|
||||
exportSuccess: '使用数据导出成功',
|
||||
|
||||
@@ -213,23 +213,25 @@
|
||||
<div class="flex items-center gap-1.5">
|
||||
<span class="text-gray-500 dark:text-gray-400">{{ t('keys.today') }}:</span>
|
||||
<span
|
||||
v-if="usageLoading && !usageStats[row.id]"
|
||||
v-if="usageLoading"
|
||||
data-test="usage-pending"
|
||||
class="inline-block h-3 w-14 animate-pulse rounded bg-gray-200 dark:bg-dark-600"
|
||||
/>
|
||||
<span v-else class="font-medium text-gray-900 dark:text-white">
|
||||
${{ (usageStats[row.id]?.today_actual_cost ?? 0).toFixed(4) }}
|
||||
<span v-else-if="usageStats[row.id]" class="font-medium text-gray-900 dark:text-white">
|
||||
${{ usageStats[row.id].today_actual_cost.toFixed(4) }}
|
||||
</span>
|
||||
<span v-else :title="t('usage.statsUnavailable')">—</span>
|
||||
</div>
|
||||
<div class="mt-0.5 flex items-center gap-1.5">
|
||||
<span class="text-gray-500 dark:text-gray-400">{{ t('keys.total') }}:</span>
|
||||
<span
|
||||
v-if="usageLoading && !usageStats[row.id]"
|
||||
v-if="usageLoading"
|
||||
class="inline-block h-3 w-14 animate-pulse rounded bg-gray-200 dark:bg-dark-600"
|
||||
/>
|
||||
<span v-else class="font-medium text-gray-900 dark:text-white">
|
||||
${{ (usageStats[row.id]?.total_actual_cost ?? 0).toFixed(4) }}
|
||||
<span v-else-if="usageStats[row.id]" class="font-medium text-gray-900 dark:text-white">
|
||||
${{ usageStats[row.id].total_actual_cost.toFixed(4) }}
|
||||
</span>
|
||||
<span v-else :title="t('usage.statsUnavailable')">—</span>
|
||||
</div>
|
||||
<!-- Quota progress (if quota is set) -->
|
||||
<div v-if="row.quota > 0" class="mt-1.5">
|
||||
@@ -1599,6 +1601,7 @@ const loadApiKeys = async () => {
|
||||
abortController = controller
|
||||
const { signal } = controller
|
||||
loading.value = true
|
||||
usageStats.value = {}
|
||||
usageLoading.value = false
|
||||
try {
|
||||
// Build filters
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<template>
|
||||
<AppLayout>
|
||||
<div class="space-y-6">
|
||||
<UsageStatsCards :stats="usageStats" :show-account-cost="false" :strike-standard-cost="true" />
|
||||
<UsageStatsCards v-if="usageStats" :stats="usageStats" :show-account-cost="false" :strike-standard-cost="true" />
|
||||
|
||||
<p v-else class="card p-4 text-sm text-gray-500" role="status">
|
||||
{{ endpointStatsLoading ? t('common.loading') : t('usage.statsUnavailable') }}
|
||||
</p>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div class="card p-4">
|
||||
@@ -330,6 +334,7 @@ const applyErrorFilters = () => {
|
||||
let abortController: AbortController | null = null
|
||||
let chartReqSeq = 0
|
||||
let statsReqSeq = 0
|
||||
let errorReqSeq = 0
|
||||
let modelStatsReqSeq = 0
|
||||
|
||||
const formatLocalDate = (date: Date): string =>
|
||||
@@ -468,6 +473,7 @@ const loadLogs = async () => {
|
||||
|
||||
const loadStats = async () => {
|
||||
const seq = ++statsReqSeq
|
||||
usageStats.value = null
|
||||
endpointStatsLoading.value = true
|
||||
try {
|
||||
const stats = await usageAPI.getStats(normalizedFilters.value)
|
||||
@@ -866,12 +872,15 @@ const resetErrorRows = () => {
|
||||
if (activeTab.value === 'errors') {
|
||||
void loadErrors()
|
||||
} else {
|
||||
++errorReqSeq
|
||||
errorLoading.value = false
|
||||
errorRows.value = []
|
||||
errorTotal.value = 0
|
||||
}
|
||||
}
|
||||
|
||||
const loadErrors = async () => {
|
||||
const seq = ++errorReqSeq
|
||||
errorLoading.value = true
|
||||
try {
|
||||
const resp = await usageAPI.listMyErrorRequests({
|
||||
@@ -886,13 +895,17 @@ const loadErrors = async () => {
|
||||
sort_by: errorSortBy.value,
|
||||
sort_order: errorSortOrder.value,
|
||||
})
|
||||
if (seq !== errorReqSeq) return
|
||||
errorRows.value = resp.items
|
||||
errorTotal.value = resp.total
|
||||
} catch (error) {
|
||||
if (seq !== errorReqSeq) return
|
||||
errorRows.value = []
|
||||
errorTotal.value = 0
|
||||
console.error('[UsageView] loadErrors failed:', error)
|
||||
appStore.showError(t('usage.errors.failedToLoad'))
|
||||
} finally {
|
||||
errorLoading.value = false
|
||||
if (seq === errorReqSeq) errorLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,6 +941,7 @@ onMounted(() => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
++errorReqSeq
|
||||
abortController?.abort()
|
||||
document.removeEventListener('click', handleColumnClickOutside)
|
||||
})
|
||||
|
||||
@@ -683,7 +683,21 @@ describe('user KeysView column settings', () => {
|
||||
const wrapper = await mountView()
|
||||
|
||||
expect(wrapper.find('[data-test="usage-pending"]').exists()).toBe(false)
|
||||
expect(wrapper.get('[data-test="usage"]').text()).toContain('$0.0000')
|
||||
const usage = () => wrapper.get('[data-test="usage"]').text()
|
||||
expect(usage()).not.toContain('$')
|
||||
expect(usage()).toContain('—')
|
||||
|
||||
getDashboardApiKeysUsage.mockResolvedValueOnce({
|
||||
stats: { 1: { api_key_id: 1, today_actual_cost: 0, total_actual_cost: 12 } },
|
||||
})
|
||||
await wrapper.get('button[title="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(usage()).toContain('$0.0000')
|
||||
expect(usage()).toContain('$12.0000')
|
||||
|
||||
await wrapper.get('button[title="Refresh"]').trigger('click')
|
||||
await flushPromises()
|
||||
expect(usage()).not.toContain('$')
|
||||
consoleError.mockRestore()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -159,9 +159,9 @@ function mountUsageView() {
|
||||
Select: true,
|
||||
DateRangePicker: true,
|
||||
Icon: true,
|
||||
UsageStatsCards: chartStub,
|
||||
UsageStatsCards: { name: 'UsageStatsCards', props: ['stats'], template: '<div />' },
|
||||
UsageTable: { ...chartStub, props: ['columns'] },
|
||||
UserErrorRequestsTable: chartStub,
|
||||
UserErrorRequestsTable: { name: 'UserErrorRequestsTable', props: ['rows', 'total', 'loading'], template: '<div />' },
|
||||
ModelDistributionChart: chartStub,
|
||||
GroupDistributionChart: chartStub,
|
||||
EndpointDistributionChart: chartStub,
|
||||
@@ -217,6 +217,59 @@ describe('user UsageView', () => {
|
||||
getAvailable.mockResolvedValue([{ id: 1, name: 'default' }])
|
||||
})
|
||||
|
||||
it('invalidates the summary when the key changes and recovers on refresh', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
const cards = () => wrapper.findComponent({ name: 'UsageStatsCards' })
|
||||
expect(cards().props('stats').total_actual_cost).toBe(0.08)
|
||||
|
||||
let rejectStats!: (error: Error) => void
|
||||
getStats.mockReturnValueOnce(new Promise((_, reject) => { rejectStats = reject }))
|
||||
const select = wrapper.findAllComponents(Select).find((item) =>
|
||||
item.props('options').some((option: SelectOption) => option.label === 'All API Keys')
|
||||
)!
|
||||
select.vm.$emit('update:modelValue', 1)
|
||||
select.vm.$emit('change', 1)
|
||||
await flushPromises()
|
||||
expect(cards().exists()).toBe(false)
|
||||
|
||||
rejectStats(new Error('timeout'))
|
||||
await flushPromises()
|
||||
expect(wrapper.text()).toContain('usage.statsUnavailable')
|
||||
getStats.mockResolvedValueOnce({ total_actual_cost: 0 })
|
||||
await wrapper.findAll('button').find((button) => button.text() === 'Refresh')!.trigger('click')
|
||||
await flushPromises()
|
||||
expect(cards().props('stats').total_actual_cost).toBe(0)
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('only accepts the current error page response and loading state', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
let resolveFirst!: (result: unknown) => void
|
||||
let rejectSecond!: (error: Error) => void
|
||||
let resolveLatest!: (result: unknown) => void
|
||||
listMyErrorRequests
|
||||
.mockReturnValueOnce(new Promise((resolve) => { resolveFirst = resolve }))
|
||||
.mockReturnValueOnce(new Promise((_, reject) => { rejectSecond = reject }))
|
||||
.mockReturnValueOnce(new Promise((resolve) => { resolveLatest = resolve }))
|
||||
await wrapper.findAll('button').find((button) => button.text() === 'Error records')!.trigger('click')
|
||||
const table = wrapper.getComponent({ name: 'UserErrorRequestsTable' })
|
||||
table.vm.$emit('update:page', 2)
|
||||
table.vm.$emit('update:page', 3)
|
||||
rejectSecond(new Error('obsolete request'))
|
||||
await flushPromises()
|
||||
expect(table.props('loading')).toBe(true)
|
||||
expect(showError).not.toHaveBeenCalled()
|
||||
|
||||
resolveLatest({ items: [{ id: 3 }], total: 55 })
|
||||
await flushPromises()
|
||||
resolveFirst({ items: [{ id: 1 }], total: 10 })
|
||||
await flushPromises()
|
||||
expect(table.props()).toMatchObject({ rows: [{ id: 3 }], total: 55, loading: false })
|
||||
wrapper.unmount()
|
||||
})
|
||||
|
||||
it('loads logs, stats, model stats, and snapshot on first render', async () => {
|
||||
const wrapper = mountUsageView()
|
||||
await flushPromises()
|
||||
|
||||
Reference in new issue
Block a user