From a69b3508299cd36f41cd27c609d2931b3e7834cc Mon Sep 17 00:00:00 2001 From: cat-shark <1716967236@qq.com> Date: Sat, 10 Oct 2026 20:08:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=94=A8=E9=87=8F=E6=98=8E=E7=BB=86?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E6=8C=89=E7=94=A8=E6=88=B7=E5=88=86=E7=BB=84?= =?UTF-8?q?=E4=B8=8E=E7=AD=9B=E9=80=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 分组维度增加「按用户」,首列渲染 label(用户名),未归属单独成行 - 新增用户筛选下拉,选项来自 groupBy=user,未归属不进下拉 --- AGENTS.md | 4 ++ src/__tests__/api/aiUsage.spec.ts | 16 ++++++ .../integration/ai-usage-flow.spec.ts | 56 +++++++++++++++++++ src/api/aiUsage.ts | 15 +++-- src/components/AiUsage.vue | 52 ++++++++++++++--- 5 files changed, 132 insertions(+), 11 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c27801c..bda4feb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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`。 ## 认证与请求 diff --git a/src/__tests__/api/aiUsage.spec.ts b/src/__tests__/api/aiUsage.spec.ts index 753b414..9f63f0c 100644 --- a/src/__tests__/api/aiUsage.spec.ts +++ b/src/__tests__/api/aiUsage.spec.ts @@ -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' }) diff --git a/src/__tests__/integration/ai-usage-flow.spec.ts b/src/__tests__/integration/ai-usage-flow.spec.ts index efa9e8a..0987aba 100644 --- a/src/__tests__/integration/ai-usage-flow.spec.ts +++ b/src/__tests__/integration/ai-usage-flow.spec.ts @@ -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' })) + }) }) diff --git a/src/api/aiUsage.ts b/src/api/aiUsage.ts index 97b610c..6825ae7 100644 --- a/src/api/aiUsage.ts +++ b/src/api/aiUsage.ts @@ -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; diff --git a/src/components/AiUsage.vue b/src/components/AiUsage.vue index 9e1319c..e1347ab 100644 --- a/src/components/AiUsage.vue +++ b/src/components/AiUsage.vue @@ -34,11 +34,14 @@ const rangeKey = ref("7d"); const customRange = ref<[string, string] | null>(null); const taskType = ref(""); const model = ref(""); +const userId = ref(""); const groupBy = ref("taskType"); // 下拉候选来自不带筛选条件的 breakdown,避免在前端硬编码任务类型/模型 const taskTypeOptions = ref([]); const modelOptions = ref([]); +/** 用户筛选:value 是用户 id,label 是用户名(两者不同,不能复用字符串数组) */ +const userOptions = ref<{ value: string; label: string }[]>([]); const summary = ref(null); const series = ref([]); @@ -75,9 +78,17 @@ const queryParams = computed(() => { } 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(() => { +
+ 用户 + + + +
@@ -420,13 +457,14 @@ onMounted(() => { 按任务类型 按模型 + 按用户
- + @@ -438,8 +476,8 @@ onMounted(() => { - - + +
{{ groupBy === "taskType" ? "任务类型" : "模型" }}{{ groupColumnLabel }} 调用 成功 失败
{{ row.key }}
{{ row.label ?? row.key }} {{ formatCount(row.calls) }} {{ formatCount(row.successCalls) }} {{ formatCount(row.failedCalls) }}