feat: 操作审计支持按筛选条件导出 CSV

- 后端新增导出端点 GET /apis/audit.guichumo.com/v1alpha1/auditlogs/-/export:
  筛选参数与 query 完全一致(条件构造抽取为 AuditLogFilters 共用),
  按时间升序分批(每批 200)遍历全量、流式输出 UTF-8 BOM CSV(Excel/WPS 直开),
  字段引号转义 + 公式注入防护;列含 describeOperation 移植版中文操作描述(OperationDescription)
- role-template 追加 auditlogs/export(动词仍 get/list,保持只读语义)
- Console 列表页工具栏新增「导出」按钮:按当前筛选条件 fetch → blob → a[download] 下载
- 测试:后端新增导出端点/分批取数/CSV 转义/操作描述用例(71 个全绿),
  前端新增导出链路结构性回归 spec(31 个全绿)+ vue-tsc 通过
- 文档:设计文档 V2 规划项标注已实现,README 补导出说明
This commit is contained in:
2026-11-21 21:28:03 +08:00
parent 3abd79a65f
commit 058596c0ea
13 changed files with 880 additions and 88 deletions
@@ -0,0 +1,63 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
// 结构性回归测试:不渲染组件,仅检查 SFC 源码中的导出功能链路。
// 导出为按当前筛选条件的全量 CSV 下载:工具栏「导出」按钮 → fetch 导出端点
// (筛选参数与 query 一致,但去掉分页参数)→ blob 触发 a[download] 下载,
// 期间按钮进入 loading、失败走顶部 VAlert 错误提示。
// 历史上本功能不存在,本测试锁定端点路径与下载链路形态,防止路径漂移或链路残缺。
const sfc = readFileSync(fileURLToPath(new URL('./AuditLogList.vue', import.meta.url)), 'utf-8')
describe('AuditLogList 导出', () => {
it('声明与后端一致的导出端点路径', () => {
expect(sfc).toContain(
"const EXPORT_ENDPOINT =\n '/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'",
)
})
it('工具栏导出按钮:IconSave 图标、loading 绑定 exporting、点击 exportLogs', () => {
// 导出按钮位于 VPageHeader #actions 的 VSpace 内,与「刷新」并列
const actionsStart = sfc.indexOf('<template #actions>')
expect(actionsStart).toBeGreaterThan(-1)
const actionsEnd = sfc.indexOf('</VSpace>', actionsStart)
const actions = sfc.slice(actionsStart, actionsEnd)
expect(actions).toMatch(/<VButton :loading="exporting"[^>]*@click="exportLogs">/)
expect(actions).toContain('<IconSave class="h-full w-full" />')
expect(actions).toContain('导出')
expect(actions).toContain('刷新')
})
it('导出前去掉分页参数(导出为全量接口)', () => {
const fnStart = sfc.indexOf('async function exportLogs()')
expect(fnStart).toBeGreaterThan(-1)
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
expect(fn).toContain('new URLSearchParams(buildQuery())')
expect(fn).toContain("params.delete('page')")
expect(fn).toContain("params.delete('size')")
})
it('下载链路:fetch 非 ok 报错进 VAlert,blob → createObjectURL → a[download]', () => {
const fnStart = sfc.indexOf('async function exportLogs()')
const fn = sfc.slice(fnStart, sfc.indexOf('function resetFilter()', fnStart))
// 错误语义与查询一致:HTTP 非 2xx 抛错并写入 error(顶部 VAlert 展示)
expect(fn).toMatch(/throw new Error\(`导出失败(HTTP \$\{response\.status\})`\)/)
expect(fn).toContain('error.value = e instanceof Error ? e.message : String(e)')
expect(fn).toContain('await response.blob()')
expect(fn).toContain('URL.createObjectURL(blob)')
expect(fn).toMatch(/anchor\.download = exportFilename\(\)/)
expect(fn).toContain('anchor.click()')
expect(fn).toContain('URL.revokeObjectURL(url)')
// 无论成败都复位按钮 loading
expect(fn).toMatch(/finally\s*\{\s*exporting\.value = false\s*\}/)
})
it('导出文件名不含冒号/空格(Windows 文件名非法字符)', () => {
const fnStart = sfc.indexOf('function exportFilename()')
expect(fnStart).toBeGreaterThan(-1)
const fn = sfc.slice(fnStart, sfc.indexOf('/** 按当前筛选条件导出全部记录', fnStart))
expect(fn).toContain("audit-logs-${now.getFullYear()}")
expect(fn).not.toMatch(/getMinutes\(\)\}:/) // 不出现冒号拼接
expect(fn).toMatch(/\.csv/)
})
})
@@ -12,6 +12,7 @@ import {
VSpace,
VAlert,
IconRefreshLine,
IconSave,
} from '@halo-dev/components'
import type { AuditLog, ListResult } from '@/utils/audit'
import {
@@ -28,12 +29,17 @@ import AuditLogDetail from './AuditLogDetail.vue'
const QUERY_ENDPOINT =
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/query'
/** 导出端点路径:筛选参数与 query 一致,全量 CSV 附件下载(与 AuditQueryEndpoint 保持一致)。 */
const EXPORT_ENDPOINT =
'/apis/audit.guichumo.com/v1alpha1/auditlogs/-/export'
const RESOURCE_TYPES = [
'posts', 'comments', 'users', 'roles', 'auth', 'settings', 'configmaps',
'plugins', 'themes', 'attachments', 'menus', 'categories', 'tags',
]
const loading = ref(false)
const exporting = ref(false)
const error = ref('')
const logs = ref<AuditLog[]>([])
const total = ref(0)
@@ -115,6 +121,43 @@ async function fetchLogs() {
}
}
/** 导出文件名:audit-logs-<本地时间 yyyyMMdd-HHmmss>.csv(冒号/空格在文件名中非法)。 */
function exportFilename(): string {
const now = new Date()
const pad = (n: number) => String(n).padStart(2, '0')
return (
`audit-logs-${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}` +
`-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.csv`
)
}
/** 按当前筛选条件导出全部记录:fetch → blob → 触发下载,失败进顶部错误提示。 */
async function exportLogs() {
exporting.value = true
error.value = ''
try {
// 导出为全量接口,无需分页参数
const params = new URLSearchParams(buildQuery())
params.delete('page')
params.delete('size')
const response = await fetch(`${EXPORT_ENDPOINT}?${params.toString()}`)
if (!response.ok) {
throw new Error(`导出失败(HTTP ${response.status})`)
}
const blob = await response.blob()
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = exportFilename()
anchor.click()
URL.revokeObjectURL(url)
} catch (e) {
error.value = e instanceof Error ? e.message : String(e)
} finally {
exporting.value = false
}
}
function resetFilter() {
filterUsername.value = ''
filterResourceType.value = ''
@@ -153,6 +196,12 @@ onMounted(fetchLogs)
</template>
<template #actions>
<VSpace>
<VButton :loading="exporting" type="default" @click="exportLogs">
<template #icon>
<IconSave class="h-full w-full" />
</template>
导出
</VButton>
<VButton :loading="loading" type="default" @click="fetchLogs">
<template #icon>
<IconRefreshLine class="h-full w-full" />