fix: migrate UI to V2 API and fix admin dashboard

Backend fixes:
- Fix markdown generation using correct 'markdown_content' key in tasks.py
- Update admin service to return flat data structure matching frontend types
- Add task_count and failed_tasks fields to user statistics
- Fix top users endpoint to return complete user data

Frontend fixes:
- Migrate ResultsPage from V1 batch API to V2 task API with polling
- Create TaskDetailPage component with markdown preview and download buttons
- Refactor ExportPage to support multi-task selection using V2 download endpoints
- Fix login infinite refresh loop with concurrency control flags
- Create missing Checkbox UI component

New features:
- Add /tasks/:taskId route for task detail view
- Implement multi-task batch export functionality
- Add real-time task status polling (2s interval)

OpenSpec:
- Archive completed proposal 2025-11-17-fix-v2-api-ui-issues
- Create result-export and task-management specifications

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
egg
2025-11-17 08:55:50 +08:00
parent 62609de57c
commit 012da1abc4
15 changed files with 1122 additions and 496 deletions

View File

@@ -1,53 +1,43 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useTranslation } from 'react-i18next'
import { useQuery } from '@tanstack/react-query'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
import ResultsTable from '@/components/ResultsTable'
import MarkdownPreview from '@/components/MarkdownPreview'
import { useToast } from '@/components/ui/toast'
import { useUploadStore } from '@/store/uploadStore'
import { apiClient } from '@/services/api'
import { FileText, Download, Languages, AlertCircle, TrendingUp, Clock, Layers } from 'lucide-react'
import { apiClientV2 } from '@/services/apiV2'
import { FileText, Download, AlertCircle, TrendingUp, Clock, Layers, FileJson, Loader2 } from 'lucide-react'
import { Badge } from '@/components/ui/badge'
export default function ResultsPage() {
const { t } = useTranslation()
const navigate = useNavigate()
const { toast } = useToast()
const { batchId } = useUploadStore()
const [selectedFileId, setSelectedFileId] = useState<number | null>(null)
// Get batch status to show results
const { data: batchStatus } = useQuery({
queryKey: ['batchStatus', batchId],
queryFn: () => apiClient.getBatchStatus(batchId!),
enabled: !!batchId,
// In V2, batchId is actually a task_id (string)
const taskId = batchId ? String(batchId) : null
// Get task details
const { data: taskDetail, isLoading } = useQuery({
queryKey: ['taskDetail', taskId],
queryFn: () => apiClientV2.getTask(taskId!),
enabled: !!taskId,
refetchInterval: (query) => {
const data = query.state.data
if (!data) return 2000
if (data.status === 'completed' || data.status === 'failed') {
return false
}
return 2000
},
})
// Get OCR result for selected file
const { data: ocrResult, isLoading: isLoadingResult } = useQuery({
queryKey: ['ocrResult', selectedFileId],
queryFn: () => apiClient.getOCRResult(selectedFileId!),
enabled: !!selectedFileId,
})
const handleViewResult = (fileId: number) => {
setSelectedFileId(fileId)
}
const handleDownloadPDF = async (fileId: number) => {
const handleDownloadPDF = async () => {
if (!taskId) return
try {
const blob = await apiClient.exportPDF(fileId)
const url = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = `ocr-result-${fileId}.pdf`
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
document.body.removeChild(a)
await apiClientV2.downloadPDF(taskId)
toast({
title: t('export.exportSuccess'),
description: 'PDF 已下載',
@@ -62,12 +52,57 @@ export default function ResultsPage() {
}
}
const handleExport = () => {
navigate('/export')
const handleDownloadMarkdown = async () => {
if (!taskId) return
try {
await apiClientV2.downloadMarkdown(taskId)
toast({
title: t('export.exportSuccess'),
description: 'Markdown 已下載',
variant: 'success',
})
} catch (error: any) {
toast({
title: t('export.exportError'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
}
}
// Show helpful message when no batch is selected
if (!batchId) {
const handleDownloadJSON = async () => {
if (!taskId) return
try {
await apiClientV2.downloadJSON(taskId)
toast({
title: t('export.exportSuccess'),
description: 'JSON 已下載',
variant: 'success',
})
} catch (error: any) {
toast({
title: t('export.exportError'),
description: error.response?.data?.detail || t('errors.networkError'),
variant: 'destructive',
})
}
}
const getStatusBadge = (status: string) => {
switch (status) {
case 'completed':
return <Badge variant="default" className="bg-green-600"></Badge>
case 'processing':
return <Badge variant="default"></Badge>
case 'failed':
return <Badge variant="destructive"></Badge>
default:
return <Badge variant="secondary"></Badge>
}
}
// Show helpful message when no task is selected
if (!taskId) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<Card className="max-w-md text-center">
@@ -81,7 +116,7 @@ export default function ResultsPage() {
</CardHeader>
<CardContent className="space-y-4">
<p className="text-muted-foreground">
{t('results.noBatchMessage', { defaultValue: '尚未選擇任何批次。請先上傳並處理檔案。' })}
{t('results.noBatchMessage', { defaultValue: '尚未選擇任何任務。請先上傳並處理檔案。' })}
</p>
<Button onClick={() => navigate('/upload')} size="lg">
{t('results.goToUpload', { defaultValue: '前往上傳頁面' })}
@@ -92,7 +127,35 @@ export default function ResultsPage() {
)
}
const completedFiles = batchStatus?.files.filter((f) => f.status === 'completed') || []
if (isLoading) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<div className="text-center">
<Loader2 className="w-12 h-12 animate-spin text-primary mx-auto mb-4" />
<p className="text-muted-foreground">...</p>
</div>
</div>
)
}
if (!taskDetail) {
return (
<div className="flex items-center justify-center min-h-[60vh]">
<Card className="max-w-md text-center">
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<Button onClick={() => navigate('/tasks')}>
</Button>
</CardContent>
</Card>
</div>
)
}
const isCompleted = taskDetail.status === 'completed'
return (
<div className="space-y-6">
@@ -102,115 +165,124 @@ export default function ResultsPage() {
<div>
<h1 className="page-title">{t('results.title')}</h1>
<p className="text-muted-foreground mt-1">
ID: <span className="font-mono text-primary">{batchId}</span> · {completedFiles.length}
ID: <span className="font-mono text-primary">{taskId}</span>
{taskDetail.filename && ` · ${taskDetail.filename}`}
</p>
</div>
<div className="flex gap-3">
<Button onClick={handleExport} className="gap-2">
<Download className="w-4 h-4" />
{t('nav.export')}
</Button>
<Button
variant="outline"
disabled
title={t('translation.comingSoon')}
className="gap-2"
>
<Languages className="w-4 h-4" />
{t('translation.title')}
<span className="text-xs bg-warning/20 text-warning px-2 py-0.5 rounded ml-1">
</span>
</Button>
<div className="flex gap-3 items-center">
{getStatusBadge(taskDetail.status)}
{isCompleted && (
<>
<Button onClick={handleDownloadJSON} variant="outline" className="gap-2">
<FileJson className="w-4 h-4" />
JSON
</Button>
<Button onClick={handleDownloadMarkdown} variant="outline" className="gap-2">
<FileText className="w-4 h-4" />
Markdown
</Button>
<Button onClick={handleDownloadPDF} className="gap-2">
<Download className="w-4 h-4" />
PDF
</Button>
</>
)}
</div>
</div>
</div>
<div className="grid grid-cols-1 lg:grid-cols-5 gap-6">
{/* Results Table - Takes 2 columns */}
<div className="lg:col-span-2">
<ResultsTable
files={batchStatus?.files || []}
onViewResult={handleViewResult}
onDownloadPDF={handleDownloadPDF}
/>
</div>
{/* Preview Panel - Takes 3 columns */}
<div className="lg:col-span-3">
{selectedFileId && ocrResult ? (
<div className="space-y-4">
{/* Preview Card */}
<MarkdownPreview
title={`${t('results.viewMarkdown')} - ${ocrResult.filename}`}
content={ocrResult.markdown_content}
/>
{/* Stats Grid */}
<div className="grid grid-cols-3 gap-3">
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="p-2 bg-success/10 rounded-lg">
<TrendingUp className="w-5 h-5 text-success" />
</div>
<div>
<p className="text-xs text-muted-foreground"></p>
<p className="text-lg font-bold text-foreground">
{((ocrResult.confidence || 0) * 100).toFixed(1)}%
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="p-2 bg-primary/10 rounded-lg">
<Clock className="w-5 h-5 text-primary" />
</div>
<div>
<p className="text-xs text-muted-foreground"></p>
<p className="text-lg font-bold text-foreground">
{(ocrResult.processing_time || 0).toFixed(2)}s
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-4">
<div className="flex items-center gap-3">
<div className="p-2 bg-accent/10 rounded-lg">
<Layers className="w-5 h-5 text-accent" />
</div>
<div>
<p className="text-xs text-muted-foreground"></p>
<p className="text-lg font-bold text-foreground">
{ocrResult.json_data?.total_text_regions || 0}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
) : (
<Card className="h-full min-h-[400px]">
<CardContent className="h-full flex flex-col items-center justify-center p-12">
<div className="w-16 h-16 bg-muted rounded-full flex items-center justify-center mb-4">
<FileText className="w-8 h-8 text-muted-foreground" />
{/* Stats Grid */}
{isCompleted && (
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="p-3 bg-primary/10 rounded-lg">
<Clock className="w-6 h-6 text-primary" />
</div>
<p className="text-muted-foreground text-center">
{isLoadingResult ? t('common.loading') : '選擇左側檔案以查看詳細結果'}
</p>
</CardContent>
</Card>
)}
<div>
<p className="text-sm text-muted-foreground"></p>
<p className="text-2xl font-bold">
{taskDetail.processing_time_ms ? (taskDetail.processing_time_ms / 1000).toFixed(2) : '0'}s
</p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="p-3 bg-success/10 rounded-lg">
<TrendingUp className="w-6 h-6 text-success" />
</div>
<div>
<p className="text-sm text-muted-foreground"></p>
<p className="text-2xl font-bold text-success"></p>
</div>
</div>
</CardContent>
</Card>
<Card>
<CardContent className="p-6">
<div className="flex items-center gap-3">
<div className="p-3 bg-accent/10 rounded-lg">
<Layers className="w-6 h-6 text-accent" />
</div>
<div>
<p className="text-sm text-muted-foreground"></p>
<p className="text-2xl font-bold">OCR</p>
</div>
</div>
</CardContent>
</Card>
</div>
</div>
)}
{/* Results Preview */}
{isCompleted ? (
<Card>
<CardHeader>
<CardTitle></CardTitle>
</CardHeader>
<CardContent>
<MarkdownPreview
title={`OCR 結果 - ${taskDetail.filename || '未知檔案'}`}
content="請使用上方下載按鈕下載 Markdown 或 JSON 格式查看完整結果"
/>
</CardContent>
</Card>
) : taskDetail.status === 'processing' ? (
<Card>
<CardContent className="p-12 text-center">
<Loader2 className="w-16 h-16 animate-spin text-primary mx-auto mb-4" />
<p className="text-lg font-semibold">...</p>
<p className="text-muted-foreground mt-2">OCR </p>
</CardContent>
</Card>
) : taskDetail.status === 'failed' ? (
<Card>
<CardContent className="p-12 text-center">
<AlertCircle className="w-16 h-16 text-destructive mx-auto mb-4" />
<p className="text-lg font-semibold text-destructive"></p>
{taskDetail.error_message && (
<p className="text-muted-foreground mt-2">{taskDetail.error_message}</p>
)}
</CardContent>
</Card>
) : (
<Card>
<CardContent className="p-12 text-center">
<Clock className="w-16 h-16 text-muted-foreground mx-auto mb-4" />
<p className="text-lg font-semibold"></p>
<p className="text-muted-foreground mt-2"> OCR </p>
<Button onClick={() => navigate('/processing')} className="mt-4">
</Button>
</CardContent>
</Card>
)}
</div>
)
}