Compare commits

..

2 Commits

Author SHA1 Message Date
xiaoxia 41eafee545 Merge branch 'develop' into refactor/assets-api
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 20s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 1m20s
CI/CD Pipeline / Validate - Code Quality (pull_request) Failing after 1m47s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 32s
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 24s
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m29s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 2m0s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 3m10s
AI Code Review / AI Code Review (pull_request) Successful in 1m28s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 44s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 50s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 15m27s
CI/CD Pipeline / CI Gate (pull_request) 失败: CI/CD Pipeline / Validate - Code Quality (pull_request) [frontend-only]
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Failing after 22s
ACR Cleanup / ACR Image Cleanup (pull_request_target) Has been cancelled
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been cancelled
Preview Cleanup / Cleanup Preview Environment (pull_request) Successful in 19s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
2026-07-27 12:35:02 +08:00
xiaoxia d857298737 refactor(assets): API层按模块拆分(443行→入口77行, -83%)
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 9s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 51s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 50s
CI/CD Pipeline / Frontend Lint (pull_request) Failing after 21s
CI/CD Pipeline / Validate - Code Quality (pull_request) Failing after 1m29s
CI/CD Pipeline / Build Staging API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Staging Worker Image (pull_request) Has been skipped
CI/CD Pipeline / PR Build Worker Image (pull_request) Successful in 29s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 52s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 2m14s
CI/CD Pipeline / PR Build Web Image (pull_request) Failing after 2m3s
Preview Deploy / Deploy Preview Environment (pull_request) Failing after 21s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 41s
AI Code Review / AI Code Review (pull_request) Successful in 6m33s
CI/CD Pipeline / Unit Tests (pull_request) Has been skipped
CI/CD Pipeline / Build Production API Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Web Image (pull_request) Has been skipped
CI/CD Pipeline / Build Production Worker Image (pull_request) Has been skipped
CI/CD Pipeline / Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / Deploy Staging (Watchtower auto-deploy) (pull_request) Has been skipped
CI/CD Pipeline / Frontend Unit Tests (pull_request) Failing after 44s
CI/CD Pipeline / Deploy Production (pull_request) Has been skipped
CI/CD Pipeline / Staging E2E Tests (pull_request) Has been skipped
CI/CD Pipeline / Staging API Integration Tests (pull_request) Has been skipped
CI/CD Pipeline / ACR Image Cleanup (pull_request) Has been skipped
CI/CD Pipeline / Canary Release to Production (pull_request) Has been cancelled
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
将 assets.ts 单文件拆分为目录结构:

- types.ts — 所有类型定义
- diagnosis.ts — 素材诊断 API
- libraries.ts — 素材库 CRUD
- assets.ts — 素材 CRUD
- upload.ts — 表单上传 + OSS 直传(带进度/超时/错误诊断)
- jobs.ts — 入库任务 + 分类任务
- batch.ts — 批量操作(删除/打标签/分类/智能标记)+ 归一化工具
- index.ts — 统一入口,re-export 所有类型和函数

