feat: 新增 AI 用量统计页与头部入口

- 新增 /ai-usage 页面:统计卡、按任务类型/模型明细、内联 SVG 趋势图、上游余额
- 入口按钮放在「退出登录」左侧,显隐读登录响应写入的 aiAdmin
- token 为 null 时显示「未上报」,与 0 区分
This commit is contained in:
2026-10-10 18:46:11 +08:00
parent b48ce89f4e
commit 0a728cfba8
11 changed files with 1255 additions and 9 deletions
+5
View File
@@ -48,6 +48,11 @@ lpt-fe/src/
| `/review` | Review.vue | 复习总览 |
| `/review/detail/:type/:id` | ReviewDetail.vue | 复习详情 |
| `/review/recall/:taskNum` | ReviewRecall.vue | 回忆复习 |
| `/ai-usage` | AiUsage.vue | AI 用量统计(仅白名单用户可见) |
> 「AI 用量统计」的数据全部来自 `lpt-be` 的 `/ai/usage/*`(不直连 lpt-ai),
> 页面只展示聚合数字与费用,**不含 prompt 与学习内容**(完整日志仍在 lpt-ai 的 `/admin`)。
> 入口显隐读登录响应写入的 `localStorage.aiAdmin`,真正的权限校验在服务端。
## 认证与请求
+84
View File
@@ -0,0 +1,84 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@/utils/request', () => ({
default: {
get: vi.fn(),
post: vi.fn(),
put: vi.fn(),
del: vi.fn(),
},
}))
import request from '@/utils/request'
import {
getUsageBalance,
getUsageBreakdown,
getUsagePermission,
getUsageSeries,
getUsageSummary,
} from '@/api/aiUsage'
const mockedRequest = vi.mocked(request)
describe('aiUsage API', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('getUsagePermission calls GET /ai/usage/permission', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: { allowed: true } })
const result = await getUsagePermission()
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/permission')
expect(result).toEqual({ code: 200, data: { allowed: true } })
})
it('getUsageSummary sends the time range and filters', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
await getUsageSummary({ from: 1000, to: 2000, taskType: 'guidance', model: 'deepseek-flash' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/summary', {
from: 1000,
to: 2000,
taskType: 'guidance',
model: 'deepseek-flash',
})
})
it('getUsageSummary sends no filters by default', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
await getUsageSummary()
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/summary', {})
})
it('getUsageSeries calls GET /ai/usage/series with the bucket', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
await getUsageSeries({ from: 1000, to: 2000, bucket: 'day' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/series', {
from: 1000,
to: 2000,
bucket: 'day',
})
})
it('getUsageBreakdown calls GET /ai/usage/breakdown with the group dimension', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
await getUsageBreakdown({ from: 1000, to: 2000, groupBy: 'model' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/breakdown', {
from: 1000,
to: 2000,
groupBy: 'model',
})
})
it('getUsageBreakdown can be called without filters to derive dropdown options', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
await getUsageBreakdown({ groupBy: 'taskType' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/breakdown', { groupBy: 'taskType' })
})
it('getUsageBalance calls GET /ai/usage/balance', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: { configured: false } })
const result = await getUsageBalance()
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/balance')
expect(result).toEqual({ code: 200, data: { configured: false } })
})
})
+15 -1
View File
@@ -46,7 +46,7 @@ describe('Login.vue', () => {
})
it('sets localStorage and navigates on successful login', async () => {
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功' } as any)
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功', data: { token: 't', aiAdmin: true } } as any)
const wrapper = mountLogin()
wrapper.vm.registerData.username = 'admin'
wrapper.vm.registerData.password = '123456'
@@ -54,10 +54,24 @@ describe('Login.vue', () => {
await wrapper.vm.submitForm(createForm(true))
expect(localStorage.getItem('isLoggedIn')).toBe('true')
expect(localStorage.getItem('aiAdmin')).toBe('true')
expect(ElMessage.success).toHaveBeenCalledWith('登录成功')
expect(router.currentRoute.value.path).toBe('/welcome')
})
it('非白名单用户登录后写入 aiAdmin=false,不残留入口标记', async () => {
localStorage.setItem('aiAdmin', 'true')
vi.mocked(login).mockResolvedValue({ code: 200, message: '登录成功', data: { token: 't', aiAdmin: false } } as any)
const wrapper = mountLogin()
wrapper.vm.registerData.username = 'cat'
wrapper.vm.registerData.password = '123456'
await wrapper.vm.submitForm(createForm(true))
expect(localStorage.getItem('isLoggedIn')).toBe('true')
expect(localStorage.getItem('aiAdmin')).toBe('false')
})
it('shows error message on failed login', async () => {
vi.mocked(login).mockResolvedValue({ code: 401, message: '密码错误' } as any)
const wrapper = mountLogin()
+45 -4
View File
@@ -96,15 +96,56 @@ describe('MyHead.vue', () => {
expect(welcomeWrapper.vm.pageTitle).toBeUndefined()
})
it('clears login state and navigates to login on logout', async () => { vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
it('clears login state and navigates to login on logout', async () => {
vi.mocked(logout).mockResolvedValue({ code: 200 } as any)
localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountAt('/study')
localStorage.setItem('aiAdmin', 'true')
const wrapper = await mountRealAt('/study')
await wrapper.vm.handleLogout()
await wrapper.findAll('button').find((button) => button.text().includes('退出登录'))!.trigger('click')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/login'))
expect(localStorage.getItem('isLoggedIn')).toBeNull()
expect(localStorage.getItem('aiAdmin')).toBeNull()
expect(ElMessage.success).toHaveBeenCalledWith('已退出登录')
expect(router.currentRoute.value.path).toBe('/login')
})
it('白名单用户显示 AI 用量入口,点击后进入统计页', async () => {
localStorage.setItem('isLoggedIn', 'true')
localStorage.setItem('aiAdmin', 'true')
const wrapper = await mountRealAt('/study')
const entry = wrapper.findAll('button').find((button) => button.text().includes('AI 用量统计'))
expect(entry).toBeTruthy()
await entry!.trigger('click')
await vi.waitFor(() => expect(router.currentRoute.value.path).toBe('/ai-usage'))
})
it('非白名单用户不显示 AI 用量入口', async () => {
localStorage.setItem('isLoggedIn', 'true')
const wrapper = await mountRealAt('/study')
expect(wrapper.text()).not.toContain('AI 用量统计')
})
it('登录页即使是白名单也不显示 AI 用量入口', async () => {
localStorage.setItem('aiAdmin', 'true')
const wrapper = await mountRealAt('/login')
expect(wrapper.text()).not.toContain('AI 用量统计')
})
it('换账号登录后按路由变化重新读取白名单,不残留上一个账号的入口', async () => {
localStorage.setItem('isLoggedIn', 'true')
localStorage.setItem('aiAdmin', 'true')
const wrapper = await mountRealAt('/study')
expect(wrapper.text()).toContain('AI 用量统计')
// 非管理员重新登录后只写了 isLoggedIn 与 aiAdmin=false
localStorage.setItem('aiAdmin', 'false')
await router.push('/welcome')
await vi.waitFor(() => expect(wrapper.text()).not.toContain('AI 用量统计'))
})
it('clears login state even when logout API fails', async () => {
@@ -0,0 +1,252 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
import ElementPlus from 'element-plus'
import AiUsage from '@/components/AiUsage.vue'
import {
getUsageBalance,
getUsageBreakdown,
getUsagePermission,
getUsageSeries,
getUsageSummary,
} from '@/api/aiUsage'
vi.mock('@/api/aiUsage', () => ({
getUsagePermission: vi.fn(),
getUsageSummary: vi.fn(),
getUsageSeries: vi.fn(),
getUsageBreakdown: vi.fn(),
getUsageBalance: vi.fn(),
}))
const summaryFixture = (overrides: Record<string, unknown> = {}) => ({
totalCalls: 12,
successCalls: 11,
failedCalls: 1,
promptTokens: 1000,
completionTokens: 2000,
totalTokens: 3000,
cacheHitTokens: 400,
cacheMissTokens: 600,
cacheHitRate: 0.4,
costUsd: 0.0123,
costCny: 0.0861,
avgDurationMs: 7466,
p95DurationMs: 12000,
unreportedUsageCalls: 0,
...overrides,
})
const seriesFixture = [
{ bucket: '2026-10-08', calls: 1, successCalls: 1, failedCalls: 0, promptTokens: 100, completionTokens: 200, costUsd: 0.001 },
{ bucket: '2026-10-09', calls: 4, successCalls: 4, failedCalls: 0, promptTokens: 400, completionTokens: 800, costUsd: 0.004 },
{ bucket: '2026-10-10', calls: 7, successCalls: 6, failedCalls: 1, promptTokens: 500, completionTokens: 1000, costUsd: 0.0073 },
]
const breakdownFixture = [
{
key: 'aggregate-report',
calls: 3,
successCalls: 3,
failedCalls: 0,
promptTokens: 300,
completionTokens: 600,
cacheHitTokens: 100,
costUsd: 0.003,
avgDurationMs: 7000,
},
]
/** 取某张统计卡的可见文案,避免整页 text() 里数字互相干扰 */
const cardText = (wrapper: VueWrapper, label: string) => {
const card = wrapper.findAll('.metric-card').find((item) => item.find('.metric-label').text() === label)
if (!card) throw new Error(`找不到统计卡:${label}`)
return card.text()
}
/**
* 交互式集成测试:真实挂载 AI 用量统计页,覆盖
* 统计卡渲染、null 语义(未上报 / —)、失败重试、白名单拦截、筛选联动。
*/
describe('AI 用量统计交互流程(集成)', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(getUsagePermission).mockResolvedValue({ code: 200, data: { allowed: true } } as never)
vi.mocked(getUsageSummary).mockResolvedValue({ code: 200, data: summaryFixture() } as never)
vi.mocked(getUsageSeries).mockResolvedValue({ code: 200, data: seriesFixture } as never)
vi.mocked(getUsageBreakdown).mockResolvedValue({ code: 200, data: breakdownFixture } as never)
vi.mocked(getUsageBalance).mockResolvedValue({
code: 200,
data: {
configured: true,
currency: 'CNY',
totalBalance: '12.34',
grantedBalance: '0.00',
toppedUpBalance: '12.34',
fetchedAt: '2026-10-10T09:38:23.543Z',
},
} as never)
})
const mountUsage = async () => {
const wrapper = mount(AiUsage, {
global: {
plugins: [ElementPlus],
// el-tag 在 jsdom + VTU 下 vnode mounted 钩子崩溃(EP 2.8),纯视觉组件,stub 掉
stubs: { ElTag: true },
},
})
await flushPromises()
await flushPromises()
return wrapper
}
it('加载完成后展示统计卡、趋势图与明细表', async () => {
const wrapper = await mountUsage()
expect(cardText(wrapper, '总调用')).toContain('12')
expect(cardText(wrapper, '成功率')).toContain('91.7%')
expect(cardText(wrapper, '输入 Token')).toContain('1,000')
expect(cardText(wrapper, '输出 Token')).toContain('2,000')
expect(cardText(wrapper, '缓存命中率')).toContain('40.0%')
expect(cardText(wrapper, '平均耗时')).toContain('7.47 秒')
expect(cardText(wrapper, 'P95 耗时')).toContain('12 秒')
expect(cardText(wrapper, '未上报 usage 的调用数')).toContain('0')
expect(wrapper.findAll('.trend-bar')).toHaveLength(3)
expect(wrapper.find('.trend-chart').text()).toContain('10-08')
expect(wrapper.find('.breakdown-table').text()).toContain('aggregate-report')
})
it('估算费用同时给出 USD 与 CNY,并标注为估算值', async () => {
const wrapper = await mountUsage()
const cost = cardText(wrapper, '估算费用')
expect(cost).toContain('$0.0123')
expect(cost).toContain('¥0.0861')
expect(cost).toContain('估算值')
})
it('未上报的 token 显示「未上报」,命中率分母为 0 时显示「—」', async () => {
vi.mocked(getUsageSummary).mockResolvedValue({
code: 200,
data: summaryFixture({
promptTokens: null,
completionTokens: null,
cacheHitRate: null,
unreportedUsageCalls: 2,
}),
} as never)
const wrapper = await mountUsage()
expect(cardText(wrapper, '输入 Token')).toContain('未上报')
expect(cardText(wrapper, '输出 Token')).toContain('未上报')
expect(cardText(wrapper, '缓存命中率')).toContain('—')
expect(cardText(wrapper, '未上报 usage 的调用数')).toContain('2')
})
it('明细表里的未上报 token 同样不显示成 0', async () => {
vi.mocked(getUsageBreakdown).mockResolvedValue({
code: 200,
data: [{ ...breakdownFixture[0], promptTokens: null, cacheHitTokens: null, costUsd: null }],
} as never)
const wrapper = await mountUsage()
const row = wrapper.find('.breakdown-table tbody tr')
expect(row.text()).toContain('aggregate-report')
expect(row.text()).toContain('未上报')
})
it('接口失败时展示可重试的失败态,重试成功后恢复统计卡', async () => {
vi.mocked(getUsageSummary).mockRejectedValueOnce({ code: 500, message: '服务异常' })
const wrapper = await mountUsage()
expect(wrapper.text()).toContain('用量数据加载失败,请稍后重试')
expect(wrapper.findAll('.metric-card')).toHaveLength(0)
const retry = wrapper.findAll('button').find((button) => button.text().includes('重新加载'))
expect(retry).toBeTruthy()
await retry!.trigger('click')
await flushPromises()
await flushPromises()
expect(getUsageSummary).toHaveBeenCalledTimes(2)
expect(wrapper.text()).not.toContain('用量数据加载失败')
expect(cardText(wrapper, '总调用')).toContain('12')
})
it('非白名单用户看到「没有查看权限」提示态,且不请求用量数据', async () => {
vi.mocked(getUsagePermission).mockResolvedValue({ code: 200, data: { allowed: false } } as never)
const wrapper = await mountUsage()
expect(wrapper.text()).toContain('没有查看权限')
expect(getUsageSummary).not.toHaveBeenCalled()
expect(getUsageSeries).not.toHaveBeenCalled()
expect(getUsageBreakdown).not.toHaveBeenCalled()
expect(wrapper.findAll('.metric-card')).toHaveLength(0)
})
it('上游余额未配置时显示「未配置」,不显示 0', async () => {
vi.mocked(getUsageBalance).mockResolvedValue({ code: 200, data: { configured: false } } as never)
const wrapper = await mountUsage()
const balanceCard = wrapper.find('.balance-card')
expect(balanceCard.text()).toContain('未配置')
expect(balanceCard.text()).not.toContain('0')
})
it('上游余额已配置时展示币种、总余额与赠送/充值明细', async () => {
const wrapper = await mountUsage()
const balanceCard = wrapper.find('.balance-card').text()
expect(balanceCard).toContain('CNY 12.34')
expect(balanceCard).toContain('赠送余额 0.00')
expect(balanceCard).toContain('充值余额 12.34')
})
it('任务类型与模型下拉候选来自不带筛选条件的 breakdown 结果', async () => {
vi.mocked(getUsageBreakdown).mockResolvedValue({
code: 200,
data: [...breakdownFixture, { ...breakdownFixture[0], key: 'generate-mind-map' }],
} as never)
const wrapper = await mountUsage()
expect(getUsageBreakdown).toHaveBeenCalledWith({ groupBy: 'taskType' })
expect(getUsageBreakdown).toHaveBeenCalledWith({ groupBy: 'model' })
const taskTypeSelect = wrapper.findAllComponents({ name: 'ElSelect' })[0]
expect(taskTypeSelect.props('placeholder')).toBe('全部任务类型')
expect(wrapper.findAllComponents({ name: 'ElOption' }).map((option) => option.props('label'))).toEqual(
expect.arrayContaining(['aggregate-report', 'generate-mind-map']),
)
})
it('选择任务类型后按该类型重新拉取汇总', async () => {
const wrapper = await mountUsage()
wrapper.findAllComponents({ name: 'ElSelect' })[0].vm.$emit('update:modelValue', 'guidance')
await flushPromises()
await flushPromises()
expect(getUsageSummary).toHaveBeenLastCalledWith(expect.objectContaining({ taskType: 'guidance' }))
})
it('切换「按模型」后按模型重新拉取明细', async () => {
const wrapper = await mountUsage()
const groupSwitch = wrapper.find('.breakdown-card').findAllComponents({ name: 'ElRadioGroup' })[0]
groupSwitch.vm.$emit('update:modelValue', 'model')
await flushPromises()
await flushPromises()
expect(getUsageBreakdown).toHaveBeenLastCalledWith(expect.objectContaining({ groupBy: 'model' }))
expect(wrapper.find('.breakdown-table').text()).toContain('模型')
})
it('所选时间范围内没有调用时,趋势区给出空态而不是空图', async () => {
vi.mocked(getUsageSeries).mockResolvedValue({ code: 200, data: [] } as never)
const wrapper = await mountUsage()
expect(wrapper.find('.trend-chart').exists()).toBe(false)
expect(wrapper.text()).toContain('所选时间范围内没有调用记录')
})
})
+96
View File
@@ -0,0 +1,96 @@
import request from "@/utils/request";
/** AI 用量查询参数:from / to 为 epoch millis,留空表示由后端取默认范围 */
export interface UsageQueryParams {
from?: number;
to?: number;
taskType?: string;
model?: string;
}
/** 时间序列分桶:day 为 yyyy-MM-dd,hour 为 yyyy-MM-dd HH:00 */
export type UsageBucket = "day" | "hour";
/** 明细分组维度 */
export type UsageGroupBy = "taskType" | "model";
export interface UsagePermission {
allowed: boolean;
}
/**
* 汇总统计。token / 费用 / 耗时字段沿用契约的 null 语义:
* null 表示上游未上报,与「明确上报为 0」不同,界面必须区分展示。
*/
export interface UsageSummary {
totalCalls: number;
successCalls: number;
failedCalls: number;
promptTokens: number | null;
completionTokens: number | null;
totalTokens: number | null;
cacheHitTokens: number | null;
cacheMissTokens: number | null;
/** cacheHitTokens / (cacheHitTokens + cacheMissTokens);分母为 0 时为 null */
cacheHitRate: number | null;
costUsd: number | null;
costCny: number | null;
avgDurationMs: number | null;
p95DurationMs: number | null;
/** prompt_tokens 为 null 的调用数 */
unreportedUsageCalls: number;
}
export interface UsageSeriesPoint {
bucket: string;
calls: number;
successCalls: number;
failedCalls: number;
promptTokens: number | null;
completionTokens: number | null;
costUsd: number | null;
}
export interface UsageBreakdownItem {
/** 分组键:groupBy=taskType 时为任务类型,groupBy=model 时为模型名 */
key: string;
calls: number;
successCalls: number;
failedCalls: number;
promptTokens: number | null;
completionTokens: number | null;
cacheHitTokens: number | null;
costUsd: number | null;
avgDurationMs: number | null;
}
/** 上游余额:未配置或上游失败时只有 configured=false,其余字段缺省 */
export interface UsageBalance {
configured: boolean;
currency?: string;
totalBalance?: string;
grantedBalance?: string;
toppedUpBalance?: string;
fetchedAt?: string;
}
/** 当前用户是否有查看用量统计的权限;非白名单返回 allowed=false 而不是错误 */
export const getUsagePermission = () => {
return request.get<UsagePermission>("/ai/usage/permission");
};
export const getUsageSummary = (params: UsageQueryParams = {}) => {
return request.get<UsageSummary>("/ai/usage/summary", params);
};
export const getUsageSeries = (params: UsageQueryParams & { bucket?: UsageBucket } = {}) => {
return request.get<UsageSeriesPoint[]>("/ai/usage/series", params);
};
export const getUsageBreakdown = (params: UsageQueryParams & { groupBy?: UsageGroupBy } = {}) => {
return request.get<UsageBreakdownItem[]>("/ai/usage/breakdown", params);
};
export const getUsageBalance = () => {
return request.get<UsageBalance>("/ai/usage/balance");
};
+7 -1
View File
@@ -1,7 +1,13 @@
import request from "@/utils/request";
/** 登录响应体:token 用于兼容旧登录态,前端实际靠 Cookie;aiAdmin 决定是否展示 AI 用量入口 */
export interface LoginResult {
token?: string;
aiAdmin?: boolean;
}
export const login = (username: string, password: string) => {
return request.post("/login", { username, password });
return request.post<LoginResult>("/login", { username, password });
};
export const logout = () => {
+704
View File
@@ -0,0 +1,704 @@
<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {
getUsageBalance,
getUsageBreakdown,
getUsagePermission,
getUsageSeries,
getUsageSummary,
type UsageBalance,
type UsageBreakdownItem,
type UsageGroupBy,
type UsageQueryParams,
type UsageSeriesPoint,
type UsageSummary,
} from "@/api/aiUsage";
const DAY_MS = 24 * 60 * 60 * 1000;
type RangeKey = "today" | "7d" | "30d" | "custom";
const rangeOptions: { value: RangeKey; label: string }[] = [
{ value: "today", label: "今天" },
{ value: "7d", label: "最近 7 天" },
{ value: "30d", label: "最近 30 天" },
{ value: "custom", label: "自定义" },
];
const allowed = ref(false);
const permissionChecked = ref(false);
const loading = ref(false);
const loadFailed = ref(false);
const rangeKey = ref<RangeKey>("7d");
const customRange = ref<[string, string] | null>(null);
const taskType = ref("");
const model = ref("");
const groupBy = ref<UsageGroupBy>("taskType");
// 下拉候选来自不带筛选条件的 breakdown,避免在前端硬编码任务类型/模型
const taskTypeOptions = ref<string[]>([]);
const modelOptions = ref<string[]>([]);
const summary = ref<UsageSummary | null>(null);
const series = ref<UsageSeriesPoint[]>([]);
const breakdown = ref<UsageBreakdownItem[]>([]);
const balance = ref<UsageBalance | null>(null);
const balanceFailed = ref(false);
const permissionDenied = computed(() => permissionChecked.value && !allowed.value);
const successRate = computed(() => {
const data = summary.value;
if (!data || !data.totalCalls) return null;
return data.successCalls / data.totalCalls;
});
const queryParams = computed<UsageQueryParams>(() => {
const params: UsageQueryParams = {};
const now = Date.now();
if (rangeKey.value === "today") {
const start = new Date();
start.setHours(0, 0, 0, 0);
params.from = start.getTime();
params.to = now;
} else if (rangeKey.value === "7d") {
params.from = now - 7 * DAY_MS;
params.to = now;
} else if (rangeKey.value === "30d") {
params.from = now - 30 * DAY_MS;
params.to = now;
} else if (customRange.value?.[0] && customRange.value?.[1]) {
const [start, end] = customRange.value;
params.from = new Date(`${start}T00:00:00`).getTime();
params.to = new Date(`${end}T23:59:59.999`).getTime();
}
if (taskType.value) params.taskType = taskType.value;
if (model.value) params.model = model.value;
return params;
});
// ============ 格式化:null 一律与 0 区分 ============
const formatCount = (value: number | null | undefined) =>
typeof value === "number" ? value.toLocaleString("zh-CN") : "—";
const formatTokens = (value: number | null | undefined) =>
typeof value === "number" ? value.toLocaleString("zh-CN") : "未上报";
const formatPercent = (value: number | null | undefined) =>
typeof value === "number" ? `${(value * 100).toFixed(1)}%` : "—";
/** 去掉定点小数尾部多余的 0,避免 $0.012300 这类噪声 */
const trimZeros = (value: number, digits: number) => String(Number(value.toFixed(digits)));
const formatUsd = (value: number | null | undefined) =>
typeof value === "number" ? `$${trimZeros(value, 6)}` : "未上报";
const formatCny = (value: number | null | undefined) =>
typeof value === "number" ? `¥${trimZeros(value, 6)}` : "未上报";
const formatDuration = (value: number | null | undefined) => {
if (typeof value !== "number") return "—";
if (value < 1000) return `${value} 毫秒`;
return `${trimZeros(value / 1000, 2)} 秒`;
};
const formatFetchedAt = (value?: string) => {
if (!value) return "—";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return "—";
return date.toLocaleString("zh-CN");
};
// ============ 内联 SVG 趋势图(不引入图表库) ============
const CHART = { height: 200, top: 16, right: 12, bottom: 28, left: 48 };
// 每个数据点占的横向单位数;宽度按点数算出来,svg 再 1:1 渲染,
// 这样坐标文字不会随容器缩放而变糊,窄屏改为横向滚动。
const CHART_POINT_WIDTH = 36;
const CHART_MIN_WIDTH = 640;
const shortBucket = (bucket: string) => (bucket.length >= 10 ? bucket.slice(5) : bucket);
const chartWidth = computed(() => Math.max(CHART_MIN_WIDTH, series.value.length * CHART_POINT_WIDTH));
const chart = computed(() => {
const points = series.value;
const width = chartWidth.value;
const plotWidth = width - CHART.left - CHART.right;
const plotHeight = CHART.height - CHART.top - CHART.bottom;
const max = Math.max(1, ...points.map((point) => Number(point.calls) || 0));
const slot = points.length > 0 ? plotWidth / points.length : plotWidth;
const barWidth = Math.max(2, Math.min(32, slot * 0.6));
const bars = points.map((point, index) => {
const value = Number(point.calls) || 0;
const height = (value / max) * plotHeight;
return {
bucket: point.bucket,
value,
x: CHART.left + slot * index + (slot - barWidth) / 2,
y: CHART.top + plotHeight - height,
width: barWidth,
height: Math.max(value > 0 ? 1 : 0, height),
};
});
// x 轴最多标 6 个日期,避免挤在一起
const labelStep = Math.max(1, Math.ceil(points.length / 6));
const labels = points
.map((point, index) => ({ index, bucket: point.bucket }))
.filter((item) => item.index % labelStep === 0 || item.index === points.length - 1)
.map((item) => ({
bucket: item.bucket,
x: CHART.left + slot * item.index + slot / 2,
}));
return {
width,
height: CHART.height,
left: CHART.left,
top: CHART.top,
plotWidth,
plotHeight,
max,
bars,
labels,
};
});
// ============ 数据加载 ============
const loadOptions = async () => {
try {
const [taskTypeRes, modelRes] = await Promise.all([
getUsageBreakdown({ groupBy: "taskType" }),
getUsageBreakdown({ groupBy: "model" }),
]);
taskTypeOptions.value = (taskTypeRes?.data || []).map((item) => item.key);
modelOptions.value = (modelRes?.data || []).map((item) => item.key);
} catch {
// 候选缺失不阻塞统计主体,下拉保持为空
}
};
const loadBalance = async () => {
balanceFailed.value = false;
try {
const res = await getUsageBalance();
balance.value = res?.data ?? null;
} catch {
// 余额是辅助信息:失败要区别于「未配置」,不能显示成 0
balance.value = null;
balanceFailed.value = true;
}
};
const loadUsage = async () => {
const params = queryParams.value;
const [summaryRes, seriesRes, breakdownRes] = await Promise.all([
getUsageSummary(params),
getUsageSeries({ ...params, bucket: "day" }),
getUsageBreakdown({ ...params, groupBy: groupBy.value }),
]);
summary.value = summaryRes?.data ?? null;
series.value = seriesRes?.data || [];
breakdown.value = breakdownRes?.data || [];
};
const init = async () => {
if (loading.value) return;
loading.value = true;
loadFailed.value = false;
try {
const permissionRes = await getUsagePermission();
permissionChecked.value = true;
allowed.value = permissionRes?.data?.allowed === true;
if (!allowed.value) return;
void loadOptions();
void loadBalance();
await loadUsage();
} catch {
// 请求层已提示具体错误,这里保证失败态可重试,而不是留空白
loadFailed.value = true;
} finally {
loading.value = false;
}
};
const reload = async () => {
if (!allowed.value || loading.value) return;
loading.value = true;
loadFailed.value = false;
try {
await loadUsage();
} catch {
loadFailed.value = true;
} finally {
loading.value = false;
}
};
watch([rangeKey, customRange, taskType, model, groupBy], () => {
// 切到自定义但还没选区间时不发无意义的请求
if (rangeKey.value === "custom" && !customRange.value) return;
void reload();
});
onMounted(() => {
void init();
});
</script>
<template>
<section class="ai-usage-page">
<div v-if="permissionDenied" class="surface-card permission-card">
<h2>没有查看权限</h2>
<p>当前账号不在 AI 用量统计的白名单内,如需查看请联系管理员。</p>
</div>
<template v-else>
<div class="filter-bar surface-card">
<div class="filter-item">
<span class="filter-label">时间范围</span>
<el-radio-group v-model="rangeKey" size="small">
<el-radio-button
v-for="option in rangeOptions"
:key="option.value"
:value="option.value"
>
{{ option.label }}
</el-radio-button>
</el-radio-group>
</div>
<div v-if="rangeKey === 'custom'" class="filter-item">
<span class="filter-label">自定义区间</span>
<el-date-picker
v-model="customRange"
class="custom-range"
type="daterange"
value-format="YYYY-MM-DD"
range-separator="至"
start-placeholder="开始日期"
end-placeholder="结束日期"
size="small"
/>
</div>
<div class="filter-item">
<span class="filter-label">任务类型</span>
<el-select
v-model="taskType"
class="filter-select"
placeholder="全部任务类型"
clearable
size="small"
>
<el-option v-for="key in taskTypeOptions" :key="key" :label="key" :value="key" />
</el-select>
</div>
<div class="filter-item">
<span class="filter-label">模型</span>
<el-select
v-model="model"
class="filter-select"
placeholder="全部模型"
clearable
size="small"
>
<el-option v-for="key in modelOptions" :key="key" :label="key" :value="key" />
</el-select>
</div>
</div>
<div v-loading="loading" class="usage-body">
<el-empty v-if="loadFailed" description="用量数据加载失败,请稍后重试">
<el-button type="success" plain @click="init">重新加载</el-button>
</el-empty>
<template v-else-if="summary">
<div class="metric-grid">
<article class="surface-card metric-card">
<span class="metric-label">总调用</span>
<strong class="metric-value">{{ formatCount(summary.totalCalls) }}</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">成功率</span>
<strong class="metric-value">{{ formatPercent(successRate) }}</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">输入 Token</span>
<strong class="metric-value" :class="{ 'metric-muted': summary.promptTokens === null }">
{{ formatTokens(summary.promptTokens) }}
</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">输出 Token</span>
<strong class="metric-value" :class="{ 'metric-muted': summary.completionTokens === null }">
{{ formatTokens(summary.completionTokens) }}
</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">缓存命中率</span>
<strong class="metric-value">{{ formatPercent(summary.cacheHitRate) }}</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">估算费用</span>
<strong class="metric-value" :class="{ 'metric-muted': summary.costUsd === null }">
{{ formatUsd(summary.costUsd) }}
</strong>
<span class="metric-note">≈ {{ formatCny(summary.costCny) }} · 估算值</span>
</article>
<article class="surface-card metric-card">
<span class="metric-label">平均耗时</span>
<strong class="metric-value">{{ formatDuration(summary.avgDurationMs) }}</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">P95 耗时</span>
<strong class="metric-value">{{ formatDuration(summary.p95DurationMs) }}</strong>
</article>
<article class="surface-card metric-card">
<span class="metric-label">未上报 usage 的调用数</span>
<strong class="metric-value">{{ formatCount(summary.unreportedUsageCalls) }}</strong>
</article>
</div>
<article class="surface-card trend-card">
<div class="card-head">
<h3>按天趋势</h3>
<span class="metric-note">柱高为该天的调用次数</span>
</div>
<div v-if="series.length > 0" class="trend-scroll">
<svg
class="trend-chart"
:viewBox="`0 0 ${chart.width} ${chart.height}`"
:style="{ minWidth: `${chart.width}px` }"
role="img"
aria-label="按天调用次数趋势"
>
<line
class="trend-axis"
:x1="chart.left"
:y1="chart.top + chart.plotHeight"
:x2="chart.left + chart.plotWidth"
:y2="chart.top + chart.plotHeight"
/>
<rect
v-for="bar in chart.bars"
:key="bar.bucket"
class="trend-bar"
:x="bar.x"
:y="bar.y"
:width="bar.width"
:height="bar.height"
>
<title>{{ bar.bucket }}:{{ bar.value }} 次调用</title>
</rect>
<text
v-for="label in chart.labels"
:key="label.bucket"
class="trend-label"
:x="label.x"
:y="chart.height - 8"
text-anchor="middle"
>
{{ shortBucket(label.bucket) }}
</text>
<text
class="trend-label"
:x="chart.left - 8"
:y="chart.top + 10"
text-anchor="end"
>
{{ chart.max }}
</text>
</svg>
</div>
<p v-else class="empty-hint">所选时间范围内没有调用记录</p>
</article>
<article class="surface-card breakdown-card">
<div class="card-head">
<h3>用量明细</h3>
<el-radio-group v-model="groupBy" size="small">
<el-radio-button value="taskType">按任务类型</el-radio-button>
<el-radio-button value="model">按模型</el-radio-button>
</el-radio-group>
</div>
<div class="table-scroll">
<table class="breakdown-table">
<thead>
<tr>
<th>{{ groupBy === "taskType" ? "任务类型" : "模型" }}</th>
<th>调用</th>
<th>成功</th>
<th>失败</th>
<th>输入 Token</th>
<th>输出 Token</th>
<th>缓存命中 Token</th>
<th>估算费用</th>
<th>平均耗时</th>
</tr>
</thead>
<tbody>
<tr v-for="row in breakdown" :key="row.key">
<td class="key-cell">{{ row.key }}</td>
<td>{{ formatCount(row.calls) }}</td>
<td>{{ formatCount(row.successCalls) }}</td>
<td>{{ formatCount(row.failedCalls) }}</td>
<td>{{ formatTokens(row.promptTokens) }}</td>
<td>{{ formatTokens(row.completionTokens) }}</td>
<td>{{ formatTokens(row.cacheHitTokens) }}</td>
<td>{{ formatUsd(row.costUsd) }}</td>
<td>{{ formatDuration(row.avgDurationMs) }}</td>
</tr>
<tr v-if="breakdown.length === 0">
<td class="empty-cell" colspan="9">所选时间范围内没有用量明细</td>
</tr>
</tbody>
</table>
</div>
</article>
<article class="surface-card balance-card">
<div class="card-head">
<span class="metric-label">上游账户余额</span>
<span class="metric-note">数据来自模型服务商</span>
</div>
<template v-if="balance?.configured">
<strong class="metric-value">
{{ balance.currency || "CNY" }} {{ balance.totalBalance }}
</strong>
<span class="metric-note">
赠送余额 {{ balance.grantedBalance || "—" }} · 充值余额 {{ balance.toppedUpBalance || "—" }}
</span>
<span class="metric-note">更新于 {{ formatFetchedAt(balance.fetchedAt) }}</span>
</template>
<template v-else-if="balanceFailed">
<strong class="metric-value metric-muted">余额获取失败</strong>
<el-button text size="small" class="balance-retry" @click="loadBalance">重试</el-button>
</template>
<strong v-else-if="balance" class="metric-value metric-muted">未配置</strong>
<span v-else class="metric-value metric-muted">加载中…</span>
</article>
</template>
</div>
</template>
</section>
</template>
<style scoped>
.ai-usage-page {
display: flex;
flex-direction: column;
gap: 14px;
}
.permission-card {
padding: 28px 22px;
}
.permission-card h2 {
margin: 0 0 8px;
font-size: 20px;
color: var(--green-900);
}
.permission-card p {
margin: 0;
color: var(--text-secondary);
}
.filter-bar {
padding: 12px 16px;
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 12px 20px;
}
.filter-item {
display: flex;
align-items: center;
gap: 8px;
}
.filter-label {
font-size: 13px;
color: var(--text-secondary);
white-space: nowrap;
}
.filter-select {
width: 180px;
}
.usage-body {
display: flex;
flex-direction: column;
gap: 14px;
min-height: 120px;
}
.metric-grid {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
}
.metric-card {
padding: 14px 16px;
display: flex;
flex-direction: column;
gap: 4px;
}
.metric-label {
font-size: 13px;
color: var(--text-secondary);
}
.metric-value {
font-size: 24px;
line-height: 1.2;
color: var(--green-900);
overflow-wrap: anywhere;
}
.metric-muted {
color: var(--text-secondary);
}
.metric-note {
font-size: 12px;
color: var(--text-secondary);
}
.card-head {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px 12px;
}
.card-head h3 {
margin: 0;
font-size: 15px;
color: var(--green-900);
}
.trend-card,
.breakdown-card,
.balance-card {
padding: 16px 18px;
display: flex;
flex-direction: column;
gap: 12px;
}
.trend-scroll {
overflow-x: auto;
}
.trend-chart {
display: block;
width: 100%;
height: 200px;
}
.trend-bar {
fill: var(--green-600);
}
.trend-bar:hover {
fill: var(--green-700);
}
.trend-axis {
stroke: var(--border-soft);
stroke-width: 1;
}
.trend-label {
fill: var(--text-secondary);
font-size: 11px;
}
.empty-hint {
margin: 0;
font-size: 13px;
color: var(--text-secondary);
}
.table-scroll {
overflow-x: auto;
}
.breakdown-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.breakdown-table th,
.breakdown-table td {
padding: 8px 10px;
text-align: right;
white-space: nowrap;
border-bottom: 1px solid var(--border-soft);
}
.breakdown-table th {
color: var(--text-secondary);
font-weight: 600;
}
.breakdown-table td {
color: var(--text-primary);
}
.breakdown-table th:first-child,
.breakdown-table td:first-child {
text-align: left;
}
.key-cell {
color: var(--green-800);
font-weight: 600;
}
.empty-cell {
text-align: center !important;
color: var(--text-secondary);
}
.balance-retry {
align-self: flex-start;
padding: 0;
}
@media (max-width: 900px) {
.metric-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
@media (max-width: 768px) {
.filter-bar {
flex-direction: column;
align-items: stretch;
}
.filter-item {
flex-direction: column;
align-items: stretch;
}
.filter-select,
.custom-range {
width: 100%;
}
.metric-grid {
grid-template-columns: 1fr;
}
}
</style>
+2
View File
@@ -40,6 +40,8 @@ const submitForm = async (formEl: FormInstance | undefined) => {
const result = await login(registerData.username, registerData.password);
if (result.code === 200) {
localStorage.setItem("isLoggedIn", "true");
// 白名单标记:非管理员也要写 false,避免上一个账号的入口残留
localStorage.setItem("aiAdmin", String(result.data?.aiAdmin === true));
ElMessage.success(result.message);
await router.push("/welcome");
} else {
+40 -3
View File
@@ -15,6 +15,14 @@
<p class="brand-title">学习进度跟踪系统</p>
<p class="brand-subtitle">把学习变成可记录、可回顾、可持续的日常流程</p>
</div>
<el-button
v-if="showAiUsageEntry"
plain
class="ai-usage-btn"
@click="openAiUsage"
>
AI 用量统计
</el-button>
<el-button
v-if="!isLoginRoute"
type="success"
@@ -29,7 +37,7 @@
</template>
<script setup lang="ts">
import { computed, ref } from "vue";
import { computed, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import router from "@/router";
@@ -46,6 +54,22 @@ const backLabel = computed(() => (route.meta?.backLabel as string | undefined) |
const backUseHistory = computed(() => route.meta?.backUseHistory === true);
const loggingOut = ref(false);
// 白名单来自登录响应写入的 localStorage;头部组件只挂载一次,
// 因此换账号登录后要按路由变化重新读取,避免残留上一个账号的入口。
const aiAdmin = ref(localStorage.getItem("aiAdmin") === "true");
const showAiUsageEntry = computed(() => !isLoginRoute.value && aiAdmin.value);
watch(
() => route.path,
() => {
aiAdmin.value = localStorage.getItem("aiAdmin") === "true";
},
);
const openAiUsage = () => {
router.push("/ai-usage");
};
const goBack = () => {
if (backUseHistory.value && window.history.state?.back) {
router.back();
@@ -64,6 +88,7 @@ const handleLogout = async () => {
// 后端退出失败时,仍然清理前端登录态,避免用户被卡住。
}
localStorage.removeItem("isLoggedIn");
localStorage.removeItem("aiAdmin");
ElMessage.success("已退出登录");
await router.push("/login");
} finally {
@@ -71,7 +96,7 @@ const handleLogout = async () => {
}
};
defineExpose({ isLoginRoute, showBackButton, pageTitle, backTo, backLabel, loggingOut, goBack, handleLogout });
defineExpose({ isLoginRoute, showBackButton, pageTitle, backTo, backLabel, loggingOut, goBack, handleLogout, showAiUsageEntry, openAiUsage });
</script>
<style scoped>
@@ -121,13 +146,25 @@ defineExpose({ isLoginRoute, showBackButton, pageTitle, backTo, backLabel, loggi
color: var(--green-700);
}
/* 次级入口:中性描边,不与主按钮「退出登录」抢视觉 */
.ai-usage-btn {
border-color: var(--border-soft);
color: var(--green-700);
}
.ai-usage-btn:hover {
border-color: var(--green-600);
color: var(--green-800);
}
@media (max-width: 768px) {
.head {
align-items: flex-start;
flex-direction: column;
}
.logout-btn {
.logout-btn,
.ai-usage-btn {
width: 100%;
}
}
+5
View File
@@ -53,6 +53,11 @@ const routes: RouteRecordRaw[] = [
component: () => import("@/components/TagReview.vue"),
meta: { requiresAuth: true, title: "按标签复习", wide: true },
},
{
path: "/ai-usage",
component: () => import("@/components/AiUsage.vue"),
meta: { requiresAuth: true, title: "AI 用量统计" },
},
{
path: "/start-task/:taskNum",
name: "start-task",