Compare commits

..

2 Commits

Author SHA1 Message Date
xiaoxia ff845c3086 Merge branch 'develop' into refactor/products-api
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 30s
CI/CD Pipeline / Frontend Lint (pull_request) Successful in 43s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 1m17s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 1m16s
CI/CD Pipeline / Validate - Code Quality (pull_request) Failing after 1m59s
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 28s
CI/CD Pipeline / PR Build Web Image (pull_request) Successful in 1m54s
AI Code Review / AI Code Review (pull_request) Successful in 1m19s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 3m36s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 46s
Preview Deploy / Deploy Preview Environment (pull_request) Successful in 34s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 15m19s
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 / 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 20s
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 17s
CI/CD Pipeline / Production Browser E2E (pull_request) Has been skipped
2026-07-27 12:34:58 +08:00
xiaoxia 17d6530438 refactor(api): 拆分 products.ts 为目录结构(types/utils/products/index)
CI/CD Pipeline / Check if frontend-only change (pull_request) Successful in 26s
CI/CD Pipeline / Frontend Lint (pull_request) Failing after 37s
CI/CD Pipeline / Validate - Migration (alembic) (pull_request) Successful in 1m25s
CI/CD Pipeline / Validate - Type Check (mypy) (pull_request) Successful in 1m26s
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 57s
CI/CD Pipeline / Validate - Code Quality (pull_request) Failing after 2m27s
AI Code Review / AI Code Review (pull_request) Successful in 1m16s
Preview Deploy / Deploy Preview Environment (pull_request) Failing after 32s
PR Automation / Auto Approve on CI Green (pull_request) Successful in 59s
PR Automation / Auto Merge on CI Green + Approved (pull_request) Successful in 56s
CI/CD Pipeline / PR Build Web Image (pull_request) Failing after 2m29s
CI/CD Pipeline / PR Build API Image (pull_request) Successful in 6m6s
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 / Frontend Unit Tests (pull_request) Failing after 21s
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 / 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
将 174 行的 products.ts 拆分为目录化结构:
- types.ts: 类型定义(ProductItem/VideoItem/ReviewStatus 等)
- utils.ts: 数据转换函数(mapVideoToProductItem)
- products.ts: 全部 7 个 API 函数
- index.ts: 统一入口 re-export,保持 @/api/products 路径向后兼容