入口文件 443 行 → 77 行,各模块职责单一。
导入路径 @/api/assets 保持向后兼容。
2026-07-26 16:51:36 +08:00
15 changed files with 785 additions and 868 deletions
-443
View File
@@ -1,443 +0,0 @@
/**
* 素材相关 API
* Phase 1 重构:去掉 project_id,素材直接归属用户
*/
import apiClient from "./client"
import { getOrCreateDefaultProject } from "./projects"
/** 素材元数据 */
export interface AssetMetadata {
/** 时长(秒) */
duration?: number
/** 宽度(像素) */
width?: number
/** 高度(像素) */
height?: number
/** 比特率(bps */
bitrate?: number
/** 编码格式 */
codec?: string
/** 帧率 */
fps?: number
/** 采样率(Hz */
sample_rate?: number
/** 声道数 */
channels?: number
/** 其他扩展字段 */
[key: string]: unknown
}
/** 素材分类状态 */
export type AssetClassificationStatus = "pending" | "processing" | "completed" | "failed"
/** 素材条目 */
export interface AssetItem {
id: string
library_id: string
name: string
storage_key: string
mime_type: string
metadata: AssetMetadata
file_size?: number
file_url?: string
thumbnail_url?: string
/** 时长(秒),视频/音频素材由后端从 metadata 提取到顶层 */
duration?: number
status?: string
classification_status?: AssetClassificationStatus | null
quality_score?: number | null
tag_ids?: string[]
created_at?: string
}
/** 素材库 */
export interface AssetLibraryItem {
id: string
name: string
kind: "video" | "voice" | "image"
asset_count?: number
total_size?: number
created_at?: string
}
/** 入库任务 */
export interface IngestJob {
id: string
library_id: string
storage_key: string
status: "pending" | "processing" | "completed" | "failed"
error_message: string
result_asset_id: string
}
/** 分类任务 */
export interface ClassificationJob {
id: string
asset_id: string
status: "pending" | "processing" | "completed" | "failed"
classification: string
confidence: number
error_message: string
}
/** 素材诊断信息 */
export interface AssetDiagnosis {
readiness_score: number
readiness_label: string
total_assets: number
ready_assets: number
video_assets: number
image_assets: number
voice_assets: number
total_duration_seconds: number
estimated_video_count: number
used_assets: number
unused_assets: number
pending_review_assets: number
smart_views: Array<{
key: string
label: string
count: number
description: string
}>
gaps: Array<{
key: string
severity: "critical" | "warning" | "info"
message: string
recommendation: string
}>
}
// ─── 素材诊断 ──────────────────────────────────────────────
/** 获取素材诊断信息(可选 asset_id 查单素材,否则全局诊断) */
export const getAssetDiagnosis = async (assetId?: string): Promise<AssetDiagnosis> => {
const params: Record<string, string> = {}
if (assetId) params.asset_id = assetId
const response = await apiClient.get("/asset-diagnosis", { params })
return response.data
}
// ─── 素材库 ────────────────────────────────────────────────
/** 获取当前用户的所有素材库 */
export const getAssetLibraries = async (): Promise<AssetLibraryItem[]> => {
const response = await apiClient.get("/asset-libraries")
return response.data.items || []
}
/** 创建素材库(自动获取或创建默认项目以提供 project_id */
export const createAssetLibrary = async (data: {
name: string
kind: "video" | "voice" | "image"
}): Promise<AssetLibraryItem> => {
// 后端要求 project_id,前端自动管理默认项目
const project = await getOrCreateDefaultProject()
const response = await apiClient.post("/asset-libraries", {
project_id: project.id,
...data,
})
return response.data
}
/** 确保项目下指定 kind 的默认素材库存在(不存在则自动创建) */
export const ensureDefaultLibrary = async (data: {
project_id: string
kind: "video" | "voice" | "image"
}): Promise<AssetLibraryItem> => {
const response = await apiClient.post("/asset-libraries/ensure-default", data)
return response.data
}
/** 删除素材库 */
export const deleteAssetLibrary = async (libraryId: string): Promise<void> => {
await apiClient.delete(`/asset-libraries/${libraryId}`)
}
// ─── 素材 ──────────────────────────────────────────────────
/** 获取素材库下的所有素材 */
export const getAssets = async (
libraryId: string,
options?: { status?: string; page?: number; page_size?: number },
): Promise<{ items: AssetItem[]; total: number }> => {
const params: Record<string, string | number> = { library_id: libraryId }
// 默认拉取所有非删除状态的素材(ready/ingesting/processing/uploading/error/failed
// 让用户能看到"处理中"的素材,不会以为上传失败了
if (options?.status) {
params.status = options.status
}
if (options?.page) params.page = options.page
if (options?.page_size) params.page_size = options.page_size
const response = await apiClient.get("/assets", { params })
const data = response.data || {}
const items: AssetItem[] = data.items || []
const total: number = typeof data.total === "number" ? data.total : items.length
return { items, total }
}
/** 按类型获取素材(如 voice/video/image),支持可选筛选 */
export const getAssetsByKind = async (
kind: string,
filters?: {
keyword?: string
gender?: string
style?: string
tag_ids?: string[]
limit?: number
page?: number
page_size?: number
},
): Promise<AssetItem[]> => {
const params: Record<string, string | number> = { kind }
if (filters?.keyword) params.keyword = filters.keyword
if (filters?.gender) params.gender = filters.gender
if (filters?.style) params.style = filters.style
if (filters?.tag_ids?.length) params.tag_ids = filters.tag_ids.join(",")
if (filters?.limit) params.limit = filters.limit
if (filters?.page) params.page = filters.page
if (filters?.page_size) params.page_size = filters.page_size
const response = await apiClient.get("/assets", { params })
return response.data.items || []
}
/** 创建素材(上传文件后调用,附带 metadata) */
export const createAsset = async (data: {
library_id: string
name: string
storage_key: string
mime_type: string
metadata?: AssetMetadata
}): Promise<AssetItem> => {
const response = await apiClient.post("/assets", data)
return response.data
}
/** 更新素材(名称、metadata 等) */
export const updateAsset = async (
assetId: string,
data: { name?: string; metadata?: AssetMetadata },
): Promise<AssetItem> => {
const response = await apiClient.put(`/assets/${assetId}`, data)
return response.data
}
/** 更新素材审核状态 */
export const updateAssetReviewStatus = async (
assetId: string,
reviewStatus: "pending_review" | "approved" | "rejected",
): Promise<AssetItem> => {
const response = await apiClient.patch(`/assets/${assetId}/review`, {
review_status: reviewStatus,
})
return response.data
}
/** 删除素材 */
export const deleteAsset = async (assetId: string): Promise<void> => {
await apiClient.delete(`/assets/${assetId}`)
}
// ─── 上传 ──────────────────────────────────────────────────
/** 表单上传素材(小文件) */
export const uploadAsset = async (
formData: FormData,
): Promise<{ storage_key: string; ingest_job_id: string; url: string }> => {
const response = await apiClient.post("/upload", formData, {
headers: { "Content-Type": "multipart/form-data" },
timeout: 30 * 60 * 1000,
})
return response.data
}
/** 预签名直传准备 */
export const prepareDirectUpload = async (data: {
project_id: string
library_id: string
filename: string
content_type: string
file_size: number
}): Promise<{
upload_url: string
method: string
storage_key: string
expires_at: string
fields: Record<string, string>
max_size_bytes: number
}> => {
const response = await apiClient.post("/upload/direct/prepare", data)
return response.data
}
/** 直传完成确认 */
export const completeDirectUpload = async (data: {
project_id: string
library_id: string
storage_key: string
}): Promise<{ storage_key: string; ingest_job_id: string }> => {
const response = await apiClient.post("/upload/direct/complete", data)
return response.data
}
/** 直传上传(大文件推荐),支持可选进度回调 */
export const uploadAssetDirect = async (data: {
file: File
library_id: string
onProgress?: (percent: number) => void
}): Promise<{ storage_key: string; ingest_job_id: string }> => {
// 后端要求 project_id,前端自动获取默认项目
const project = await getOrCreateDefaultProject()
const prepared = await prepareDirectUpload({
project_id: project.id,
library_id: data.library_id,
filename: data.file.name,
content_type: data.file.type || "application/octet-stream",
file_size: data.file.size,
})
const directForm = new FormData()
Object.entries(prepared.fields).forEach(([key, value]) => directForm.append(key, value))
directForm.append("file", data.file)
// 使用 XMLHttpRequest 以获取上传进度 + 超时控制 + 详细错误诊断
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(prepared.method, prepared.upload_url)
// 超时 10 分钟
xhr.timeout = 10 * 60 * 1000
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && data.onProgress) {
data.onProgress(Math.round((e.loaded / e.total) * 100))
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve()
} else {
// 解析 OSS 返回的 XML 错误信息
let ossError = ""
try {
const codeMatch = xhr.responseText.match(/<Code>([^<]+)<\/Code>/)
const msgMatch = xhr.responseText.match(/<Message>([^<]+)<\/Message>/)
if (codeMatch || msgMatch) {
ossError = ` [OSS: ${codeMatch?.[1] || "unknown"} - ${msgMatch?.[1] || "unknown"}]`
}
} catch {
// 无法解析响应体
}
const detail = `OSS 直传失败: HTTP ${xhr.status} ${xhr.statusText}${ossError}`
console.error("[OSS Upload] 直传失败:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
status: xhr.status,
statusText: xhr.statusText,
})
reject(new Error(detail))
}
}
xhr.onerror = () => {
console.error("[OSS Upload] 网络错误:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
})
reject(new Error("OSS 上传网络错误,请检查网络连接"))
}
xhr.ontimeout = () => {
console.error("[OSS Upload] 上传超时:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
})
reject(new Error("OSS 上传超时(10分钟),请检查网络或尝试更小的文件"))
}
xhr.send(directForm)
})
return completeDirectUpload({
project_id: project.id,
library_id: data.library_id,
storage_key: prepared.storage_key,
})
}
// ─── 入库 / 分类任务 ───────────────────────────────────────
/** 查询入库任务状态 */
export const getIngestJob = async (jobId: string): Promise<IngestJob> => {
const response = await apiClient.get(`/ingest-jobs/${jobId}`)
return response.data
}
/** 提交素材分类任务 */
export const submitClassificationJob = async (data: {
asset_id: string
}): Promise<ClassificationJob> => {
const response = await apiClient.post("/classification-jobs", data)
return response.data
}
/** 查询分类任务状态 */
export const getClassificationJob = async (jobId: string): Promise<ClassificationJob> => {
const response = await apiClient.get(`/classification-jobs/${jobId}`)
return response.data
}
// ─── 批量操作 ───────────────────────────────────────────────
/** 批量操作结果 */
export interface BatchOperationResult {
succeeded: string[]
failed: string[]
total: number
success_count: number
failure_count: number
}
/** 统一批量操作结果归一化,防御后端字段缺失或格式不一致 */
const normalizeBatchResult = (raw: Record<string, unknown>): BatchOperationResult => {
const succeeded = Array.isArray(raw.succeeded) ? (raw.succeeded as string[]) : []
const failed = Array.isArray(raw.failed) ? (raw.failed as string[]) : []
const success_count = typeof raw.success_count === "number" ? raw.success_count : succeeded.length
const failure_count = typeof raw.failure_count === "number" ? raw.failure_count : failed.length
const total = typeof raw.total === "number" ? raw.total : success_count + failure_count
return { succeeded, failed, total, success_count, failure_count }
}
/** 批量删除素材 */
export const batchDeleteAssets = async (assetIds: string[]): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-delete", {
asset_ids: assetIds,
})
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量打标签 */
export const batchTagAssets = async (data: {
asset_ids: string[]
tags: string[]
mode: "add" | "replace"
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-tag", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量改分类 */
export const batchClassifyAssets = async (data: {
asset_ids: string[]
category: string
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-classify", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量智能标记 */
export const batchMarkAssets = async (data: {
asset_ids: string[]
smart_view: "recommended" | "caution" | "high_risk"
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-mark", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
+87
View File
@@ -0,0 +1,87 @@
/**
* 素材 CRUD API
*/
import apiClient from "../client"
import type { AssetItem, AssetMetadata } from "./types"
/** 获取素材库下的所有素材 */
export const getAssets = async (
libraryId: string,
options?: {
status?: string
page?: number
page_size?: number
},
): Promise<{ items: AssetItem[]; total: number }> => {
const params: Record<string, string | number> = { library_id: libraryId }
if (options?.status) params.status = options.status
if (options?.page) params.page = options.page
if (options?.page_size) params.page_size = options.page_size
const response = await apiClient.get("/assets", { params })
const data = response.data || {}
const items: AssetItem[] = data.items || []
const total: number = typeof data.total === "number" ? data.total : items.length
return { items, total }
}
/** 按类型获取素材(如 voice/video/image),支持可选筛选 */
export const getAssetsByKind = async (
kind: string,
filters?: {
keyword?: string
gender?: string
style?: string
tag_ids?: string[]
limit?: number
page?: number
page_size?: number
},
): Promise<AssetItem[]> => {
const params: Record<string, string | number> = { kind }
if (filters?.keyword) params.keyword = filters.keyword
if (filters?.gender) params.gender = filters.gender
if (filters?.style) params.style = filters.style
if (filters?.tag_ids?.length) params.tag_ids = filters.tag_ids.join(",")
if (filters?.limit) params.limit = filters.limit
if (filters?.page) params.page = filters.page
if (filters?.page_size) params.page_size = filters.page_size
const response = await apiClient.get("/assets", { params })
return response.data.items || []
}
/** 创建素材(上传文件后调用,附带 metadata) */
export const createAsset = async (data: {
library_id: string
name: string
storage_key: string
mime_type: string
metadata?: AssetMetadata
}): Promise<AssetItem> => {
const response = await apiClient.post("/assets", data)
return response.data
}
/** 更新素材(名称、metadata 等) */
export const updateAsset = async (
assetId: string,
data: { name?: string; metadata?: AssetMetadata },
): Promise<AssetItem> => {
const response = await apiClient.put(`/assets/${assetId}`, data)
return response.data
}
/** 更新素材审核状态 */
export const updateAssetReviewStatus = async (
assetId: string,
reviewStatus: "pending_review" | "approved" | "rejected",
): Promise<AssetItem> => {
const response = await apiClient.patch(`/assets/${assetId}/review`, {
review_status: reviewStatus,
})
return response.data
}
/** 删除素材 */
export const deleteAsset = async (assetId: string): Promise<void> => {
await apiClient.delete(`/assets/${assetId}`)
}
+51
View File
@@ -0,0 +1,51 @@
/**
* 素材批量操作 API
*/
import apiClient from "../client"
import type { BatchOperationResult } from "./types"
/** 统一批量操作结果归一化,防御后端字段缺失或格式不一致 */
export const normalizeBatchResult = (raw: Record<string, unknown>): BatchOperationResult => {
const succeeded = Array.isArray(raw.succeeded) ? (raw.succeeded as string[]) : []
const failed = Array.isArray(raw.failed) ? (raw.failed as string[]) : []
const success_count = typeof raw.success_count === "number" ? raw.success_count : succeeded.length
const failure_count = typeof raw.failure_count === "number" ? raw.failure_count : failed.length
const total = typeof raw.total === "number" ? raw.total : success_count + failure_count
return { succeeded, failed, total, success_count, failure_count }
}
/** 批量删除素材 */
export const batchDeleteAssets = async (assetIds: string[]): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-delete", {
asset_ids: assetIds,
})
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量打标签 */
export const batchTagAssets = async (data: {
asset_ids: string[]
tags: string[]
mode: "add" | "replace"
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-tag", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量改分类 */
export const batchClassifyAssets = async (data: {
asset_ids: string[]
category: string
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-classify", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
/** 批量智能标记 */
export const batchMarkAssets = async (data: {
asset_ids: string[]
smart_view: "recommended" | "caution" | "high_risk"
}): Promise<BatchOperationResult> => {
const response = await apiClient.post("/assets/batch-mark", data)
return normalizeBatchResult((response.data || {}) as Record<string, unknown>)
}
+13
View File
@@ -0,0 +1,13 @@
/**
* 素材诊断 API
*/
import apiClient from "../client"
import type { AssetDiagnosis } from "./types"
/** 获取素材诊断信息(可选 asset_id 查单素材,否则全局诊断) */
export const getAssetDiagnosis = async (assetId?: string): Promise<AssetDiagnosis> => {
const params: Record<string, string> = {}
if (assetId) params.asset_id = assetId
const response = await apiClient.get("/asset-diagnosis", { params })
return response.data
}
+55
View File
@@ -0,0 +1,55 @@
/**
* 素材相关 API — 按模块拆分后的统一入口
* 保持与原 assets.ts 相同的导出结构,向后兼容
*/
// 类型
export type {
AssetMetadata,
AssetClassificationStatus,
AssetItem,
AssetLibraryItem,
IngestJob,
ClassificationJob,
AssetDiagnosis,
BatchOperationResult,
UploadResult,
DirectUploadPrepareResult,
DirectUploadCompleteResult,
} from "./types"
// 素材诊断
export { getAssetDiagnosis } from "./diagnosis"
// 素材库
export {
getAssetLibraries,
createAssetLibrary,
ensureDefaultLibrary,
deleteAssetLibrary,
} from "./libraries"
// 素材 CRUD
export {
getAssets,
getAssetsByKind,
createAsset,
updateAsset,
updateAssetReviewStatus,
deleteAsset,
} from "./assets"
// 上传
export { uploadAsset, prepareDirectUpload, completeDirectUpload, uploadAssetDirect } from "./upload"
// 任务
export { getIngestJob, submitClassificationJob, getClassificationJob } from "./jobs"
// 批量操作
export {
normalizeBatchResult,
batchDeleteAssets,
batchTagAssets,
batchClassifyAssets,
batchMarkAssets,
} from "./batch"
+25
View File
@@ -0,0 +1,25 @@
/**
* 入库任务 & 分类任务 API
*/
import apiClient from "../client"
import type { IngestJob, ClassificationJob } from "./types"
/** 查询入库任务状态 */
export const getIngestJob = async (jobId: string): Promise<IngestJob> => {
const response = await apiClient.get(`/ingest-jobs/${jobId}`)
return response.data
}
/** 提交素材分类任务 */
export const submitClassificationJob = async (data: {
asset_id: string
}): Promise<ClassificationJob> => {
const response = await apiClient.post("/classification-jobs", data)
return response.data
}
/** 查询分类任务状态 */
export const getClassificationJob = async (jobId: string): Promise<ClassificationJob> => {
const response = await apiClient.get(`/classification-jobs/${jobId}`)
return response.data
}
+39
View File
@@ -0,0 +1,39 @@
/**
* 素材库 API
*/
import apiClient from "../client"
import { getOrCreateDefaultProject } from "../projects"
import type { AssetLibraryItem } from "./types"
/** 获取当前用户的所有素材库 */
export const getAssetLibraries = async (): Promise<AssetLibraryItem[]> => {
const response = await apiClient.get("/asset-libraries")
return response.data.items || []
}
/** 创建素材库(自动获取或创建默认项目以提供 project_id */
export const createAssetLibrary = async (data: {
name: string
kind: "video" | "voice" | "image"
}): Promise<AssetLibraryItem> => {
const project = await getOrCreateDefaultProject()
const response = await apiClient.post("/asset-libraries", {
project_id: project.id,
...data,
})
return response.data
}
/** 确保项目下指定 kind 的默认素材库存在 */
export const ensureDefaultLibrary = async (data: {
project_id: string
kind: "video" | "voice" | "image"
}): Promise<AssetLibraryItem> => {
const response = await apiClient.post("/asset-libraries/ensure-default", data)
return response.data
}
/** 删除素材库 */
export const deleteAssetLibrary = async (libraryId: string): Promise<void> => {
await apiClient.delete(`/asset-libraries/${libraryId}`)
}
+138
View File
@@ -0,0 +1,138 @@
/**
* 素材相关类型定义
*/
/** 素材元数据 */
export interface AssetMetadata {
/** 时长(秒) */
duration?: number
/** 宽度(像素) */
width?: number
/** 高度(像素) */
height?: number
/** 比特率(bps */
bitrate?: number
/** 编码格式 */
codec?: string
/** 帧率 */
fps?: number
/** 采样率(Hz */
sample_rate?: number
/** 声道数 */
channels?: number
/** 其他扩展字段 */
[key: string]: unknown
}
/** 素材分类状态 */
export type AssetClassificationStatus = "pending" | "processing" | "completed" | "failed"
/** 素材条目 */
export interface AssetItem {
id: string
library_id: string
name: string
storage_key: string
mime_type: string
metadata: AssetMetadata
file_size?: number
file_url?: string
thumbnail_url?: string
/** 时长(秒),视频/音频素材由后端从 metadata 提取到顶层 */
duration?: number
status?: string
classification_status?: AssetClassificationStatus | null
quality_score?: number | null
tag_ids?: string[]
created_at?: string
}
/** 素材库 */
export interface AssetLibraryItem {
id: string
name: string
kind: "video" | "voice" | "image"
asset_count?: number
total_size?: number
created_at?: string
}
/** 入库任务 */
export interface IngestJob {
id: string
library_id: string
storage_key: string
status: "pending" | "processing" | "completed" | "failed"
error_message: string
result_asset_id: string
}
/** 分类任务 */
export interface ClassificationJob {
id: string
asset_id: string
status: "pending" | "processing" | "completed" | "failed"
classification: string
confidence: number
error_message: string
}
/** 素材诊断信息 */
export interface AssetDiagnosis {
readiness_score: number
readiness_label: string
total_assets: number
ready_assets: number
video_assets: number
image_assets: number
voice_assets: number
total_duration_seconds: number
estimated_video_count: number
used_assets: number
unused_assets: number
pending_review_assets: number
smart_views: Array<{
key: string
label: string
count: number
description: string
}>
gaps: Array<{
key: string
severity: "critical" | "warning" | "info"
message: string
recommendation: string
}>
}
/** 批量操作结果 */
export interface BatchOperationResult {
succeeded: string[]
failed: string[]
total: number
success_count: number
failure_count: number
}
/** 上传返回 */
export interface UploadResult {
storage_key: string
ingest_job_id: string
url: string
}
/** 预签名直传准备返回 */
export interface DirectUploadPrepareResult {
upload_url: string
method: string
storage_key: string
expires_at: string
fields: Record<string, string>
max_size_bytes: number
}
/** 直传完成确认返回 */
export interface DirectUploadCompleteResult {
storage_key: string
ingest_job_id: string
}
+119
View File
@@ -0,0 +1,119 @@
/**
* 上传相关 API(表单上传 + OSS 直传)
*/
import apiClient from "../client"
import { getOrCreateDefaultProject } from "../projects"
import type { UploadResult, DirectUploadPrepareResult, DirectUploadCompleteResult } from "./types"
/** 表单上传素材(小文件) */
export const uploadAsset = async (formData: FormData): Promise<UploadResult> => {
const response = await apiClient.post("/upload", formData, {
headers: { "Content-Type": "multipart/form-data" },
timeout: 30 * 60 * 1000,
})
return response.data
}
/** 预签名直传准备 */
export const prepareDirectUpload = async (data: {
project_id: string
library_id: string
filename: string
content_type: string
file_size: number
}): Promise<DirectUploadPrepareResult> => {
const response = await apiClient.post("/upload/direct/prepare", data)
return response.data
}
/** 直传完成确认 */
export const completeDirectUpload = async (data: {
project_id: string
library_id: string
storage_key: string
}): Promise<DirectUploadCompleteResult> => {
const response = await apiClient.post("/upload/direct/complete", data)
return response.data
}
/** 直传上传(大文件推荐),支持可选进度回调 */
export const uploadAssetDirect = async (data: {
file: File
library_id: string
onProgress?: (percent: number) => void
}): Promise<DirectUploadCompleteResult> => {
const project = await getOrCreateDefaultProject()
const prepared = await prepareDirectUpload({
project_id: project.id,
library_id: data.library_id,
filename: data.file.name,
content_type: data.file.type || "application/octet-stream",
file_size: data.file.size,
})
const directForm = new FormData()
Object.entries(prepared.fields).forEach(([key, value]) => directForm.append(key, value))
directForm.append("file", data.file)
// 使用 XMLHttpRequest 以获取上传进度 + 超时控制 + 详细错误诊断
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open(prepared.method, prepared.upload_url)
// 超时 10 分钟
xhr.timeout = 10 * 60 * 1000
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && data.onProgress) {
data.onProgress(Math.round((e.loaded / e.total) * 100))
}
}
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
resolve()
} else {
// 解析 OSS 返回的 XML 错误信息
let ossError = ""
try {
const codeMatch = xhr.responseText.match(/<Code>([^<]+)<\/Code>/)
const msgMatch = xhr.responseText.match(/<Message>([^<]+)<\/Message>/)
if (codeMatch || msgMatch) {
ossError = ` [OSS: ${codeMatch?.[1] || "unknown"} - ${msgMatch?.[1] || "unknown"}]`
}
} catch {
// 无法解析响应体
}
const detail = `OSS 直传失败: HTTP ${xhr.status} ${xhr.statusText}${ossError}`
console.error("[OSS Upload] 直传失败:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
status: xhr.status,
statusText: xhr.statusText,
})
reject(new Error(detail))
}
}
xhr.onerror = () => {
console.error("[OSS Upload] 网络错误:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
})
reject(new Error("OSS 上传网络错误,请检查网络连接"))
}
xhr.ontimeout = () => {
console.error("[OSS Upload] 上传超时:", {
url: prepared.upload_url,
storage_key: prepared.storage_key,
})
reject(new Error("OSS 上传超时(10分钟),请检查网络或尝试更小的文件"))
}
xhr.send(directForm)
})
return completeDirectUpload({
project_id: project.id,
library_id: data.library_id,
storage_key: prepared.storage_key,
})
}
+258 -46
View File
@@ -1,88 +1,300 @@
/**
* 任务历史页面 — V21 设计系统
* 页面头部 + 圆角胶囊 Tab 筛选(含计数)+ 卡片式任务列表 + 分页 + 空状态
* 使用 useQuery 对接后端真实 APIapi/tasks.ts
*/
import React from "react"
import { PageHeader, LoadingState, ErrorState, EmptyState } from "./components/States"
import { HistoryTabs, TaskItem, Pagination } from "./components/TaskList"
import { useTaskHistory } from "./hooks/useTaskHistory"
import React, { useState } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { Button } from "@/components/ui"
import { getUserTasks, retryTask, type TaskItem } from "@/api/tasks"
import "./history.css"
/* ============================================================
* 类型 & 常量
* ============================================================ */
type TaskStatus = "completed" | "processing" | "pending" | "failed"
const statusLabel: Record<TaskStatus, string> = {
completed: "已完成",
processing: "进行中",
pending: "排队中",
failed: "失败",
}
/** 将后端 status 字符串映射为前端 TaskStatus */
const normalizeStatus = (s: string): TaskStatus => {
const map: Record<string, TaskStatus> = {
completed: "completed",
succeeded: "completed",
success: "completed",
processing: "processing",
running: "processing",
pending: "pending",
queued: "pending",
failed: "failed",
error: "failed",
}
return map[s] ?? "pending"
}
/** 格式化日期 */
const formatDate = (iso?: string | null): string => {
if (!iso) return "—"
const d = new Date(iso)
if (isNaN(d.getTime())) return "—"
const pad = (n: number) => String(n).padStart(2, "0")
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
/* ============================================================
* Tab 配置
* ============================================================ */
interface TabConfig {
key: string
label: string
statusFilter?: TaskStatus
}
const tabs: TabConfig[] = [
{ key: "all", label: "全部" },
{ key: "processing", label: "进行中", statusFilter: "processing" },
{ key: "completed", label: "已完成", statusFilter: "completed" },
{ key: "failed", label: "失败", statusFilter: "failed" },
]
/* ============================================================
* 分页配置
* ============================================================ */
const PAGE_SIZE = 10
/* ============================================================
* 组件
* ============================================================ */
const TaskHistory: React.FC = () => {
const [activeTab, setActiveTab] = useState("all")
const [currentPage, setCurrentPage] = useState(1)
const queryClient = useQueryClient()
// ── 获取任务列表 ──
const {
activeTab,
currentPage,
totalPages,
tabs,
tabCounts,
paginatedTasks,
data: tasks = [],
isLoading,
isError,
error,
retryLoading,
setCurrentPage,
handleTabChange,
handleRetry,
handleView,
refetch,
} = useTaskHistory()
} = useQuery<TaskItem[], Error>({
queryKey: ["tasks"],
queryFn: getUserTasks,
staleTime: 30_000,
})
// Loading 状态
// ── 重试任务 mutation ──
const retryMutation = useMutation({
mutationFn: retryTask,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tasks"] })
},
})
// 将后端数据映射为页面展示用的结构
const mappedTasks = tasks.map((t) => ({
id: t.id,
name: t.user_message || t.task_type,
type: t.task_type,
template: t.template_id,
status: normalizeStatus(t.status),
date: formatDate(t.created_at),
duration: undefined as string | undefined,
progress: t.progress,
retryable: t.retryable,
errorMessage: t.error_message,
}))
// 获取当前 Tab 的筛选状态
const currentTab = tabs.find((t) => t.key === activeTab)
const statusFilter = currentTab?.statusFilter
// 过滤任务
const filteredTasks = statusFilter
? mappedTasks.filter((t) => t.status === statusFilter)
: mappedTasks
// 计算各 Tab 的数量
const tabCounts: Record<string, number> = {
all: mappedTasks.length,
processing: mappedTasks.filter((t) => t.status === "processing").length,
completed: mappedTasks.filter((t) => t.status === "completed").length,
failed: mappedTasks.filter((t) => t.status === "failed").length,
}
// 分页
const totalPages = Math.ceil(filteredTasks.length / PAGE_SIZE)
const paginatedTasks = filteredTasks.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
// 切换 Tab 时重置页码
const handleTabChange = (key: string) => {
setActiveTab(key)
setCurrentPage(1)
}
// 重试任务
const handleRetry = (taskId: string) => {
retryMutation.mutate(taskId)
}
// 查看任务详情
const handleView = (taskId: string) => {
// TODO: 跳转到任务详情页(待路由实现)
console.log("查看任务:", taskId)
}
// ── Loading 状态 ──
if (isLoading) {
return (
<div className="xx-history-page">
<PageHeader />
<LoadingState />
<div className="xx-history-header">
<h2></h2>
<p></p>
</div>
<div className="xx-history-empty">
<div className="xx-history-empty-icon"></div>
<h3>...</h3>
</div>
</div>
)
}
// Error 状态
// ── Error 状态 ──
if (isError) {
return (
<div className="xx-history-page">
<PageHeader />
<ErrorState message={error?.message} onRetry={() => refetch()} />
<div className="xx-history-header">
<h2></h2>
<p></p>
</div>
<div className="xx-history-empty">
<div className="xx-history-empty-icon"></div>
<h3></h3>
<p>{error?.message || "网络异常,请稍后重试"}</p>
<Button buttonType="primary" buttonSize="md" onClick={() => refetch()}>
</Button>
</div>
</div>
)
}
const totalCount = tabCounts[activeTab] ?? paginatedTasks.length
return (
<div className="xx-history-page">
<PageHeader />
{/* ── 页面头部 ──────────────────────────────────────────── */}
<div className="xx-history-header">
<h2></h2>
<p></p>
</div>
<HistoryTabs
tabs={tabs}
activeTab={activeTab}
tabCounts={tabCounts}
onChange={handleTabChange}
/>
{/* ── Tab 切换 ──────────────────────────────────────────── */}
<div className="xx-history-tabs">
{tabs.map((tab) => (
<button
key={tab.key}
className={`xx-history-tab${activeTab === tab.key ? " active" : ""}`}
onClick={() => handleTabChange(tab.key)}
>
{tab.label}
<span className="xx-history-tab-count">{tabCounts[tab.key]}</span>
</button>
))}
</div>
{/* 任务列表 */}
{/* ── 任务列表 ──────────────────────────────────────────── */}
{paginatedTasks.length === 0 ? (
<EmptyState activeTab={activeTab} />
<div className="xx-history-empty">
<div className="xx-history-empty-icon">📭</div>
<h3></h3>
<p>{activeTab === "all" ? "点击上方按钮开始创建任务" : "当前分类下没有任务"}</p>
</div>
) : (
<div className="xx-history-task-list">
{paginatedTasks.map((task) => (
<TaskItem
key={task.id}
task={task}
onRetry={handleRetry}
onView={handleView}
retryLoading={retryLoading}
/>
<div key={task.id} className="xx-history-task-item">
{/* 任务信息 */}
<div className="xx-history-task-info">
<h4>{task.name}</h4>
<span>
{task.type} · {task.template}
</span>
</div>
{/* 状态标签 */}
<span className={`xx-history-status xx-history-status--${task.status}`}>
{statusLabel[task.status]}
</span>
{/* 时间区 */}
<div className="xx-history-task-time">
<span>{task.date}</span>
{task.status === "completed" ? (
<span></span>
) : task.status === "processing" ? (
<span> {task.progress}%</span>
) : task.status === "failed" ? (
<span>{task.errorMessage || "请重试"}</span>
) : (
<span></span>
)}
</div>
{/* 操作按钮 */}
<div className="xx-history-task-action">
{task.status === "failed" && task.retryable ? (
<Button
buttonType="ghost"
buttonSize="sm"
onClick={() => handleRetry(task.id)}
disabled={retryMutation.isPending}
>
{retryMutation.isPending ? "重试中..." : "重试"}
</Button>
) : (
<Button buttonType="ghost" buttonSize="sm" onClick={() => handleView(task.id)}>
</Button>
)}
</div>
</div>
))}
</div>
)}
<Pagination
currentPage={currentPage}
totalPages={totalPages}
total={totalCount}
onChange={setCurrentPage}
/>
{/* ── 分页 ──────────────────────────────────────────────── */}
{totalPages > 1 && (
<div className="xx-history-pagination">
<button
className="xx-history-page-btn"
disabled={currentPage === 1}
onClick={() => setCurrentPage(currentPage - 1)}
>
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
<button
key={page}
className={`xx-history-page-btn${currentPage === page ? " active" : ""}`}
onClick={() => setCurrentPage(page)}
>
{page}
</button>
))}
<button
className="xx-history-page-btn"
disabled={currentPage === totalPages}
onClick={() => setCurrentPage(currentPage + 1)}
>
</button>
<span className="xx-history-page-info"> {filteredTasks.length} </span>
</div>
)}
</div>
)
}
@@ -1,52 +0,0 @@
import React from "react"
import { Button } from "@/components/ui"
interface LoadingStateProps {
title?: string
}
/** 加载状态 */
export const LoadingState: React.FC<LoadingStateProps> = ({ title = "加载中..." }) => (
<div className="xx-history-empty">
<div className="xx-history-empty-icon"></div>
<h3>{title}</h3>
</div>
)
interface ErrorStateProps {
message?: string
onRetry: () => void
}
/** 错误状态 */
export const ErrorState: React.FC<ErrorStateProps> = ({ message, onRetry }) => (
<div className="xx-history-empty">
<div className="xx-history-empty-icon"></div>
<h3></h3>
<p>{message || "网络异常,请稍后重试"}</p>
<Button buttonType="primary" buttonSize="md" onClick={onRetry}>
</Button>
</div>
)
interface EmptyStateProps {
activeTab?: string
}
/** 空状态 */
export const EmptyState: React.FC<EmptyStateProps> = ({ activeTab = "all" }) => (
<div className="xx-history-empty">
<div className="xx-history-empty-icon">📭</div>
<h3></h3>
<p>{activeTab === "all" ? "点击上方按钮开始创建任务" : "当前分类下没有任务"}</p>
</div>
)
/** 页面头部 */
export const PageHeader: React.FC = () => (
<div className="xx-history-header">
<h2></h2>
<p></p>
</div>
)
@@ -1,142 +0,0 @@
import React from "react"
import { Button } from "@/components/ui"
import type { TabConfig } from "../constants"
import type { MappedTask } from "../hooks/useTaskHistory"
import { statusLabel } from "../constants"
interface HistoryTabsProps {
tabs: TabConfig[]
activeTab: string
tabCounts: Record<string, number>
onChange: (key: string) => void
}
/** Tab 切换栏 */
export const HistoryTabs: React.FC<HistoryTabsProps> = ({
tabs,
activeTab,
tabCounts,
onChange,
}) => (
<div className="xx-history-tabs">
{tabs.map((tab) => (
<button
key={tab.key}
className={`xx-history-tab${activeTab === tab.key ? " active" : ""}`}
onClick={() => onChange(tab.key)}
>
{tab.label}
<span className="xx-history-tab-count">{tabCounts[tab.key]}</span>
</button>
))}
</div>
)
interface TaskItemProps {
task: MappedTask
onRetry: (id: string) => void
onView: (id: string) => void
retryLoading?: boolean
}
/** 单个任务卡片 */
export const TaskItem: React.FC<TaskItemProps> = ({ task, onRetry, onView, retryLoading }) => {
const getSubText = () => {
switch (task.status) {
case "completed":
return "完成"
case "processing":
return `进度 ${task.progress}%`
case "failed":
return task.errorMessage || "请重试"
default:
return "等待中"
}
}
return (
<div className="xx-history-task-item">
{/* 任务信息 */}
<div className="xx-history-task-info">
<h4>{task.name}</h4>
<span>
{task.type} · {task.template}
</span>
</div>
{/* 状态标签 */}
<span className={`xx-history-status xx-history-status--${task.status}`}>
{statusLabel[task.status]}
</span>
{/* 时间区 */}
<div className="xx-history-task-time">
<span>{task.date}</span>
<span>{getSubText()}</span>
</div>
{/* 操作按钮 */}
<div className="xx-history-task-action">
{task.status === "failed" && task.retryable ? (
<Button
buttonType="ghost"
buttonSize="sm"
onClick={() => onRetry(task.id)}
disabled={retryLoading}
>
{retryLoading ? "重试中..." : "重试"}
</Button>
) : (
<Button buttonType="ghost" buttonSize="sm" onClick={() => onView(task.id)}>
</Button>
)}
</div>
</div>
)
}
interface PaginationProps {
currentPage: number
totalPages: number
total: number
onChange: (page: number) => void
}
/** 分页组件 */
export const Pagination: React.FC<PaginationProps> = ({
currentPage,
totalPages,
total,
onChange,
}) => {
if (totalPages <= 1) return null
return (
<div className="xx-history-pagination">
<button
className="xx-history-page-btn"
disabled={currentPage === 1}
onClick={() => onChange(currentPage - 1)}
>
</button>
{Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
<button
key={page}
className={`xx-history-page-btn${currentPage === page ? " active" : ""}`}
onClick={() => onChange(page)}
>
{page}
</button>
))}
<button
className="xx-history-page-btn"
disabled={currentPage === totalPages}
onClick={() => onChange(currentPage + 1)}
>
</button>
<span className="xx-history-page-info"> {total} </span>
</div>
)
}
-28
View File
@@ -1,28 +0,0 @@
/** 任务状态 */
export type TaskStatus = "completed" | "processing" | "pending" | "failed"
/** 状态标签 */
export const statusLabel: Record<TaskStatus, string> = {
completed: "已完成",
processing: "进行中",
pending: "排队中",
failed: "失败",
}
/** Tab 配置 */
export interface TabConfig {
key: string
label: string
statusFilter?: TaskStatus
}
/** 默认 Tab 列表 */
export const TABS: TabConfig[] = [
{ key: "all", label: "全部" },
{ key: "processing", label: "进行中", statusFilter: "processing" },
{ key: "completed", label: "已完成", statusFilter: "completed" },
{ key: "failed", label: "失败", statusFilter: "failed" },
]
/** 每页数量 */
export const PAGE_SIZE = 10
@@ -1,131 +0,0 @@
import { useState, useMemo, useCallback } from "react"
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"
import { getUserTasks, retryTask, type TaskItem } from "@/api/tasks"
import { TABS, PAGE_SIZE, type TabConfig } from "../constants"
import { normalizeStatus, formatDate } from "../utils"
/** 映射后的任务列表项 */
export interface MappedTask {
id: string
name: string
type: string
template?: string
status: "completed" | "processing" | "pending" | "failed"
date: string
progress?: number
retryable?: boolean
errorMessage?: string
}
/**
* 任务历史业务 Hook
*/
export const useTaskHistory = () => {
const [activeTab, setActiveTab] = useState("all")
const [currentPage, setCurrentPage] = useState(1)
const queryClient = useQueryClient()
// 获取任务列表
const {
data: tasks = [],
isLoading,
isError,
error,
refetch,
} = useQuery<TaskItem[], Error>({
queryKey: ["tasks"],
queryFn: getUserTasks,
staleTime: 30_000,
})
// 重试 mutation
const retryMutation = useMutation({
mutationFn: retryTask,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["tasks"] })
},
})
// 映射后端数据
const mappedTasks: MappedTask[] = useMemo(
() =>
tasks.map((t) => ({
id: t.id,
name: t.user_message || t.task_type,
type: t.task_type,
template: t.template_id,
status: normalizeStatus(t.status),
date: formatDate(t.created_at),
progress: t.progress,
retryable: t.retryable,
errorMessage: t.error_message,
})),
[tasks],
)
// 当前 Tab 筛选
const currentTabConfig: TabConfig | undefined = TABS.find((t) => t.key === activeTab)
const statusFilter = currentTabConfig?.statusFilter
// 过滤任务
const filteredTasks = useMemo(
() => (statusFilter ? mappedTasks.filter((t) => t.status === statusFilter) : mappedTasks),
[mappedTasks, statusFilter],
)
// 各 Tab 计数
const tabCounts: Record<string, number> = useMemo(
() => ({
all: mappedTasks.length,
processing: mappedTasks.filter((t) => t.status === "processing").length,
completed: mappedTasks.filter((t) => t.status === "completed").length,
failed: mappedTasks.filter((t) => t.status === "failed").length,
}),
[mappedTasks],
)
// 分页
const totalPages = Math.ceil(filteredTasks.length / PAGE_SIZE)
const paginatedTasks = filteredTasks.slice((currentPage - 1) * PAGE_SIZE, currentPage * PAGE_SIZE)
// 切换 Tab
const handleTabChange = useCallback((key: string) => {
setActiveTab(key)
setCurrentPage(1)
}, [])
// 重试
const handleRetry = useCallback(
(taskId: string) => {
retryMutation.mutate(taskId)
},
[retryMutation],
)
// 查看详情
const handleView = useCallback((taskId: string) => {
// TODO: 跳转到任务详情页(待路由实现)
console.log("查看任务:", taskId)
}, [])
return {
// 状态
activeTab,
currentPage,
totalPages,
// 数据
tabs: TABS,
tabCounts,
paginatedTasks,
isLoading,
isError,
error,
retryLoading: retryMutation.isPending,
// 操作
setCurrentPage,
handleTabChange,
handleRetry,
handleView,
refetch,
}
}
-26
View File
@@ -1,26 +0,0 @@
import type { TaskStatus } from "./constants"
/** 将后端 status 字符串映射为前端 TaskStatus */
export const normalizeStatus = (s: string): TaskStatus => {
const map: Record<string, TaskStatus> = {
completed: "completed",
succeeded: "completed",
success: "completed",
processing: "processing",
running: "processing",
pending: "pending",
queued: "pending",
failed: "failed",
error: "failed",
}
return map[s] ?? "pending"
}
/** 格式化日期 */
export const formatDate = (iso?: string | null): string => {
if (!iso) return "—"
const d = new Date(iso)
if (isNaN(d.getTime())) return "—"
const pad = (n: number) => String(n).padStart(2, "0")
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}