84 lines
2.7 KiB
TypeScript
84 lines
2.7 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|
import { createClient, createAdminClient } from '@/lib/supabase/server'
|
|
import { calculateScore } from '@/lib/utils'
|
|
|
|
export async function PATCH(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
try {
|
|
const supabase = await createClient()
|
|
const { data: { user }, error: authError } = await supabase.auth.getUser()
|
|
if (authError || !user) {
|
|
return NextResponse.json({ error: 'Non autorisé' }, { status: 401 })
|
|
}
|
|
|
|
const { id } = await params
|
|
const body = await request.json()
|
|
const { is_active } = body
|
|
|
|
const db = supabase as any
|
|
|
|
const { data: session, error } = await db
|
|
.from('sessions')
|
|
.update({ is_active })
|
|
.eq('id', id)
|
|
.eq('trainer_id', user.id)
|
|
.select('id, quiz_id')
|
|
.single()
|
|
|
|
if (error || !session) {
|
|
return NextResponse.json({ error: 'Session introuvable ou accès refusé' }, { status: 404 })
|
|
}
|
|
|
|
// Quand on ferme la session, forcer la complétion des étudiants encore en cours
|
|
if (!is_active) {
|
|
const admin = createAdminClient() as any
|
|
|
|
// Récupérer toutes les participations encore en cours
|
|
const { data: pending } = await admin
|
|
.from('student_participations')
|
|
.select('id')
|
|
.eq('session_id', id)
|
|
.eq('status', 'in_progress')
|
|
|
|
if (pending && pending.length > 0) {
|
|
// Compter le nombre total de questions du quiz pour calculer le score
|
|
const { count: totalQuestions } = await admin
|
|
.from('questions')
|
|
.select('id', { count: 'exact', head: true })
|
|
.eq('quiz_id', session.quiz_id)
|
|
|
|
const total = totalQuestions ?? 0
|
|
|
|
for (const participation of pending) {
|
|
// Récupérer les réponses données et vérifier lesquelles sont correctes
|
|
const { data: correctAnswers } = await admin
|
|
.from('student_answers')
|
|
.select('answer_id, answers!inner(is_correct)')
|
|
.eq('participation_id', participation.id)
|
|
.eq('answers.is_correct', true)
|
|
|
|
const correct = correctAnswers?.length ?? 0
|
|
const score = calculateScore(correct, total)
|
|
|
|
await admin
|
|
.from('student_participations')
|
|
.update({
|
|
status: 'completed',
|
|
score,
|
|
completed_at: new Date().toISOString(),
|
|
})
|
|
.eq('id', participation.id)
|
|
}
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({ success: true })
|
|
} catch (error) {
|
|
console.error('[sessions/toggle]', error)
|
|
return NextResponse.json({ error: 'Erreur serveur interne' }, { status: 500 })
|
|
}
|
|
}
|