主入口从 174 行减少到约 40 行,按职责清晰分层。
2026-07-26 17:07:23 +08:00
11 changed files with 475 additions and 599 deletions
-174
View File
@@ -1,174 +0,0 @@
/**
* 成品 / 视频相关 API
* 后端实际接口:/videos
*/
import apiClient from "./client"
/** 复核状态 */
export type ReviewStatus = "pending_review" | "approved" | "rejected"
/** 成品条目 */
export interface ProductItem {
id: string
title: string
video_url?: string
thumbnail_url?: string
duration_seconds?: number
file_size?: number
resolution?: string
status: "processing" | "completed" | "failed"
/** 复核状态 */
review_status?: ReviewStatus
/** 所属项目 ID */
project_id?: string
/** 所属项目名称 */
project_name?: string
/** 查重率(百分比) */
duplicate_rate?: number
created_at?: string
updated_at?: string
}
/** 列表查询参数 */
export interface ProductListParams {
page?: number
page_size?: number
project_id?: string
review_status?: ReviewStatus | "all"
}
/** 分页响应 */
export interface ProductListResponse {
items: ProductItem[]
total: number
page: number
page_size: number
}
/** 批量下载任务状态 */
export interface BatchDownloadStatus {
job_id: string
status: "processing" | "completed" | "failed"
/** 完成后返回的下载 URL */
download_url?: string
/** 进度百分比 */
progress?: number
}
/** 后端 /videos 接口返回的原始视频条目 */
interface VideoItem {
id: string
project_id: string
generation_task_id: string
name: string
file_url: string
file_size: number
duration: number
thumbnail_url: string | null
width: number
height: number
fps: number
status: string
review_status: ReviewStatus
generation_params: Record<string, unknown>
download_url: string
generated_at: string
}
/**
* 将后端 VideoItem 映射为 ProductItem 格式
*/
function mapVideoToProductItem(video: VideoItem): ProductItem {
return {
id: video.id,
title: video.name || "未命名视频",
// 优先用 download_url(带签名)播放,file_url 无签名无法访问
video_url: video.download_url || video.file_url,
thumbnail_url: video.thumbnail_url || undefined,
duration_seconds: video.duration,
file_size: video.file_size,
resolution: video.width && video.height ? `${video.width}x${video.height}` : undefined,
status:
video.status === "completed"
? "completed"
: video.status === "failed"
? "failed"
: "processing",
review_status: video.review_status,
project_id: video.project_id,
// 后端 /videos 接口暂无 project_name 字段
project_name: undefined,
// 后端字段名为 generated_at,映射为 created_at 供前端统一使用
created_at: video.generated_at,
updated_at: video.generated_at,
// 后端 /videos 接口暂无 duplicate_rate 字段
duplicate_rate: undefined,
}
}
/** 获取成品列表(支持分页和筛选) */
export const getProducts = async (params?: ProductListParams): Promise<ProductItem[]> => {
const response = await apiClient.get("/videos", { params })
const data = response.data
const videos: VideoItem[] = Array.isArray(data?.items)
? data.items
: Array.isArray(data)
? data
: []
return videos.map(mapVideoToProductItem)
}
/** 获取单个成品详情 */
export const getProduct = async (productId: string): Promise<ProductItem> => {
const response = await apiClient.get(`/videos/${productId}`)
return mapVideoToProductItem(response.data as VideoItem)
}
/**
* 删除成品
* 注意:后端暂未实现 /videos DELETE 接口,调用会返回 405
* 待后端实现后自动生效
*/
export const deleteProduct = async (productId: string): Promise<void> => {
await apiClient.delete(`/videos/${productId}`)
}
/**
* 获取成品下载链接
* 直接使用列表返回的 download_url(带OSS签名)
*/
export const getProductDownloadUrl = async (
productId: string,
): Promise<{ url: string; expires_at: string }> => {
// 优先从列表缓存取;如果没有则调详情接口
const product = await getProduct(productId)
if (!product.video_url) throw new Error("下载链接不可用")
return { url: product.video_url, expires_at: "" }
}
/** 更新复核状态 — TODO: 后端暂无对应端点,暂存本地状态 */
export const updateReviewStatus = async (
productId: string,
status: ReviewStatus,
): Promise<ProductItem> => {
// 后端暂无 /videos/{id}/review 端点
// 暂时返回当前状态,后续可扩展
const product = await getProduct(productId)
return { ...product, review_status: status }
}
/** 发起批量下载 — TODO: 后端暂无对应端点 */
export const batchDownload = async (videoIds: string[]): Promise<{ job_id: string }> => {
// 后端暂无 /videos/batch-download 端点
// 暂时返回模拟 job_id,后续可扩展
console.warn("[batchDownload] 后端暂无批量下载端点", videoIds)
return { job_id: `mock-${Date.now()}` }
}
/** 查询批量下载状态 — TODO: 后端暂无对应端点 */
export const getBatchDownloadStatus = async (jobId: string): Promise<BatchDownloadStatus> => {
// 后端暂无 /videos/batch-download/{jobId} 端点
// 暂时返回模拟状态,后续可扩展
console.warn("[getBatchDownloadStatus] 后端暂无批量下载状态端点", jobId)
return { job_id: jobId, status: "processing", progress: 0 }
}
+28
View File
@@ -0,0 +1,28 @@
/**
* 成品 / 视频相关 API — 目录化入口
* 保持与原 products.ts 相同导出,向后兼容
*/
// 类型
export type {
ReviewStatus,
ProductItem,
ProductListParams,
ProductListResponse,
BatchDownloadStatus,
VideoItem,
} from "./types"
// 工具函数
export { mapVideoToProductItem } from "./utils"
// API 函数
export {
getProducts,
getProduct,
deleteProduct,
getProductDownloadUrl,
updateReviewStatus,
batchDownload,
getBatchDownloadStatus,
} from "./products"
+80
View File
@@ -0,0 +1,80 @@
/**
* 成品 / 视频相关 API 函数
* 后端实际接口:/videos
*/
import apiClient from "../client"
import type {
BatchDownloadStatus,
ProductItem,
ProductListParams,
VideoItem,
ReviewStatus,
} from "./types"
import { mapVideoToProductItem } from "./utils"
/** 获取成品列表(支持分页和筛选) */
export const getProducts = async (params?: ProductListParams): Promise<ProductItem[]> => {
const response = await apiClient.get("/videos", { params })
const data = response.data
const videos: VideoItem[] = Array.isArray(data?.items)
? data.items
: Array.isArray(data)
? data
: []
return videos.map(mapVideoToProductItem)
}
/** 获取单个成品详情 */
export const getProduct = async (productId: string): Promise<ProductItem> => {
const response = await apiClient.get(`/videos/${productId}`)
return mapVideoToProductItem(response.data as VideoItem)
}
/**
* 删除成品
* 注意:后端暂未实现 /videos DELETE 接口,调用会返回 405
* 待后端实现后自动生效
*/
export const deleteProduct = async (productId: string): Promise<void> => {
await apiClient.delete(`/videos/${productId}`)
}
/**
* 获取成品下载链接
* 直接使用列表返回的 download_url(带OSS签名)
*/
export const getProductDownloadUrl = async (
productId: string,
): Promise<{ url: string; expires_at: string }> => {
// 优先从列表缓存取;如果没有则调详情接口
const product = await getProduct(productId)
if (!product.video_url) throw new Error("下载链接不可用")
return { url: product.video_url, expires_at: "" }
}
/** 更新复核状态 — TODO: 后端暂无对应端点,暂存本地状态 */
export const updateReviewStatus = async (
productId: string,
status: ReviewStatus,
): Promise<ProductItem> => {
// 后端暂无 /videos/{id}/review 端点
// 暂时返回当前状态,后续可扩展
const product = await getProduct(productId)
return { ...product, review_status: status }
}
/** 发起批量下载 — TODO: 后端暂无对应端点 */
export const batchDownload = async (videoIds: string[]): Promise<{ job_id: string }> => {
// 后端暂无 /videos/batch-download 端点
// 暂时返回模拟 job_id,后续可扩展
console.warn("[batchDownload] 后端暂无批量下载端点", videoIds)
return { job_id: `mock-${Date.now()}` }
}
/** 查询批量下载状态 — TODO: 后端暂无对应端点 */
export const getBatchDownloadStatus = async (jobId: string): Promise<BatchDownloadStatus> => {
// 后端暂无 /videos/batch-download/{jobId} 端点
// 暂时返回模拟状态,后续可扩展
console.warn("[getBatchDownloadStatus] 后端暂无批量下载状态端点", jobId)
return { job_id: jobId, status: "processing", progress: 0 }
}
+74
View File
@@ -0,0 +1,74 @@
/**
* 成品 / 视频相关类型定义
*/
/** 复核状态 */
export type ReviewStatus = "pending_review" | "approved" | "rejected"
/** 成品条目 */
export interface ProductItem {
id: string
title: string
video_url?: string
thumbnail_url?: string
duration_seconds?: number
file_size?: number
resolution?: string
status: "processing" | "completed" | "failed"
/** 复核状态 */
review_status?: ReviewStatus
/** 所属项目 ID */
project_id?: string
/** 所属项目名称 */
project_name?: string
/** 查重率(百分比) */
duplicate_rate?: number
created_at?: string
updated_at?: string
}
/** 列表查询参数 */
export interface ProductListParams {
page?: number
page_size?: number
project_id?: string
review_status?: ReviewStatus | "all"
}
/** 分页响应 */
export interface ProductListResponse {
items: ProductItem[]
total: number
page: number
page_size: number
}
/** 批量下载任务状态 */
export interface BatchDownloadStatus {
job_id: string
status: "processing" | "completed" | "failed"
/** 完成后返回的下载 URL */
download_url?: string
/** 进度百分比 */
progress?: number
}
/** 后端 /videos 接口返回的原始视频条目 */
export interface VideoItem {
id: string
project_id: string
generation_task_id: string
name: string
file_url: string
file_size: number
duration: number
thumbnail_url: string | null
width: number
height: number
fps: number
status: string
review_status: ReviewStatus
generation_params: Record<string, unknown>
download_url: string
generated_at: string
}
+35
View File
@@ -0,0 +1,35 @@
/**
* 成品数据转换工具函数
*/
import type { ProductItem, VideoItem } from "./types"
/**
* 将后端 VideoItem 映射为 ProductItem 格式
*/
export function mapVideoToProductItem(video: VideoItem): ProductItem {
return {
id: video.id,
title: video.name || "未命名视频",
// 优先用 download_url(带签名)播放,file_url 无签名无法访问
video_url: video.download_url || video.file_url,
thumbnail_url: video.thumbnail_url || undefined,
duration_seconds: video.duration,
file_size: video.file_size,
resolution: video.width && video.height ? `${video.width}x${video.height}` : undefined,
status:
video.status === "completed"
? "completed"
: video.status === "failed"
? "failed"
: "processing",
review_status: video.review_status,
project_id: video.project_id,
// 后端 /videos 接口暂无 project_name 字段
project_name: undefined,
// 后端字段名为 generated_at,映射为 created_at 供前端统一使用
created_at: video.generated_at,
updated_at: video.generated_at,
// 后端 /videos 接口暂无 duplicate_rate 字段
duplicate_rate: undefined,
}
}
+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())}`
}