實作完整分享、刪除、下載報告功能

This commit is contained in:
2025-09-24 00:01:37 +08:00
parent 69c9323038
commit 99ff9654d9
35 changed files with 4779 additions and 45 deletions

View File

@@ -0,0 +1,114 @@
import { NextRequest, NextResponse } from 'next/server';
import { EvaluationService, ProjectService, ProjectFileService, ProjectWebsiteService } from '@/lib/services/database';
import { unlink } from 'fs/promises';
import { join } from 'path';
export async function DELETE(
request: NextRequest,
{ params }: { params: { id: string } }
) {
try {
const evaluationId = parseInt(params.id);
if (isNaN(evaluationId)) {
return NextResponse.json(
{ success: false, error: '無效的評審ID' },
{ status: 400 }
);
}
console.log(`🗑️ 開始刪除評審記錄: ID=${evaluationId}`);
// 獲取評審記錄以找到對應的專案
const evaluation = await EvaluationService.findById(evaluationId);
if (!evaluation) {
return NextResponse.json(
{ success: false, error: '找不到指定的評審記錄' },
{ status: 404 }
);
}
const projectId = evaluation.project_id;
console.log(`📋 找到對應專案: ID=${projectId}`);
// 獲取專案信息
const project = await ProjectService.findById(projectId);
if (!project) {
return NextResponse.json(
{ success: false, error: '找不到對應的專案' },
{ status: 404 }
);
}
// 獲取專案文件列表
const projectFiles = await ProjectFileService.findByProjectId(projectId);
console.log(`📁 找到 ${projectFiles.length} 個專案文件`);
// 開始事務性刪除
try {
// 1. 刪除評審相關數據(這些會因為外鍵約束自動刪除)
// - evaluation_scores (CASCADE)
// - evaluation_feedback (CASCADE)
await EvaluationService.delete(evaluationId);
console.log(`✅ 已刪除評審記錄: ID=${evaluationId}`);
// 2. 刪除專案網站記錄
const projectWebsites = await ProjectWebsiteService.findByProjectId(projectId);
for (const website of projectWebsites) {
await ProjectWebsiteService.delete(website.id);
}
console.log(`✅ 已刪除 ${projectWebsites.length} 個專案網站記錄`);
// 3. 刪除專案文件記錄和實際文件
for (const file of projectFiles) {
try {
// 刪除實際文件
const filePath = join(process.cwd(), file.file_path);
await unlink(filePath);
console.log(`🗑️ 已刪除文件: ${file.original_name}`);
} catch (fileError) {
console.warn(`⚠️ 刪除文件失敗: ${file.original_name}`, fileError);
// 繼續刪除其他文件,不中斷整個流程
}
// 刪除文件記錄
await ProjectFileService.delete(file.id);
}
console.log(`✅ 已刪除 ${projectFiles.length} 個專案文件記錄`);
// 4. 刪除專案記錄
await ProjectService.delete(projectId);
console.log(`✅ 已刪除專案記錄: ID=${projectId}`);
console.log(`🎉 成功刪除評審報告: 專案=${project.title}`);
return NextResponse.json({
success: true,
message: '評審報告已成功刪除',
data: {
projectId: projectId,
projectTitle: project.title,
deletedFiles: projectFiles.length,
deletedWebsites: projectWebsites.length
}
});
} catch (deleteError) {
console.error('❌ 刪除過程中發生錯誤:', deleteError);
return NextResponse.json(
{
success: false,
error: '刪除過程中發生錯誤,請稍後再試'
},
{ status: 500 }
);
}
} catch (error) {
console.error('❌ 刪除評審記錄失敗:', error);
return NextResponse.json(
{ success: false, error: '刪除評審記錄失敗' },
{ status: 500 }
);
}
}