feat: 用量明细支持按用户分组与筛选

- 分组维度增加「按用户」,首列渲染 label(用户名),未归属单独成行
- 新增用户筛选下拉,选项来自 groupBy=user,未归属不进下拉
This commit is contained in:
2026-10-10 20:08:51 +08:00
parent 0a728cfba8
commit a69b350829
5 changed files with 132 additions and 11 deletions
+4
View File
@@ -53,6 +53,10 @@ lpt-fe/src/
> 「AI 用量统计」的数据全部来自 `lpt-be` 的 `/ai/usage/*`(不直连 lpt-ai),
> 页面只展示聚合数字与费用,**不含 prompt 与学习内容**(完整日志仍在 lpt-ai 的 `/admin`)。
> 入口显隐读登录响应写入的 `localStorage.aiAdmin`,真正的权限校验在服务端。
>
> 支持三个分组维度:任务类型 / 模型 / **用户**(`groupBy=user`)。用户维度靠 lpt-be 落库的归属字段,
> 未归属的记录单独成行(`key` 为 null、`label` 为「未归属」),并且**不进用户筛选下拉**——
> 它不是一个可筛选的用户。明细表首列渲染 `label ?? key`。
## 认证与请求
+16
View File
@@ -43,6 +43,16 @@ describe('aiUsage API', () => {
})
})
it('getUsageSummary can filter by the owning user', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
await getUsageSummary({ from: 1000, to: 2000, userId: 'U-1' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/summary', {
from: 1000,
to: 2000,
userId: 'U-1',
})
})
it('getUsageSummary sends no filters by default', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: {} })
await getUsageSummary()
@@ -69,6 +79,12 @@ describe('aiUsage API', () => {
})
})
it('getUsageBreakdown supports the user dimension', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
await getUsageBreakdown({ groupBy: 'user' })
expect(mockedRequest.get).toHaveBeenCalledWith('/ai/usage/breakdown', { groupBy: 'user' })
})
it('getUsageBreakdown can be called without filters to derive dropdown options', async () => {
mockedRequest.get.mockResolvedValue({ code: 200, data: [] })
await getUsageBreakdown({ groupBy: 'taskType' })
@@ -249,4 +249,60 @@ describe('AI 用量统计交互流程(集成)', () => {
expect(wrapper.find('.trend-chart').exists()).toBe(false)
expect(wrapper.text()).toContain('所选时间范围内没有调用记录')
})
/** 用户维度的明细:一条有归属、一条未归属(key 为 null) */
const userBreakdownFixture = [
{ ...breakdownFixture[0], key: 'U-1', label: 'cat', costUsd: 0.003 },
{ ...breakdownFixture[0], key: null, label: '未归属', costUsd: 0.0005 },
]
/** 按分组维度返回不同数据,才能验证「按用户」确实换了取数维度 */
const mockBreakdownByGroup = () => {
vi.mocked(getUsageBreakdown).mockImplementation(async (params) => {
const data = params?.groupBy === 'user' ? userBreakdownFixture : breakdownFixture
return { code: 200, data } as never
})
}
it('切换到「按用户」后展示用户名,未归属单独成行', async () => {
mockBreakdownByGroup()
const wrapper = await mountUsage()
const groupSwitch = wrapper.find('.breakdown-card').findAllComponents({ name: 'ElRadioGroup' })[0]
groupSwitch.vm.$emit('update:modelValue', 'user')
await flushPromises()
await flushPromises()
expect(getUsageBreakdown).toHaveBeenLastCalledWith(expect.objectContaining({ groupBy: 'user' }))
const table = wrapper.find('.breakdown-table')
expect(table.text()).toContain('用户')
// 展示的是用户名,而不是用户 id
expect(table.text()).toContain('cat')
expect(table.text()).not.toContain('U-1')
// 归属链路断了也要看得出来,不能静默合并进某个用户
expect(table.text()).toContain('未归属')
})
it('用户下拉列出来用户名,且不把「未归属」当成可筛选的用户', async () => {
mockBreakdownByGroup()
const wrapper = await mountUsage()
const userSelect = wrapper.findAllComponents({ name: 'ElSelect' })[2]
expect(userSelect.props('placeholder')).toBe('全部用户')
const labels = wrapper.findAllComponents({ name: 'ElOption' }).map((option) => option.props('label'))
expect(labels).toContain('cat')
expect(labels).not.toContain('未归属')
})
it('选择用户后按该用户重新拉取汇总', async () => {
mockBreakdownByGroup()
const wrapper = await mountUsage()
wrapper.findAllComponents({ name: 'ElSelect' })[2].vm.$emit('update:modelValue', 'U-1')
await flushPromises()
await flushPromises()
expect(getUsageSummary).toHaveBeenLastCalledWith(expect.objectContaining({ userId: 'U-1' }))
})
})
+11 -4
View File
@@ -6,13 +6,15 @@ export interface UsageQueryParams {
to?: number;
taskType?: string;
model?: string;
/** 归属用户 id;未归属的记录不会出现在任何用户的筛选结果里 */
userId?: string;
}
/** 时间序列分桶:day 为 yyyy-MM-dd,hour 为 yyyy-MM-dd HH:00 */
export type UsageBucket = "day" | "hour";
/** 明细分组维度 */
export type UsageGroupBy = "taskType" | "model";
/** 明细分组维度;`user` 是用户维度报表(归属靠上报的 callerRef) */
export type UsageGroupBy = "taskType" | "model" | "user";
export interface UsagePermission {
allowed: boolean;
@@ -52,8 +54,13 @@ export interface UsageSeriesPoint {
}
export interface UsageBreakdownItem {
/** 分组键:groupBy=taskType 时为任务类型,groupBy=model 时为模型名 */
key: string;
/**
* 分组键:`groupBy=user` 时是用户 id;未归属的记录为 `null`。
* 其余分组维度下永远是原值(非 null)。
*/
key: string | null;
/** 展示名:`groupBy=user` 时是用户名(未归属为「未归属」);其余维度等于 `key` */
label?: string | null;
calls: number;
successCalls: number;
failedCalls: number;
+45 -7
View File
@@ -34,11 +34,14 @@ const rangeKey = ref<RangeKey>("7d");
const customRange = ref<[string, string] | null>(null);
const taskType = ref("");
const model = ref("");
const userId = ref("");
const groupBy = ref<UsageGroupBy>("taskType");
// 下拉候选来自不带筛选条件的 breakdown,避免在前端硬编码任务类型/模型
const taskTypeOptions = ref<string[]>([]);
const modelOptions = ref<string[]>([]);
/** 用户筛选:value 是用户 id,label 是用户名(两者不同,不能复用字符串数组) */
const userOptions = ref<{ value: string; label: string }[]>([]);
const summary = ref<UsageSummary | null>(null);
const series = ref<UsageSeriesPoint[]>([]);
@@ -75,9 +78,17 @@ const queryParams = computed<UsageQueryParams>(() => {
}
if (taskType.value) params.taskType = taskType.value;
if (model.value) params.model = model.value;
if (userId.value) params.userId = userId.value;
return params;
});
/** 明细表首列标题:随分组维度切换 */
const groupColumnLabel = computed(() => {
if (groupBy.value === "model") return "模型";
if (groupBy.value === "user") return "用户";
return "任务类型";
});
// ============ 格式化:null 一律与 0 区分 ============
const formatCount = (value: number | null | undefined) =>
@@ -169,12 +180,21 @@ const chart = computed(() => {
const loadOptions = async () => {
try {
const [taskTypeRes, modelRes] = await Promise.all([
const [taskTypeRes, modelRes, userRes] = await Promise.all([
getUsageBreakdown({ groupBy: "taskType" }),
getUsageBreakdown({ groupBy: "model" }),
getUsageBreakdown({ groupBy: "user" }),
]);
taskTypeOptions.value = (taskTypeRes?.data || []).map((item) => item.key);
modelOptions.value = (modelRes?.data || []).map((item) => item.key);
taskTypeOptions.value = (taskTypeRes?.data || [])
.map((item) => item.key)
.filter((key): key is string => key != null);
modelOptions.value = (modelRes?.data || [])
.map((item) => item.key)
.filter((key): key is string => key != null);
// 「未归属」的 key 是 null,不是一个可筛选的「用户」,不进下拉
userOptions.value = (userRes?.data || [])
.filter((item) => item.key != null)
.map((item) => ({ value: item.key as string, label: item.label || (item.key as string) }));
} catch {
// 候选缺失不阻塞统计主体,下拉保持为空
}
@@ -237,7 +257,7 @@ const reload = async () => {
}
};
watch([rangeKey, customRange, taskType, model, groupBy], () => {
watch([rangeKey, customRange, taskType, model, userId, groupBy], () => {
// 切到自定义但还没选区间时不发无意义的请求
if (rangeKey.value === "custom" && !customRange.value) return;
void reload();
@@ -306,6 +326,23 @@ onMounted(() => {
<el-option v-for="key in modelOptions" :key="key" :label="key" :value="key" />
</el-select>
</div>
<div class="filter-item">
<span class="filter-label">用户</span>
<el-select
v-model="userId"
class="filter-select"
placeholder="全部用户"
clearable
size="small"
>
<el-option
v-for="item in userOptions"
:key="item.value"
:label="item.label"
:value="item.value"
/>
</el-select>
</div>
</div>
<div v-loading="loading" class="usage-body">
@@ -420,13 +457,14 @@ onMounted(() => {
<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-button value="user">按用户</el-radio-button>
</el-radio-group>
</div>
<div class="table-scroll">
<table class="breakdown-table">
<thead>
<tr>
<th>{{ groupBy === "taskType" ? "任务类型" : "模型" }}</th>
<th>{{ groupColumnLabel }}</th>
<th>调用</th>
<th>成功</th>
<th>失败</th>
@@ -438,8 +476,8 @@ onMounted(() => {
</tr>
</thead>
<tbody>
<tr v-for="row in breakdown" :key="row.key">
<td class="key-cell">{{ row.key }}</td>
<tr v-for="row in breakdown" :key="row.key ?? row.label ?? ''">
<td class="key-cell">{{ row.label ?? row.key }}</td>
<td>{{ formatCount(row.calls) }}</td>
<td>{{ formatCount(row.successCalls) }}</td>
<td>{{ formatCount(row.failedCalls) }}</td>