feat(audit): Enhance CreateTaskDialog with improved task creation workflow

- Add navigation to project details page after task creation
- Update task creation process with more detailed toast notifications
- Modify created_by field to handle null scenario for system users
- Refactor CreateTaskDialog to improve user experience and error handling
- Optimize repoScan service with more robust background task processing
- Update example image for visual consistency
Improves the audit task creation flow by providing better user feedback and streamlining the post-creation experience.
This commit is contained in:
lintsinghua 2025-10-22 22:18:19 +08:00
parent 96e15452e8
commit 9b11e47b36
5 changed files with 153 additions and 93 deletions

Binary file not shown.

Before

Width:  |  Height:  |  Size: 424 KiB

After

Width:  |  Height:  |  Size: 368 KiB

View File

@ -1,4 +1,5 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input"; import { Input } from "@/components/ui/input";
@ -30,6 +31,7 @@ interface CreateTaskDialogProps {
} }
export default function CreateTaskDialog({ open, onOpenChange, onTaskCreated, preselectedProjectId }: CreateTaskDialogProps) { export default function CreateTaskDialog({ open, onOpenChange, onTaskCreated, preselectedProjectId }: CreateTaskDialogProps) {
const navigate = useNavigate();
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [creating, setCreating] = useState(false); const [creating, setCreating] = useState(false);
@ -98,13 +100,21 @@ export default function CreateTaskDialog({ open, onOpenChange, onTaskCreated, pr
await api.createAuditTask({ await api.createAuditTask({
...taskForm, ...taskForm,
created_by: "system" // 无登录场景下使用系统用户 created_by: null // 无登录场景下设置为null
} as any); } as any);
toast.success("审计任务创建成功"); // 显示详细的提示信息
toast.success("审计任务创建成功", {
description: '因为网络和代码文件大小等因素审计时长通常至少需要1分钟请耐心等待...',
duration: 5000
});
onOpenChange(false); onOpenChange(false);
resetForm(); resetForm();
onTaskCreated(); onTaskCreated();
// 跳转到项目详情页面
navigate(`/projects/${taskForm.project_id}`);
} catch (error) { } catch (error) {
console.error('Failed to create task:', error); console.error('Failed to create task:', error);
toast.error("创建任务失败"); toast.error("创建任务失败");

View File

@ -45,6 +45,10 @@ export async function runRepositoryAudit(params: {
created_by: params.createdBy created_by: params.createdBy
} as any); } as any);
const taskId = (task as any).id as string;
// 启动后台审计任务,不阻塞返回
(async () => {
try { try {
const m = params.repoUrl.match(/github\.com\/(.+?)\/(.+?)(?:\.git)?$/i); const m = params.repoUrl.match(/github\.com\/(.+?)\/(.+?)(?:\.git)?$/i);
if (!m) throw new Error("仅支持 GitHub 仓库 URL例如 https://github.com/owner/repo"); if (!m) throw new Error("仅支持 GitHub 仓库 URL例如 https://github.com/owner/repo");
@ -80,7 +84,7 @@ export async function runRepositoryAudit(params: {
createdIssues += issues.length; createdIssues += issues.length;
for (const issue of issues) { for (const issue of issues) {
await api.createAuditIssue({ await api.createAuditIssue({
task_id: (task as any).id, task_id: taskId,
file_path: f.path, file_path: f.path,
line_number: issue.line || null, line_number: issue.line || null,
column_number: issue.column || null, column_number: issue.column || null,
@ -97,7 +101,7 @@ export async function runRepositoryAudit(params: {
} as any); } as any);
} }
if (totalFiles % 10 === 0) { if (totalFiles % 10 === 0) {
await api.updateAuditTask((task as any).id, { status: "running", total_files: totalFiles, scanned_files: totalFiles, total_lines: totalLines, issues_count: createdIssues } as any); await api.updateAuditTask(taskId, { status: "running", total_files: totalFiles, scanned_files: totalFiles, total_lines: totalLines, issues_count: createdIssues } as any);
} }
} catch {} } catch {}
await new Promise(r=>setTimeout(r, LLM_GAP_MS)); await new Promise(r=>setTimeout(r, LLM_GAP_MS));
@ -107,12 +111,15 @@ export async function runRepositoryAudit(params: {
const pool = Array.from({ length: Math.min(LLM_CONCURRENCY, files.length) }, () => worker()); const pool = Array.from({ length: Math.min(LLM_CONCURRENCY, files.length) }, () => worker());
await Promise.all(pool); await Promise.all(pool);
await api.updateAuditTask((task as any).id, { status: "completed", total_files: totalFiles, scanned_files: totalFiles, total_lines: totalLines, issues_count: createdIssues, quality_score: 0 } as any); await api.updateAuditTask(taskId, { status: "completed", total_files: totalFiles, scanned_files: totalFiles, total_lines: totalLines, issues_count: createdIssues, quality_score: 0 } as any);
return (task as any).id as string;
} catch (e) { } catch (e) {
await api.updateAuditTask((task as any).id, { status: "failed" } as any); console.error('审计任务执行失败:', e);
throw e; await api.updateAuditTask(taskId, { status: "failed" } as any);
} }
})();
// 立即返回任务ID让用户可以跳转到任务详情页面
return taskId;
} }

View File

@ -1,5 +1,5 @@
import { useState, useEffect } from "react"; import { useState, useEffect } from "react";
import { useParams, Link } from "react-router-dom"; import { useParams, Link, useNavigate } from "react-router-dom";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
@ -26,6 +26,7 @@ import CreateTaskDialog from "@/components/audit/CreateTaskDialog";
export default function ProjectDetail() { export default function ProjectDetail() {
const { id } = useParams<{ id: string }>(); const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const [project, setProject] = useState<Project | null>(null); const [project, setProject] = useState<Project | null>(null);
const [tasks, setTasks] = useState<AuditTask[]>([]); const [tasks, setTasks] = useState<AuditTask[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
@ -66,17 +67,28 @@ export default function ProjectDetail() {
} }
try { try {
setScanning(true); setScanning(true);
await runRepositoryAudit({ console.log('开始启动审计任务...');
const taskId = await runRepositoryAudit({
projectId: id, projectId: id,
repoUrl: project.repository_url, repoUrl: project.repository_url,
branch: project.default_branch || 'main', branch: project.default_branch || 'main',
githubToken: undefined, githubToken: undefined,
createdBy: undefined createdBy: undefined
}); });
toast.success('已启动仓库审计');
await loadProjectData(); console.log('审计任务创建成功taskId:', taskId);
// 显示详细的提示信息
toast.success('审计任务已启动', {
description: '因为网络和代码文件大小等因素审计时长通常至少需要1分钟请耐心等待...',
duration: 5000
});
// 跳转到任务详情页面
console.log('准备跳转到:', `/tasks/${taskId}`);
navigate(`/tasks/${taskId}`);
} catch (e: any) { } catch (e: any) {
console.error(e); console.error('启动审计失败:', e);
toast.error(e?.message || '启动审计失败'); toast.error(e?.message || '启动审计失败');
} finally { } finally {
setScanning(false); setScanning(false);
@ -116,7 +128,10 @@ export default function ProjectDetail() {
}; };
const handleTaskCreated = () => { const handleTaskCreated = () => {
toast.success("审计任务已创建"); toast.success("审计任务已创建", {
description: '因为网络和代码文件大小等因素审计时长通常至少需要1分钟请耐心等待...',
duration: 5000
});
loadProjectData(); // 重新加载项目数据以显示新任务 loadProjectData(); // 重新加载项目数据以显示新任务
}; };

View File

@ -29,12 +29,15 @@ import { scanZipFile, validateZipFile } from "@/features/projects/services";
import type { Project, CreateProjectForm } from "@/shared/types"; import type { Project, CreateProjectForm } from "@/shared/types";
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { toast } from "sonner"; import { toast } from "sonner";
import CreateTaskDialog from "@/components/audit/CreateTaskDialog";
export default function Projects() { export default function Projects() {
const [projects, setProjects] = useState<Project[]>([]); const [projects, setProjects] = useState<Project[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [searchTerm, setSearchTerm] = useState(""); const [searchTerm, setSearchTerm] = useState("");
const [showCreateDialog, setShowCreateDialog] = useState(false); const [showCreateDialog, setShowCreateDialog] = useState(false);
const [showCreateTaskDialog, setShowCreateTaskDialog] = useState(false);
const [selectedProjectForTask, setSelectedProjectForTask] = useState<string>("");
const [uploadProgress, setUploadProgress] = useState(0); const [uploadProgress, setUploadProgress] = useState(0);
const [uploading, setUploading] = useState(false); const [uploading, setUploading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null); const fileInputRef = useRef<HTMLInputElement>(null);
@ -189,6 +192,19 @@ export default function Projects() {
return new Date(dateString).toLocaleDateString('zh-CN'); return new Date(dateString).toLocaleDateString('zh-CN');
}; };
const handleCreateTask = (projectId: string) => {
setSelectedProjectForTask(projectId);
setShowCreateTaskDialog(true);
};
const handleTaskCreated = () => {
toast.success("审计任务已创建", {
description: '因为网络和代码文件大小等因素审计时长通常至少需要1分钟请耐心等待...',
duration: 5000
});
// 任务创建后会自动跳转到项目详情页面
};
if (loading) { if (loading) {
return ( return (
<div className="flex items-center justify-center min-h-screen"> <div className="flex items-center justify-center min-h-screen">
@ -545,9 +561,13 @@ export default function Projects() {
</Button> </Button>
</Link> </Link>
<Button size="sm" className="btn-primary"> <Button
size="sm"
className="btn-primary"
onClick={() => handleCreateTask(project.id)}
>
<Shield className="w-4 h-4 mr-2" /> <Shield className="w-4 h-4 mr-2" />
</Button> </Button>
</div> </div>
</CardContent> </CardContent>
@ -638,6 +658,14 @@ export default function Projects() {
</Card> </Card>
</div> </div>
)} )}
{/* 创建任务对话框 */}
<CreateTaskDialog
open={showCreateTaskDialog}
onOpenChange={setShowCreateTaskDialog}
onTaskCreated={handleTaskCreated}
preselectedProjectId={selectedProjectForTask}
/>
</div> </div>
); );
} }