import { NextResponse } from 'next/server'; import supabase from '@/lib/db'; interface KelompokKeahlianLulusTepat { nama_kelompok: string; jumlah_lulusan_tercepat: number; } export async function GET(request: Request) { try { // Get all lulus students with their kelompok keahlian const { data, error } = await supabase .from('mahasiswa') .select(` kelompok_keahlian!inner( nama_kelompok ), semester, status_kuliah `) .eq('status_kuliah', 'Lulus'); if (error) { console.error('Error fetching kelompok keahlian lulus tepat:', error); return NextResponse.json( { error: 'Failed to fetch kelompok keahlian lulus tepat data' }, { status: 500, headers: { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=30', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, } ); } // Process data to calculate percentages const groupedData = data.reduce((acc, item: any) => { const nama_kelompok = item.kelompok_keahlian?.nama_kelompok; if (!nama_kelompok) return acc; if (!acc[nama_kelompok]) { acc[nama_kelompok] = { total_lulus: 0, lulus_tepat: 0 }; } acc[nama_kelompok].total_lulus += 1; // Check if lulus tepat waktu (semester <= 8) if (item.semester <= 8) { acc[nama_kelompok].lulus_tepat += 1; } return acc; }, {} as Record); // Convert to final format (without percentage) and sort by count DESC then name ASC const results: KelompokKeahlianLulusTepat[] = Object.entries(groupedData) .map(([nama_kelompok, counts]) => ({ nama_kelompok, jumlah_lulusan_tercepat: counts.lulus_tepat, })) .sort((a, b) => { if (b.jumlah_lulusan_tercepat !== a.jumlah_lulusan_tercepat) { return b.jumlah_lulusan_tercepat - a.jumlah_lulusan_tercepat; } return a.nama_kelompok.localeCompare(b.nama_kelompok); }); return NextResponse.json(results, { headers: { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=30', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, }); } catch (error) { console.error('Error fetching kelompok keahlian lulus tepat:', error); return NextResponse.json( { error: 'Failed to fetch kelompok keahlian lulus tepat data' }, { status: 500, headers: { 'Cache-Control': 'public, max-age=60, stale-while-revalidate=30', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }, } ); } }