优化构架

This commit is contained in:
2026-08-03 18:49:18 +08:00
parent 1241d11c01
commit 44c33a6280
133 changed files with 651 additions and 603 deletions
@@ -0,0 +1,41 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { http } from '@/shared/api/http'
import {
createPlatformExportTask,
downloadPlatformExportTask,
listPlatformExportTasks,
retryPlatformExportTask,
} from './platformExportTasks'
vi.mock('@/shared/api/http', async () => {
const actual = await vi.importActual<typeof import('@/shared/api/http')>('@/shared/api/http')
return { ...actual, http: { get: vi.fn(), post: vi.fn() } }
})
describe('platformExportTasks', () => {
beforeEach(() => vi.clearAllMocks())
it('creates a backend export task with the filter snapshot', async () => {
const task = { id: '9', status: 'PENDING', exportType: 'CUSTOMER_LIST' }
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: task })
const payload = { exportType: 'CUSTOMER_LIST', format: 'XLSX' as const, taskName: '客户列表', parameters: { status: 'ACTIVE' } }
await expect(createPlatformExportTask(payload)).resolves.toEqual(task)
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks', payload)
})
it('lists, downloads, and retries export tasks through File service', async () => {
const page = { records: [], page: '1', size: '20', total: '0', pages: '0' }
const blob = new Blob(['xlsx'])
vi.mocked(http.get).mockResolvedValueOnce({ code: '200', message: 'success', data: page }).mockResolvedValueOnce(blob)
vi.mocked(http.post).mockResolvedValue({ code: '200', message: 'success', data: { id: '9', status: 'PENDING' } })
await expect(listPlatformExportTasks({ page: 1, size: 20, status: 'FAILED' })).resolves.toEqual({ records: [], page: 1, size: 20, total: 0, pages: 0 })
await expect(downloadPlatformExportTask('9')).resolves.toBe(blob)
await expect(retryPlatformExportTask('9')).resolves.toMatchObject({ id: '9', status: 'PENDING' })
expect(http.get).toHaveBeenNthCalledWith(1, '/platform/v1/files/export-tasks', { params: { page: 1, size: 20, status: 'FAILED' } })
expect(http.get).toHaveBeenNthCalledWith(2, '/platform/v1/files/export-tasks/9/download', { responseType: 'blob' })
expect(http.post).toHaveBeenCalledWith('/platform/v1/files/export-tasks/9/retry', {})
})
})
@@ -0,0 +1,82 @@
import { http, unwrapApiResponse, type ApiEnvelope } from '@/shared/api/http'
export type ExportTaskStatus = 'PENDING' | 'RUNNING' | 'SUCCEEDED' | 'FAILED' | 'EXPIRED'
export type ExportTaskType = 'CUSTOMER_LIST' | string
export interface PlatformExportTask {
id: string
taskNo: string
exportType: ExportTaskType
format: 'XLSX' | string
taskName: string
status: ExportTaskStatus
totalRows: number | null
processedRows: number
fileName: string | null
contentType: string | null
sizeBytes: number | null
failureMessage: string | null
requestedBy: string
requestedUsername: string | null
requestedAt: string
startedAt: string | null
completedAt: string | null
expiresAt: string | null
}
export interface PlatformExportTaskPage {
records: PlatformExportTask[]
page: number
size: number
total: number
pages: number
}
export interface PlatformExportTaskQuery {
page: number
size: number
exportType?: string
status?: ExportTaskStatus
requestedFrom?: string
requestedTo?: string
}
export interface CreatePlatformExportTaskRequest {
exportType: ExportTaskType
format: 'XLSX'
taskName: string
parameters: Record<string, string | number | boolean | null | undefined>
}
const basePath = '/platform/v1/files/export-tasks'
export async function createPlatformExportTask(payload: CreatePlatformExportTaskRequest) {
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(basePath, payload)
return unwrapApiResponse(response)
}
export async function listPlatformExportTasks(query: PlatformExportTaskQuery) {
const response = await http.get<ApiEnvelope<PlatformExportTaskPage>, ApiEnvelope<PlatformExportTaskPage>>(basePath, {
params: query,
})
const page = unwrapApiResponse(response)
return {
...page,
page: Number(page.page),
size: Number(page.size),
total: Number(page.total),
pages: Number(page.pages),
}
}
export function downloadPlatformExportTask(taskId: string) {
return http.get<Blob, Blob>(`${basePath}/${encodeURIComponent(taskId)}/download`, { responseType: 'blob' })
}
export async function retryPlatformExportTask(taskId: string) {
const response = await http.post<ApiEnvelope<PlatformExportTask>, ApiEnvelope<PlatformExportTask>>(
`${basePath}/${encodeURIComponent(taskId)}/retry`,
{},
)
return unwrapApiResponse(response)
}
+1
View File
@@ -0,0 +1 @@
export * from './api/platformExportTasks'
@@ -0,0 +1,105 @@
import ElementPlus from 'element-plus'
import { createPinia, setActivePinia } from 'pinia'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
downloadPlatformExportTask,
listPlatformExportTasks,
retryPlatformExportTask,
type PlatformExportTask,
} from '@/modules/downloads/api/platformExportTasks'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
import { useAuthStore } from '@/core/auth/auth'
import DownloadCenterView from './DownloadCenterView.vue'
vi.mock('@/modules/downloads/api/platformExportTasks', () => ({
downloadPlatformExportTask: vi.fn(),
listPlatformExportTasks: vi.fn(),
retryPlatformExportTask: vi.fn(),
}))
class ResizeObserverStub implements ResizeObserver {
observe() {}
unobserve() {}
disconnect() {}
}
const task: PlatformExportTask = {
id: '9', taskNo: 'EXP9', exportType: 'CUSTOMER_LIST', format: 'XLSX', taskName: '客户列表',
status: 'SUCCEEDED', totalRows: 12, processedRows: 12, fileName: '客户列表.xlsx',
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', sizeBytes: 2048,
failureMessage: null, requestedBy: '1', requestedUsername: 'admin', requestedAt: '2026-08-03T10:00:00',
startedAt: '2026-08-03T10:00:01', completedAt: '2026-08-03T10:00:02', expiresAt: '2026-08-10T10:00:02',
}
enableAutoUnmount(afterEach)
afterEach(() => vi.useRealTimers())
describe('DownloadCenterView', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubGlobal('ResizeObserver', ResizeObserverStub)
Object.defineProperty(URL, 'createObjectURL', { configurable: true, value: vi.fn(() => 'blob:export') })
Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
const pinia = createPinia()
setActivePinia(pinia)
const auth = useAuthStore()
auth.token = 'token'
auth.permissions = ['platform:download:list', 'platform:customer:export']
useAccessPreviewStore().initializeAfterLogin()
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [task], page: 1, size: 20, total: 1, pages: 1 })
vi.mocked(downloadPlatformExportTask).mockResolvedValue(new Blob(['xlsx']))
vi.mocked(retryPlatformExportTask).mockResolvedValue({ ...task, status: 'PENDING' })
})
it('lists completed tasks and downloads the backend-generated artifact', async () => {
const pinia = setActivePinia(createPinia())
const auth = useAuthStore()
auth.token = 'token'
auth.permissions = ['platform:download:list', 'platform:customer:export']
useAccessPreviewStore().initializeAfterLogin()
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
await flushPromises()
expect(document.body.textContent).toContain('客户列表')
expect(document.querySelector('.failure-cell')?.classList.contains('failure-message')).toBe(false)
const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find((item) => item.textContent?.trim() === '下载')
button?.click()
await flushPromises()
expect(downloadPlatformExportTask).toHaveBeenCalledWith('9')
expect(URL.createObjectURL).toHaveBeenCalled()
})
it('shows retry only for failed tasks with the source export permission', async () => {
vi.mocked(listPlatformExportTasks).mockResolvedValue({ records: [{ ...task, status: 'FAILED', failureMessage: 'IAM timeout' }], page: 1, size: 20, total: 1, pages: 1 })
const pinia = setActivePinia(createPinia())
const auth = useAuthStore()
auth.token = 'token'
auth.permissions = ['platform:download:list', 'platform:customer:export']
useAccessPreviewStore().initializeAfterLogin()
mount(DownloadCenterView, { attachTo: document.body, global: { plugins: [pinia, ElementPlus] } })
await flushPromises()
expect(document.querySelector('.failure-cell')?.classList.contains('failure-message')).toBe(true)
const button = [...document.querySelectorAll<HTMLButtonElement>('button')].find((item) => item.textContent?.trim() === '重试')
button?.click()
await flushPromises()
expect(retryPlatformExportTask).toHaveBeenCalledWith('9')
})
it('does not schedule another refresh after an in-flight load finishes on an unmounted page', async () => {
vi.useFakeTimers()
let resolveRequest!: (value: { records: PlatformExportTask[]; page: number; size: number; total: number; pages: number }) => void
vi.mocked(listPlatformExportTasks).mockReturnValue(new Promise((resolve) => { resolveRequest = resolve }))
const wrapper = mount(DownloadCenterView, { global: { plugins: [createPinia(), ElementPlus] } })
wrapper.unmount()
resolveRequest({ records: [{ ...task, status: 'RUNNING' }], page: 1, size: 20, total: 1, pages: 1 })
await flushPromises()
await vi.advanceTimersByTimeAsync(5000)
expect(listPlatformExportTasks).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,229 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { Download, RefreshCw, RotateCcw } from '@lucide/vue'
import { ElMessage } from 'element-plus'
import { getApiErrorDetails, getApiErrorMessage, type ApiErrorDetails } from '@/shared/api/http'
import {
downloadPlatformExportTask,
listPlatformExportTasks,
retryPlatformExportTask,
type ExportTaskStatus,
type PlatformExportTask,
} from '@/modules/downloads/api/platformExportTasks'
import ApiErrorMeta from '@/shared/components/ApiErrorMeta.vue'
import DataTable, { type DataTableColumn } from '@/shared/components/DataTable.vue'
import QueryToolbar, { type QueryField, type QueryModel } from '@/shared/components/QueryToolbar.vue'
import { useAccessPreviewStore } from '@/core/access/accessPreview'
type DownloadFilters = QueryModel & {
exportType: string
status: ExportTaskStatus | ''
requestedRange: string[]
}
const access = useAccessPreviewStore()
const page = ref(1)
const pageSize = ref(20)
const loading = ref(false)
const downloadingId = ref('')
const retryingId = ref('')
const loadError = ref<ApiErrorDetails | null>(null)
const result = ref({ records: [] as PlatformExportTask[], total: 0, pages: 0 })
const filters = ref<DownloadFilters>({ exportType: '', status: '', requestedRange: [] })
let refreshTimer: number | undefined
let disposed = false
const queryFields: QueryField[] = [
{ key: 'exportType', type: 'select', placeholder: '全部任务类型', options: [
{ label: '客户列表', value: 'CUSTOMER_LIST' },
] },
{ key: 'status', type: 'select', placeholder: '全部任务状态', options: [
{ label: '等待处理', value: 'PENDING' }, { label: '处理中', value: 'RUNNING' },
{ label: '已完成', value: 'SUCCEEDED' }, { label: '失败', value: 'FAILED' },
{ label: '已过期', value: 'EXPIRED' },
] },
{ key: 'requestedRange', type: 'daterange', placeholder: '请选择申请日期' },
]
const columns: DataTableColumn[] = [
{ key: 'actions', label: '操作', width: 150, fixed: 'left', slotName: 'actions' },
{ prop: 'taskName', label: '任务名称', minWidth: 180, showOverflowTooltip: true },
{ key: 'type', label: '任务类型', width: 120, slotName: 'type' },
{ key: 'status', label: '状态', width: 110, slotName: 'status' },
{ key: 'progress', label: '数据量', width: 120, slotName: 'progress' },
{ prop: 'format', label: '格式', width: 80 },
{ key: 'requester', label: '申请人', minWidth: 130, slotName: 'requester' },
{ key: 'requestedAt', label: '申请时间', width: 170, slotName: 'requestedAt' },
{ key: 'completedAt', label: '完成时间', width: 170, slotName: 'completedAt' },
{ key: 'expiresAt', label: '过期时间', width: 170, slotName: 'expiresAt' },
{ key: 'failure', label: '失败原因', minWidth: 240, slotName: 'failure' },
]
const hasActiveTasks = computed(() => result.value.records.some((task) => ['PENDING', 'RUNNING'].includes(task.status)))
function clearRefreshTimer() {
if (refreshTimer !== undefined) window.clearTimeout(refreshTimer)
refreshTimer = undefined
}
function scheduleRefresh() {
clearRefreshTimer()
if (!disposed && hasActiveTasks.value && !loadError.value) refreshTimer = window.setTimeout(() => { void loadTasks(true) }, 5000)
}
async function loadTasks(background = false) {
clearRefreshTimer()
if (!background) loading.value = true
loadError.value = null
try {
const range = filters.value.requestedRange
const response = await listPlatformExportTasks({
page: page.value,
size: pageSize.value,
exportType: filters.value.exportType || undefined,
status: filters.value.status || undefined,
requestedFrom: range?.[0] || undefined,
requestedTo: range?.[1] || undefined,
})
result.value = { records: response.records, total: response.total, pages: response.pages }
} catch (error) {
loadError.value = getApiErrorDetails(error, '下载任务加载失败')
} finally {
if (!background) loading.value = false
scheduleRefresh()
}
}
function applyFilters() {
if (page.value === 1) void loadTasks()
else page.value = 1
}
async function downloadTask(task: PlatformExportTask) {
downloadingId.value = task.id
try {
const blob = await downloadPlatformExportTask(task.id)
const url = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = url
anchor.download = safeFileName(task.fileName || `${task.taskName}.xlsx`)
document.body.append(anchor)
anchor.click()
anchor.remove()
URL.revokeObjectURL(url)
} catch (error) {
ElMessage.error(getApiErrorMessage(error, '文件下载失败,请刷新任务状态后重试'))
} finally {
downloadingId.value = ''
}
}
async function retryTask(task: PlatformExportTask) {
retryingId.value = task.id
try {
await retryPlatformExportTask(task.id)
ElMessage.success('导出任务已重新提交')
await loadTasks()
} catch (error) {
ElMessage.error(getApiErrorMessage(error, '任务重试失败'))
} finally {
retryingId.value = ''
}
}
function safeFileName(value: string) {
const safe = value.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_').trim()
return safe || '导出文件.xlsx'
}
function typeLabel(type: string) { return type === 'CUSTOMER_LIST' ? '客户列表' : type }
function statusMeta(status: ExportTaskStatus) {
const values = {
PENDING: { label: '等待处理', type: 'info' as const },
RUNNING: { label: '处理中', type: 'warning' as const },
SUCCEEDED: { label: '已完成', type: 'success' as const },
FAILED: { label: '失败', type: 'danger' as const },
EXPIRED: { label: '已过期', type: 'info' as const },
}
return values[status]
}
function formatDate(value: string | null) {
if (!value) return '—'
const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleString('zh-CN', { hour12: false })
}
function formatSize(bytes: number | null) {
if (bytes === null) return ''
if (bytes < 1024) return `${bytes} B`
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`
return `${(bytes / 1024 / 1024).toFixed(1)} MB`
}
function canRetry(task: PlatformExportTask) {
return task.status === 'FAILED' && task.exportType === 'CUSTOMER_LIST' && access.can('platform:customer:export')
}
watch([page, pageSize], () => { void loadTasks() })
onMounted(loadTasks)
onBeforeUnmount(() => {
disposed = true
clearRefreshTimer()
})
</script>
<template>
<div class="business-page download-center-page">
<QueryToolbar v-model="filters" class="surface-panel" ariaLabel="下载任务筛选" :fields="queryFields" @search="applyFilters" />
<section v-if="loadError" class="surface-panel download-error" role="alert">
<div><strong>下载任务暂时无法加载</strong><p>{{ loadError.message }}</p><ApiErrorMeta :details="loadError" /></div>
<el-button type="primary" :loading="loading" @click="loadTasks()">重新加载</el-button>
</section>
<section v-else class="surface-panel table-panel" :aria-busy="loading">
<div class="download-table-header">
<div><h2>下载任务</h2><span>共 {{ result.total }} 个任务</span></div>
<el-button :loading="loading" @click="loadTasks()"><RefreshCw :size="16" />刷新</el-button>
</div>
<DataTable v-model:page="page" v-model:page-size="pageSize" :data="result.records" :columns="columns" :loading="loading" :total="result.total" row-key="id" empty-text="暂无符合筛选条件的下载任务" aria-label="下载任务列表">
<template #actions="{ row }"><div class="table-actions">
<el-button v-if="(row as PlatformExportTask).status === 'SUCCEEDED'" link type="primary" :loading="downloadingId === (row as PlatformExportTask).id" @click="downloadTask(row as PlatformExportTask)"><Download :size="15" />下载</el-button>
<el-button v-if="canRetry(row as PlatformExportTask)" link type="primary" :loading="retryingId === (row as PlatformExportTask).id" @click="retryTask(row as PlatformExportTask)"><RotateCcw :size="15" />重试</el-button>
<span v-if="(row as PlatformExportTask).status !== 'SUCCEEDED' && !canRetry(row as PlatformExportTask)" class="action-placeholder">—</span>
</div></template>
<template #type="{ row }">{{ typeLabel((row as PlatformExportTask).exportType) }}</template>
<template #status="{ row }"><el-tag :type="statusMeta((row as PlatformExportTask).status).type" effect="light">{{ statusMeta((row as PlatformExportTask).status).label }}</el-tag></template>
<template #progress="{ row }"><span>{{ (row as PlatformExportTask).processedRows }}<template v-if="(row as PlatformExportTask).totalRows !== null"> / {{ (row as PlatformExportTask).totalRows }}</template></span><small v-if="(row as PlatformExportTask).sizeBytes !== null">{{ formatSize((row as PlatformExportTask).sizeBytes) }}</small></template>
<template #requester="{ row }">{{ (row as PlatformExportTask).requestedUsername || (row as PlatformExportTask).requestedBy }}</template>
<template #requestedAt="{ row }">{{ formatDate((row as PlatformExportTask).requestedAt) }}</template>
<template #completedAt="{ row }">{{ formatDate((row as PlatformExportTask).completedAt) }}</template>
<template #expiresAt="{ row }">{{ formatDate((row as PlatformExportTask).expiresAt) }}</template>
<template #failure="{ row }"><span class="failure-cell" :class="{ 'failure-message': Boolean((row as PlatformExportTask).failureMessage) }">{{ (row as PlatformExportTask).failureMessage || '—' }}</span></template>
</DataTable>
</section>
</div>
</template>
<style scoped>
.download-center-page { min-width: 0; }
.download-error, .download-table-header { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
.download-error { padding: 18px; }
.download-error strong { color: var(--cc-danger); font-size: 14px; }
.download-error p { margin: 5px 0; color: var(--cc-text); font-size: 13px; }
.download-table-header { min-height: 64px; padding: 12px 18px; border-bottom: 1px solid var(--cc-border); }
.download-table-header h2 { margin: 0; color: var(--cc-text); font-size: 16px; }
.download-table-header span { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 12px; }
.table-actions { display: flex; min-height: 32px; align-items: center; gap: 8px; }
.table-actions :deep(.el-button + .el-button) { margin-left: 0; }
.action-placeholder { color: var(--cc-muted); }
.failure-cell { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.failure-message { color: var(--cc-danger); }
small { display: block; margin-top: 3px; color: var(--cc-muted); font-size: 11px; }
@media (max-width: 720px) {
.download-error, .download-table-header { align-items: stretch; flex-direction: column; }
.download-table-header :deep(.el-button) { min-height: 40px; }
}
</style>
+10
View File
@@ -0,0 +1,10 @@
import type { RouteRecordRaw } from 'vue-router'
export const downloadRoutes = [
{
path: 'downloads',
name: 'download-center',
component: () => import('@/modules/downloads/pages/DownloadCenterView.vue'),
meta: { title: '下载中心', description: '查看异步导出任务并下载已生成文件', permission: 'platform:download:list' },
},
] satisfies RouteRecordRaw[]