實作綜合題型結果與資料庫整合
This commit is contained in:
108
app/api/test-results/combined/route.ts
Normal file
108
app/api/test-results/combined/route.ts
Normal file
@@ -0,0 +1,108 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { createCombinedTestResult } from '@/lib/database/models/combined_test_result'
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
let body: any
|
||||
try {
|
||||
body = await request.json()
|
||||
const {
|
||||
userId,
|
||||
logicScore,
|
||||
creativityScore,
|
||||
overallScore,
|
||||
level,
|
||||
description,
|
||||
logicBreakdown,
|
||||
creativityBreakdown,
|
||||
balanceScore,
|
||||
completedAt
|
||||
} = body
|
||||
|
||||
// 驗證必要欄位
|
||||
if (!userId || logicScore === undefined || creativityScore === undefined ||
|
||||
overallScore === undefined || !level || !completedAt) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: '缺少必要欄位' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log('🔄 開始建立綜合測試結果...')
|
||||
console.log('用戶ID:', userId)
|
||||
console.log('邏輯分數:', logicScore)
|
||||
console.log('創意分數:', creativityScore)
|
||||
console.log('總分:', overallScore)
|
||||
console.log('等級:', level)
|
||||
|
||||
// 建立綜合測試結果
|
||||
const testResult = await createCombinedTestResult({
|
||||
user_id: userId,
|
||||
logic_score: logicScore,
|
||||
creativity_score: creativityScore,
|
||||
overall_score: overallScore,
|
||||
level: level,
|
||||
description: description || null,
|
||||
logic_breakdown: logicBreakdown || null,
|
||||
creativity_breakdown: creativityBreakdown || null,
|
||||
balance_score: balanceScore || 0,
|
||||
completed_at: completedAt
|
||||
})
|
||||
|
||||
if (!testResult) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: '建立綜合測試結果失敗' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
|
||||
console.log('✅ 綜合測試結果建立成功,ID:', testResult.id)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
testResult
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('上傳綜合測試結果失敗:', error)
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
error: '伺服器錯誤',
|
||||
details: error instanceof Error ? error.message : '未知錯誤'
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const userId = searchParams.get('userId')
|
||||
|
||||
if (!userId) {
|
||||
return NextResponse.json(
|
||||
{ success: false, error: '缺少用戶ID' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
// 獲取用戶的綜合測試結果
|
||||
const { getCombinedTestResultsByUserId } = await import('@/lib/database/models/combined_test_result')
|
||||
const results = await getCombinedTestResultsByUserId(userId)
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: results
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
console.error('獲取綜合測試結果失敗:', error)
|
||||
return NextResponse.json(
|
||||
{ success: false, error: '伺服器錯誤' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
@@ -1,5 +1,7 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { getTestResultsByUserId } from '@/lib/database/models/test_result'
|
||||
import { getTestResultsByUserId, TestResult as DBTestResult } from '@/lib/database/models/test_result'
|
||||
import { getCombinedTestResultsByUserId, CombinedTestResult } from '@/lib/database/models/combined_test_result'
|
||||
import { findUserById } from '@/lib/database/models/user'
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
@@ -13,38 +15,21 @@ export async function GET(request: NextRequest) {
|
||||
)
|
||||
}
|
||||
|
||||
// 獲取用戶的所有測試結果
|
||||
const allResults = await getTestResultsByUserId(userId)
|
||||
// 獲取邏輯和創意測試結果
|
||||
const testResults = await getTestResultsByUserId(userId)
|
||||
|
||||
if (allResults.length === 0) {
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
data: {
|
||||
results: [],
|
||||
stats: {
|
||||
totalTests: 0,
|
||||
averageScore: 0,
|
||||
bestScore: 0,
|
||||
lastTestDate: null,
|
||||
testCounts: {
|
||||
logic: 0,
|
||||
creative: 0,
|
||||
combined: 0
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
// 獲取綜合測試結果
|
||||
const combinedResults = await getCombinedTestResultsByUserId(userId)
|
||||
|
||||
// 按測試類型分組,只保留每種類型的最新結果
|
||||
const latestResults = {
|
||||
logic: allResults.filter(r => r.test_type === 'logic').sort((a, b) =>
|
||||
logic: testResults.filter(r => r.test_type === 'logic').sort((a, b) =>
|
||||
new Date(b.completed_at).getTime() - new Date(a.completed_at).getTime()
|
||||
)[0],
|
||||
creative: allResults.filter(r => r.test_type === 'creative').sort((a, b) =>
|
||||
creative: testResults.filter(r => r.test_type === 'creative').sort((a, b) =>
|
||||
new Date(b.completed_at).getTime() - new Date(a.completed_at).getTime()
|
||||
)[0],
|
||||
combined: allResults.filter(r => r.test_type === 'combined').sort((a, b) =>
|
||||
combined: combinedResults.sort((a, b) =>
|
||||
new Date(b.completed_at).getTime() - new Date(a.completed_at).getTime()
|
||||
)[0]
|
||||
}
|
||||
@@ -59,7 +44,10 @@ export async function GET(request: NextRequest) {
|
||||
// 平均分數:基於每種類型測試的最新分數計算
|
||||
const latestScores = Object.values(latestResults)
|
||||
.filter(result => result !== undefined)
|
||||
.map(result => result.score)
|
||||
.map(result => {
|
||||
// 綜合測試結果使用 overall_score,其他使用 score
|
||||
return 'overall_score' in result ? result.overall_score : result.score
|
||||
})
|
||||
|
||||
const averageScore = latestScores.length > 0
|
||||
? Math.round(latestScores.reduce((sum, score) => sum + score, 0) / latestScores.length)
|
||||
@@ -69,32 +57,58 @@ export async function GET(request: NextRequest) {
|
||||
const bestScore = latestScores.length > 0 ? Math.max(...latestScores) : 0
|
||||
|
||||
// 最近測試日期:基於所有測試結果
|
||||
const lastTestDate = allResults.length > 0
|
||||
? allResults.sort((a, b) =>
|
||||
new Date(b.completed_at).getTime() - new Date(a.completed_at).getTime()
|
||||
)[0]?.completed_at || null
|
||||
: null
|
||||
const allTestDates = [
|
||||
...testResults.map(r => r.completed_at),
|
||||
...combinedResults.map(r => r.completed_at)
|
||||
].sort((a, b) => new Date(b).getTime() - new Date(a).getTime())
|
||||
|
||||
const lastTestDate = allTestDates.length > 0 ? allTestDates[0] : null
|
||||
|
||||
// 計算各類型測試次數
|
||||
const testCounts = {
|
||||
logic: allResults.filter(r => r.test_type === 'logic').length,
|
||||
creative: allResults.filter(r => r.test_type === 'creative').length,
|
||||
combined: allResults.filter(r => r.test_type === 'combined').length
|
||||
logic: testResults.filter(r => r.test_type === 'logic').length,
|
||||
creative: testResults.filter(r => r.test_type === 'creative').length,
|
||||
combined: combinedResults.length
|
||||
}
|
||||
|
||||
// 轉換為前端需要的格式
|
||||
const formattedResults = results.map(result => ({
|
||||
type: result.test_type,
|
||||
score: result.score,
|
||||
completedAt: result.completed_at,
|
||||
testCount: testCounts[result.test_type as keyof typeof testCounts],
|
||||
details: {
|
||||
id: result.id,
|
||||
total_questions: result.total_questions,
|
||||
correct_answers: result.correct_answers,
|
||||
created_at: result.created_at
|
||||
const formattedResults = results.map(result => {
|
||||
// 檢查是否為綜合測試結果
|
||||
if ('overall_score' in result) {
|
||||
// 綜合測試結果
|
||||
const combinedResult = result as CombinedTestResult
|
||||
return {
|
||||
type: 'combined' as const,
|
||||
score: combinedResult.overall_score,
|
||||
completedAt: combinedResult.completed_at,
|
||||
testCount: testCounts.combined,
|
||||
details: {
|
||||
id: combinedResult.id,
|
||||
logic_score: combinedResult.logic_score,
|
||||
creativity_score: combinedResult.creativity_score,
|
||||
level: combinedResult.level,
|
||||
description: combinedResult.description,
|
||||
balance_score: combinedResult.balance_score,
|
||||
created_at: combinedResult.created_at
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 邏輯或創意測試結果
|
||||
const testResult = result as DBTestResult
|
||||
return {
|
||||
type: testResult.test_type,
|
||||
score: testResult.score,
|
||||
completedAt: testResult.completed_at,
|
||||
testCount: testCounts[testResult.test_type as keyof typeof testCounts],
|
||||
details: {
|
||||
id: testResult.id,
|
||||
total_questions: testResult.total_questions,
|
||||
correct_answers: testResult.correct_answers,
|
||||
created_at: testResult.created_at
|
||||
}
|
||||
}
|
||||
}
|
||||
}))
|
||||
})
|
||||
|
||||
// 按完成時間排序(最新的在前)
|
||||
formattedResults.sort((a, b) => new Date(b.completedAt).getTime() - new Date(a.completedAt).getTime())
|
||||
|
Reference in New Issue
Block a user