again n again

This commit is contained in:
Randa Firman Putra
2025-11-23 20:32:04 +07:00
parent c77321bc8a
commit 82bec8eecc
12 changed files with 2427 additions and 0 deletions

View File

@@ -0,0 +1,359 @@
'use client';
import { useEffect, useState, useMemo } from 'react';
import dynamic from 'next/dynamic';
import { ApexOptions } from 'apexcharts';
import { useTheme } from 'next-themes';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ExternalLink } from "lucide-react";
import Link from "next/link";
// Dynamically import ApexCharts to avoid SSR issues
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
interface KategoriIPKData {
tahun_angkatan: number;
kategori_ipk: string;
jumlah: number;
}
interface DistribusiIPKChartProps {
selectedYear?: string;
height?: string;
showDetailButton?: boolean;
}
export default function DistribusiIPKChart({
selectedYear = 'all',
height = "h-[300px] sm:h-[300px] md:h-[300px]",
showDetailButton = true
}: DistribusiIPKChartProps) {
const { theme } = useTheme();
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<KategoriIPKData[]>([]);
const [series, setSeries] = useState<ApexAxisChartSeries>([]);
// Get unique tahun angkatan and sort them
const tahunAngkatan = useMemo(() => {
return [...new Set(data.map(item => item.tahun_angkatan))].sort((a, b) => a - b);
}, [data]);
const chartOptions: ApexOptions = useMemo(() => ({
chart: {
type: 'bar',
stacked: true,
toolbar: {
show: true,
tools: {
download: true,
selection: true,
zoom: true,
zoomin: true,
zoomout: true,
pan: true,
reset: true
},
},
background: theme === 'dark' ? '#0F172B' : '#fff',
},
plotOptions: {
bar: {
horizontal: true,
barHeight: '70%',
},
},
dataLabels: {
enabled: true,
formatter: function (val: number, opts: any) {
const seriesIndex = opts.seriesIndex;
const dataPointIndex = opts.dataPointIndex;
// Hitung total untuk tahun angkatan ini
const allSeries = opts.w.config.series;
let totalForYear = 0;
allSeries.forEach((series: any) => {
totalForYear += series.data[dataPointIndex] || 0;
});
if (totalForYear === 0 || val === 0) return '0%';
const percentage = ((val / totalForYear) * 100).toFixed(0);
return percentage + '%';
},
style: {
fontSize: '12px',
colors: [theme === 'dark' ? '#fff' : '#000']
}
},
stroke: {
show: true,
width: 2,
colors: ['transparent'],
},
xaxis: {
categories: tahunAngkatan,
title: {
text: 'Jumlah Mahasiswa',
style: {
fontSize: '14px',
fontWeight: 'bold',
color: theme === 'dark' ? '#fff' : '#000'
}
},
labels: {
style: {
fontSize: '12px',
colors: theme === 'dark' ? '#fff' : '#000'
}
},
min: 0,
tickAmount: 5
},
yaxis: {
title: {
text: 'Tahun Angkatan',
style: {
fontSize: '14px',
fontWeight: 'bold',
color: theme === 'dark' ? '#fff' : '#000'
}
},
labels: {
style: {
fontSize: '12px',
colors: theme === 'dark' ? '#fff' : '#000'
}
}
},
fill: {
opacity: 1,
},
legend: {
position: 'top',
fontSize: '11px',
markers: {
size: 8,
},
itemMargin: {
horizontal: 12,
vertical: 8,
},
labels: {
colors: theme === 'dark' ? '#fff' : '#000',
},
formatter: function(seriesName: string) {
return seriesName;
}
},
colors: ['#008FFB', '#00E396', '#FEB019', '#EF4444'], // Sangat Baik, Baik, Cukup, Kurang
tooltip: {
theme: theme === 'dark' ? 'dark' : 'light',
shared: true,
intersect: false,
custom: function({ series, seriesIndex, dataPointIndex, w }: any) {
const tahun = w.globals.labels[dataPointIndex];
const isDark = theme === 'dark';
// Hitung total untuk tahun ini
let total = 0;
series.forEach((seriesData: number[]) => {
total += seriesData[dataPointIndex] || 0;
});
const kategoriLabels = [
'4.00 - 3.00 Sangat Baik',
'2.99 - 2.50 Baik',
'2.49 - 2.00 Cukup',
'< 2.00 Kurang'
];
const kategoriColors = ['#008FFB', '#00E396', '#FEB019', '#EF4444'];
let tooltipContent = `
<div style="
padding: 12px 16px;
background: ${isDark ? 'rgba(30, 41, 59, 0.95)' : 'rgba(255, 255, 255, 0.95)'};
backdrop-filter: blur(10px);
border: none;
border-radius: 12px;
box-shadow: 0 8px 32px ${isDark ? 'rgba(0, 0, 0, 0.3)' : 'rgba(0, 0, 0, 0.1)'};
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
min-width: 200px;
">
<div style="
font-size: 13px;
font-weight: 600;
color: ${isDark ? '#f1f5f9' : '#1f2937'};
margin-bottom: 8px;
text-align: center;
">Angkatan ${tahun}</div>`;
// Tambahkan setiap kategori
series.forEach((seriesData: number[], index: number) => {
const value = seriesData[dataPointIndex] || 0;
if (value > 0) {
const percentage = total > 0 ? ((value / total) * 100).toFixed(1) : '0';
tooltipContent += `
<div style="display: flex; align-items: center; margin-bottom: 4px;">
<div style="width: 8px; height: 8px; background: ${kategoriColors[index]}; border-radius: 50%; margin-right: 8px;"></div>
<span style="font-size: 12px; color: ${isDark ? '#cbd5e1' : '#374151'};">${kategoriLabels[index]}</span>
<span style="font-size: 12px; font-weight: 600; color: ${isDark ? '#f1f5f9' : '#1f2937'}; margin-left: auto;">${value} (${percentage}%)</span>
</div>`;
}
});
// Tambahkan total
tooltipContent += `
<div style="
border-top: 1px solid ${isDark ? '#475569' : '#e5e7eb'};
margin-top: 8px;
padding-top: 8px;
display: flex;
align-items: center;
">
<div style="width: 8px; height: 8px; background: #6366f1; border-radius: 50%; margin-right: 8px;"></div>
<span style="font-size: 12px; font-weight: 600; color: ${isDark ? '#f1f5f9' : '#1f2937'};">Total</span>
<span style="font-size: 13px; font-weight: 700; color: #6366f1; margin-left: auto;">${total}</span>
</div>
</div>
`;
return tooltipContent;
}
}
}), [theme, tahunAngkatan]);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const url = selectedYear === 'all'
? '/api/mahasiswa/kategoriipk'
: `/api/mahasiswa/kategoriipk?tahun_angkatan=${selectedYear}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.status} ${response.statusText}`);
}
const result = await response.json();
if (!Array.isArray(result)) {
throw new Error('Invalid data format received from server');
}
setData(result);
// Process data to create series
const tahunAngkatan = [...new Set(result.map(item => item.tahun_angkatan))].sort((a, b) => a - b);
const kategori = ['Sangat Baik', 'Baik', 'Cukup', 'Kurang'];
// Label lengkap dengan angka IPK untuk ditampilkan di legend
const kategoriLabels = [
'4.00 - 3.00 Sangat Baik',
'2.99 - 2.50 Baik',
'2.49 - 2.00 Cukup',
'< 2.00 Kurang'
];
// Buat series data dengan label lengkap (angka IPK + kategori)
const seriesData = kategori.map((kat, index) => ({
name: kategoriLabels[index], // Label ini akan ditampilkan di legend
data: tahunAngkatan.map(tahun => {
const item = result.find(d => d.tahun_angkatan === tahun && d.kategori_ipk === kat);
return item ? item.jumlah : 0;
}),
}));
setSeries(seriesData);
} catch (err) {
console.error('Error in fetchData:', err);
setError(err instanceof Error ? err.message : 'An error occurred while fetching data');
} finally {
setLoading(false);
}
};
fetchData();
}, [selectedYear]);
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Memuat data distribusi IPK...
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500 dark:text-red-400">
Error: {error}
</CardTitle>
</CardHeader>
</Card>
);
}
if (data.length === 0) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Distribusi IPK
{selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Tidak ada data yang tersedia untuk periode ini.
</p>
</CardContent>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle className="text-xl font-bold dark:text-white">
Distribusi IPK
{selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
</CardTitle>
{showDetailButton && (
<Link href="/detail/kategori-ipk" target="_blank">
<Button variant="outline" size="sm" className="flex items-center gap-1 dark:text-white">
<ExternalLink className="size-3" />
Detail
</Button>
</Link>
)}
</div>
</CardHeader>
<CardContent>
<div className={`${height} w-full max-w-5xl mx-auto`}>
{typeof window !== 'undefined' && (
<Chart
options={chartOptions}
series={series}
type="bar"
height="100%"
width="100%"
/>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,222 @@
'use client';
import { useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { ApexOptions } from 'apexcharts';
import { useTheme } from 'next-themes';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
interface KategoriIPKPerAngkatanData {
kategori_ipk: string;
jumlah: number;
}
interface Props {
selectedYear: string;
}
export default function DistribusiIPKChartPerangkatan({ selectedYear }: Props) {
const { theme } = useTheme();
const [data, setData] = useState<KategoriIPKPerAngkatanData[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// Label lengkap dengan angka IPK untuk ditampilkan di legend
const kategoriLabelsMap: { [key: string]: string } = {
'Sangat Baik': '4.00 - 3.00 Sangat Baik',
'Baik': '2.99 - 2.50 Baik',
'Cukup': '2.49 - 2.00 Cukup',
'Kurang': '< 2.00 Kurang'
};
// Urutan kategori untuk sorting
const kategoriOrder = ['Sangat Baik', 'Baik', 'Cukup', 'Kurang'];
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(
`/api/mahasiswa/kategoriipk?tahun_angkatan=${selectedYear}`
);
if (!response.ok) {
throw new Error('Failed to fetch data');
}
const result = await response.json();
// Filter data for selected year and group by kategori_ipk
const yearData = result.filter((item: any) =>
item.tahun_angkatan.toString() === selectedYear
);
// Group by kategori_ipk and sum jumlah
const groupedData = yearData.reduce((acc: { [key: string]: number }, item: any) => {
const kategori = item.kategori_ipk || 'Tidak Diketahui';
acc[kategori] = (acc[kategori] || 0) + item.jumlah;
return acc;
}, {});
// Convert to array format
const chartData = Object.entries(groupedData).map(([kategori_ipk, jumlah]) => ({
kategori_ipk,
jumlah: jumlah as number
}));
// Sort by kategori order
const sortedData = chartData.sort((a, b) => {
const indexA = kategoriOrder.indexOf(a.kategori_ipk);
const indexB = kategoriOrder.indexOf(b.kategori_ipk);
return indexA - indexB;
});
setData(sortedData);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
};
fetchData();
}, [selectedYear]);
// Prepare data for pie chart
const series = data.map(item => item.jumlah);
const labels = data.map(item => kategoriLabelsMap[item.kategori_ipk] || item.kategori_ipk);
const chartOptions: ApexOptions = {
chart: {
type: 'pie',
toolbar: {
show: true,
},
background: theme === 'dark' ? '#0F172B' : '#fff',
},
labels: labels,
dataLabels: {
enabled: true,
formatter: function (val: number) {
return `${val.toFixed(0)}%`;
},
style: {
fontSize: '14px',
fontFamily: 'Inter, sans-serif',
fontWeight: '500'
}
},
legend: {
position: 'bottom',
fontSize: '11px',
markers: {
size: 8,
},
itemMargin: {
horizontal: 10,
vertical: 5,
},
labels: {
colors: theme === 'dark' ? '#fff' : '#000'
},
formatter: function(seriesName: string) {
return seriesName;
}
},
colors: [
'#008FFB', // Sangat Baik - Blue
'#00E396', // Baik - Green
'#FEB019', // Cukup - Orange
'#EF4444', // Kurang - Red
],
tooltip: {
theme: theme === 'dark' ? 'dark' : 'light',
y: {
formatter: function (val: number) {
return val + ' mahasiswa';
}
}
},
plotOptions: {
pie: {
donut: {
size: '0%',
},
offsetY: 0,
},
},
states: {
hover: {
filter: {
type: 'darken',
},
},
},
};
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Memuat data distribusi IPK...
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500">
Error: {error}
</CardTitle>
</CardHeader>
</Card>
);
}
if (data.length === 0) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Distribusi IPK
{selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Tidak ada data yang tersedia untuk periode ini.
</p>
</CardContent>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Distribusi IPK
{selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
</CardTitle>
</CardHeader>
<CardContent>
<div className="h-[300px] sm:h-[300px] md:h-[300px] w-full max-w-5xl mx-auto">
{typeof window !== 'undefined' && (
<Chart
options={chartOptions}
series={series}
type="pie"
height="100%"
width="100%"
/>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,255 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import dynamic from 'next/dynamic';
import { ApexOptions } from 'apexcharts';
import { useTheme } from 'next-themes';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { ExternalLink } from 'lucide-react';
import Link from 'next/link';
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
interface TerancamDOResponse {
tahun_angkatan: number;
jumlah_mahasiswa_do: number;
}
interface TerancamDOChartProps {
selectedYear?: string;
height?: string;
showDetailButton?: boolean;
}
export default function TerancamDOChart({
selectedYear = 'all',
height = 'h-[300px] sm:h-[320px]',
showDetailButton = true,
}: TerancamDOChartProps) {
const { theme } = useTheme();
const [data, setData] = useState<TerancamDOResponse[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const url =
selectedYear === 'all'
? '/api/mahasiswa/terancamdo'
: `/api/mahasiswa/terancamdo?tahun_angkatan=${selectedYear}`;
const response = await fetch(url);
if (!response.ok) {
const errorText = await response.text();
throw new Error(
`Failed to fetch data: ${response.status} ${response.statusText} - ${errorText}`,
);
}
const result = await response.json();
if (!Array.isArray(result)) {
throw new Error('Invalid data format received from server');
}
const sorted = [...result].sort(
(a, b) => a.tahun_angkatan - b.tahun_angkatan,
);
setData(sorted);
} catch (err) {
console.error('Error fetching terancam DO data:', err);
setError(
err instanceof Error ? err.message : 'Terjadi kesalahan saat memuat data',
);
} finally {
setLoading(false);
}
};
fetchData();
}, [selectedYear]);
const categories = useMemo(
() => data.map((item) => item.tahun_angkatan),
[data],
);
const series = useMemo(
() => [
{
name: 'Mahasiswa Terancam DO',
data: data.map((item) => item.jumlah_mahasiswa_do),
},
],
[data],
);
const chartOptions: ApexOptions = {
chart: {
type: 'bar',
toolbar: {
show: true,
},
background: 'transparent',
},
plotOptions: {
bar: {
horizontal: false,
columnWidth: '55%',
borderRadius: 2,
},
},
dataLabels: {
enabled: true,
formatter: (val: number) => val.toString(),
style: {
colors: [theme === 'dark' ? '#f9fafb' : '#1f2937'],
},
},
stroke: {
show: true,
width: 2,
colors: ['transparent'],
},
xaxis: {
categories,
title: {
text: 'Tahun Angkatan',
style: {
fontSize: '14px',
fontWeight: 'bold',
color: theme === 'dark' ? '#f9fafb' : '#1f2937',
},
},
labels: {
style: {
colors: theme === 'dark' ? '#e5e7eb' : '#4b5563',
},
},
},
yaxis: {
title: {
text: 'Jumlah Mahasiswa',
style: {
fontSize: '14px',
fontWeight: 'bold',
color: theme === 'dark' ? '#f9fafb' : '#1f2937',
},
},
labels: {
style: {
colors: theme === 'dark' ? '#e5e7eb' : '#4b5563',
},
},
min: 0,
forceNiceScale: true,
},
legend: {
show: false,
},
grid: {
borderColor: theme === 'dark' ? '#374151' : '#e5e7eb',
strokeDashArray: 4,
padding: {
top: 20,
right: 20,
left: 10,
},
},
colors: ['#ef4444'],
tooltip: {
theme: theme === 'dark' ? 'dark' : 'light',
y: {
formatter: (val: number) => `${val} mahasiswa`,
},
},
};
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Memuat data terancam DO...
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg border border-red-500/40">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500">
Gagal memuat data
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-red-600 dark:text-red-400 whitespace-pre-line">
{error}
</p>
</CardContent>
</Card>
);
}
if (!data.length) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Mahasiswa Terancam DO
</CardTitle>
</CardHeader>
<CardContent>
<p className="text-sm text-muted-foreground">
Tidak ada mahasiswa yang teridentifikasi terancam DO pada periode ini.
</p>
</CardContent>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<div className="flex justify-between items-center">
<CardTitle className="text-xl font-bold dark:text-white">
Mahasiswa Terancam Drop Out
{selectedYear !== 'all' ? ` Angkatan ${selectedYear}` : ''}
</CardTitle>
{showDetailButton && (
<Link href="/detail/terancam-do" target="_blank">
<Button variant="outline" size="sm" className="flex items-center gap-1 dark:text-white">
<ExternalLink className="size-3" />
Detail
</Button>
</Link>
)}
</div>
</CardHeader>
<CardContent>
<div className={`${height} w-full`}>
{typeof window !== 'undefined' && (
<Chart
options={chartOptions}
series={series}
type="bar"
height="100%"
width="100%"
/>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -0,0 +1,451 @@
'use client';
import { useEffect, useState } from 'react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Loader2, Trophy, Medal, Award } from "lucide-react";
interface MahasiswaKategoriIPK {
nim: string;
nama: string;
tahun_angkatan: number;
ipk: number;
}
interface TabelKategoriIPKMahasiswaProps {
selectedYear: string;
}
export default function TabelKategoriIPKMahasiswa({ selectedYear }: TabelKategoriIPKMahasiswaProps) {
const [mahasiswaData, setMahasiswaData] = useState<MahasiswaKategoriIPK[]>([]);
const [filteredData, setFilteredData] = useState<MahasiswaKategoriIPK[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedKategori, setSelectedKategori] = useState<string>("all");
// State for pagination
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [paginatedData, setPaginatedData] = useState<MahasiswaKategoriIPK[]>([]);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
// Fetch data dari API dengan filter tahun angkatan dan kategori IPK
const urlParams = new URLSearchParams();
if (selectedYear !== 'all') {
urlParams.append('tahun_angkatan', selectedYear);
}
if (selectedKategori !== 'all') {
urlParams.append('kategori_ipk', selectedKategori);
}
const url = urlParams.toString()
? `/api/tabeldetail/kategori-ipk?${urlParams.toString()}`
: '/api/tabeldetail/kategori-ipk';
const response = await fetch(url, {
cache: 'no-store',
});
if (!response.ok) {
throw new Error('Failed to fetch mahasiswa kategori IPK data');
}
const data = await response.json();
setMahasiswaData(data);
setFilteredData(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Terjadi kesalahan');
console.error('Error fetching data:', err);
} finally {
setLoading(false);
}
};
fetchData();
setCurrentPage(1); // Reset to first page when filter changes
}, [selectedYear, selectedKategori]);
// Update paginated data when filtered data or pagination settings change
useEffect(() => {
paginateData();
}, [filteredData, currentPage, pageSize]);
// Paginate data
const paginateData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
setPaginatedData(filteredData.slice(startIndex, endIndex));
};
// Get total number of pages
const getTotalPages = () => {
return Math.ceil(filteredData.length / pageSize);
};
// Handle page change
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
// Handle page size change
const handlePageSizeChange = (size: string) => {
setPageSize(Number(size));
setCurrentPage(1); // Reset to first page when changing page size
};
// Handle kategori change
const handleKategoriChange = (kategori: string) => {
setSelectedKategori(kategori);
};
// Fungsi untuk mendapatkan icon berdasarkan ranking
const getRankingIcon = (index: number) => {
if (index === 0) return <Trophy className="h-4 w-4 text-yellow-500" />;
if (index === 1) return <Medal className="h-4 w-4 text-gray-400" />;
if (index === 2) return <Award className="h-4 w-4 text-amber-600" />;
return null;
};
// Fungsi untuk mendapatkan kategori IPK dari nilai IPK
const getKategoriIPKFromValue = (ipk: number): string => {
if (ipk >= 3.00 && ipk <= 4.00) {
return 'Sangat Baik';
} else if (ipk >= 2.50 && ipk < 3.00) {
return 'Baik';
} else if (ipk >= 2.00 && ipk < 2.50) {
return 'Cukup';
} else if (ipk < 2.00) {
return 'Kurang';
}
return 'Tidak Terkategorikan';
};
// Hitung statistik IPK berdasarkan filtered data
const ipkStats = {
highest: filteredData.length > 0 ? Math.max(...filteredData.map(m => m.ipk)) : 0,
lowest: filteredData.length > 0 ? Math.min(...filteredData.map(m => m.ipk)) : 0,
average: filteredData.length > 0 ?
filteredData.reduce((sum, m) => sum + m.ipk, 0) / filteredData.length : 0,
total: filteredData.length
};
// Hitung jumlah per kategori
const kategoriStats = filteredData.reduce((acc, mahasiswa) => {
const kategori = getKategoriIPKFromValue(mahasiswa.ipk);
acc[kategori] = (acc[kategori] || 0) + 1;
return acc;
}, {} as Record<string, number>);
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
<div className="flex items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
Loading...
</div>
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500 dark:text-red-400">
Error: {error}
</CardTitle>
</CardHeader>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
Tabel Kategori IPK Mahasiswa {selectedYear !== 'all' ? `Angkatan ${selectedYear}` : 'Semua Angkatan'}
</CardTitle>
{/* Filter Kategori IPK */}
<div className="flex items-center gap-2 mt-4">
<span className="text-sm dark:text-white">Filter Kategori IPK:</span>
<Select value={selectedKategori} onValueChange={handleKategoriChange}>
<SelectTrigger className="w-[220px]">
<SelectValue placeholder="Pilih Kategori IPK" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">Semua Kategori</SelectItem>
<SelectItem value="Sangat Baik">4.00 - 3.00 Sangat Baik</SelectItem>
<SelectItem value="Baik">2.99 - 2.50 Baik</SelectItem>
<SelectItem value="Cukup">2.49 - 2.00 Cukup</SelectItem>
<SelectItem value="Kurang">&lt; 2.00 Kurang</SelectItem>
</SelectContent>
</Select>
</div>
{/* Tampilkan ringkasan statistik IPK */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-2 mt-4">
<div className="px-3 py-2 rounded-lg bg-green-50 dark:bg-green-900/20">
<div className="text-xs text-green-600 dark:text-green-400">IPK Tertinggi</div>
<div className="font-bold text-green-800 dark:text-green-300">{ipkStats.highest > 0 ? ipkStats.highest.toFixed(2) : '-'}</div>
</div>
<div className="px-3 py-2 rounded-lg bg-red-50 dark:bg-red-900/20">
<div className="text-xs text-red-600 dark:text-red-400">IPK Terendah</div>
<div className="font-bold text-red-800 dark:text-red-300">{ipkStats.lowest > 0 ? ipkStats.lowest.toFixed(2) : '-'}</div>
</div>
<div className="px-3 py-2 rounded-lg bg-blue-50 dark:bg-blue-900/20">
<div className="text-xs text-blue-600 dark:text-blue-400">Rata-rata IPK</div>
<div className="font-bold text-blue-800 dark:text-blue-300">{ipkStats.average > 0 ? ipkStats.average.toFixed(2) : '-'}</div>
</div>
<div className="px-3 py-2 rounded-lg bg-gray-50 dark:bg-gray-800">
<div className="text-xs text-gray-600 dark:text-gray-400">Total Mahasiswa</div>
<div className="font-bold text-gray-800 dark:text-gray-200">{ipkStats.total}</div>
</div>
</div>
{/* Tampilkan ringkasan per kategori */}
{selectedKategori === 'all' && Object.keys(kategoriStats).length > 0 && (
<div className="flex flex-wrap gap-2 mt-4">
{Object.entries(kategoriStats)
.sort(([a], [b]) => {
const order = ['Sangat Baik', 'Baik', 'Cukup', 'Kurang'];
return order.indexOf(a) - order.indexOf(b);
})
.map(([kategori, count]) => (
<span
key={kategori}
className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
>
{kategori}: {count}
</span>
))}
</div>
)}
</CardHeader>
<CardContent>
{/* Show entries selector */}
<div className="flex items-center gap-2 mb-4">
<span className="text-sm">Show</span>
<Select
value={pageSize.toString()}
onValueChange={handlePageSizeChange}
>
<SelectTrigger className="w-[80px]">
<SelectValue placeholder={pageSize.toString()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="25">25</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
<span className="text-sm">entries</span>
</div>
<div className="border rounded-md overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50 dark:bg-slate-800">
<TableHead className="font-semibold text-center">Ranking</TableHead>
<TableHead className="font-semibold">NIM</TableHead>
<TableHead className="font-semibold">Nama Mahasiswa</TableHead>
<TableHead className="font-semibold text-center">Tahun Angkatan</TableHead>
<TableHead className="font-semibold text-center">IPK</TableHead>
<TableHead className="font-semibold text-center">Kategori IPK</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedData.length === 0 ? (
<TableRow>
<TableCell colSpan={6} className="text-center py-8 text-muted-foreground">
Tidak ada data yang tersedia
</TableCell>
</TableRow>
) : (
paginatedData.map((mahasiswa, index) => {
const globalIndex = (currentPage - 1) * pageSize + index;
const kategoriIPK = getKategoriIPKFromValue(mahasiswa.ipk);
return (
<TableRow
key={`${mahasiswa.nim}-${mahasiswa.tahun_angkatan}`}
className={index % 2 === 0 ? "bg-white dark:bg-slate-900" : "bg-gray-50/50 dark:bg-slate-800/50"}
>
<TableCell className="text-center font-medium dark:text-white">
<div className="flex items-center justify-center gap-1">
{getRankingIcon(globalIndex)}
<span>{globalIndex + 1}</span>
</div>
</TableCell>
<TableCell className="font-medium dark:text-white">
{mahasiswa.nim}
</TableCell>
<TableCell className="dark:text-white">
{mahasiswa.nama}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.tahun_angkatan}
</TableCell>
<TableCell className="text-center font-medium dark:text-white">
{mahasiswa.ipk.toFixed(2)}
</TableCell>
<TableCell className="text-center dark:text-white">
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
kategoriIPK === 'Sangat Baik' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/30 dark:text-blue-300' :
kategoriIPK === 'Baik' ? 'bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-300' :
kategoriIPK === 'Cukup' ? 'bg-yellow-100 text-yellow-800 dark:bg-yellow-900/30 dark:text-yellow-300' :
'bg-red-100 text-red-800 dark:bg-red-900/30 dark:text-red-300'
}`}>
{kategoriIPK}
</span>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</div>
{/* Pagination info and controls */}
{!loading && !error && filteredData.length > 0 && (
<div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4">
<div className="text-sm text-muted-foreground">
Showing {getDisplayRange().start} to {getDisplayRange().end} of {filteredData.length} entries
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
{renderPaginationItems()}
<PaginationItem>
<PaginationNext
onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)}
</CardContent>
</Card>
);
// Calculate the range of entries being displayed
function getDisplayRange() {
if (filteredData.length === 0) return { start: 0, end: 0 };
const start = (currentPage - 1) * pageSize + 1;
const end = Math.min(currentPage * pageSize, filteredData.length);
return { start, end };
}
// Generate pagination items
function renderPaginationItems() {
const totalPages = getTotalPages();
const items = [];
// Always show first page
items.push(
<PaginationItem key="first">
<PaginationLink
isActive={currentPage === 1}
onClick={() => handlePageChange(1)}
className="cursor-pointer"
>
1
</PaginationLink>
</PaginationItem>
);
// Show ellipsis if needed
if (currentPage > 3) {
items.push(
<PaginationItem key="ellipsis-start">
<PaginationEllipsis />
</PaginationItem>
);
}
// Show pages around current page
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
if (i === 1 || i === totalPages) continue; // Skip first and last pages as they're always shown
items.push(
<PaginationItem key={i}>
<PaginationLink
isActive={currentPage === i}
onClick={() => handlePageChange(i)}
className="cursor-pointer"
>
{i}
</PaginationLink>
</PaginationItem>
);
}
// Show ellipsis if needed
if (currentPage < totalPages - 2) {
items.push(
<PaginationItem key="ellipsis-end">
<PaginationEllipsis />
</PaginationItem>
);
}
// Always show last page if there's more than one page
if (totalPages > 1) {
items.push(
<PaginationItem key="last">
<PaginationLink
isActive={currentPage === totalPages}
onClick={() => handlePageChange(totalPages)}
className="cursor-pointer"
>
{totalPages}
</PaginationLink>
</PaginationItem>
);
}
return items;
}
}

View File

@@ -0,0 +1,379 @@
'use client';
import { useEffect, useState } from 'react';
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow
} from "@/components/ui/table";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue
} from "@/components/ui/select";
import {
Pagination,
PaginationContent,
PaginationEllipsis,
PaginationItem,
PaginationLink,
PaginationNext,
PaginationPrevious,
} from "@/components/ui/pagination";
import { Loader2, AlertTriangle } from "lucide-react";
interface MahasiswaTerancamDO {
nim: string;
nama: string;
tahun_angkatan: number;
ipk: number | null;
semester: number;
sks_total: number | null;
alasan_do: string;
}
interface TabelNamaTerancamDOProps {
selectedYear: string;
}
export default function TabelNamaTerancamDO({ selectedYear }: TabelNamaTerancamDOProps) {
const [mahasiswaData, setMahasiswaData] = useState<MahasiswaTerancamDO[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
// State for pagination
const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(10);
const [paginatedData, setPaginatedData] = useState<MahasiswaTerancamDO[]>([]);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
setError(null);
const url = selectedYear === 'all'
? '/api/tabeldetail/terancam-do'
: `/api/tabeldetail/terancam-do?tahun_angkatan=${selectedYear}`;
const response = await fetch(url, {
cache: 'no-store',
});
if (!response.ok) {
throw new Error('Failed to fetch mahasiswa terancam DO data');
}
const data = await response.json();
setMahasiswaData(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'Terjadi kesalahan');
console.error('Error fetching data:', err);
} finally {
setLoading(false);
}
};
fetchData();
}, [selectedYear]);
// Update paginated data when data or pagination settings change
useEffect(() => {
paginateData();
}, [mahasiswaData, currentPage, pageSize]);
// Paginate data
const paginateData = () => {
const startIndex = (currentPage - 1) * pageSize;
const endIndex = startIndex + pageSize;
setPaginatedData(mahasiswaData.slice(startIndex, endIndex));
};
// Get total number of pages
const getTotalPages = () => {
return Math.ceil(mahasiswaData.length / pageSize);
};
// Handle page change
const handlePageChange = (page: number) => {
setCurrentPage(page);
};
// Handle page size change
const handlePageSizeChange = (size: string) => {
setPageSize(Number(size));
setCurrentPage(1); // Reset to first page when changing page size
};
// Hitung statistik tahun angkatan
const tahunAngkatanStats = mahasiswaData.reduce((acc, mahasiswa) => {
const tahun = mahasiswa.tahun_angkatan;
acc[tahun] = (acc[tahun] || 0) + 1;
return acc;
}, {} as Record<number, number>);
// Hitung statistik semester
const semesterStats = mahasiswaData.reduce((acc, mahasiswa) => {
const sem = mahasiswa.semester;
acc[sem] = (acc[sem] || 0) + 1;
return acc;
}, {} as Record<number, number>);
const stats = {
total: mahasiswaData.length,
total_tahun_angkatan: Object.keys(tahunAngkatanStats).length,
total_semester: Object.keys(semesterStats).length
};
if (loading) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white">
<div className="flex items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
Loading...
</div>
</CardTitle>
</CardHeader>
</Card>
);
}
if (error) {
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold text-red-500 dark:text-red-400">
Error: {error}
</CardTitle>
</CardHeader>
</Card>
);
}
return (
<Card className="bg-white dark:bg-slate-900 shadow-lg">
<CardHeader>
<CardTitle className="text-xl font-bold dark:text-white flex items-center gap-2">
<AlertTriangle className="h-5 w-5 text-red-500" />
Tabel Mahasiswa Terancam DO {selectedYear !== 'all' ? `Angkatan ${selectedYear}` : 'Semua Angkatan'}
</CardTitle>
{/* Tampilkan ringkasan statistik */}
<div className="grid grid-cols-2 md:grid-cols-3 gap-2 mt-2">
<div className="px-3 py-2 rounded-lg bg-red-50 dark:bg-red-900/20">
<div className="text-xs text-red-600 dark:text-red-400">Total Mahasiswa Terancam DO</div>
<div className="font-bold text-red-800 dark:text-red-300">{stats.total}</div>
</div>
</div>
{/* Tampilkan ringkasan per tahun angkatan */}
<div className="flex flex-wrap gap-2 mt-2">
{Object.entries(tahunAngkatanStats)
.sort(([a], [b]) => Number(a) - Number(b)) // Urutkan berdasarkan tahun angkatan
.map(([tahun, count]) => (
<span
key={tahun}
className="px-2 py-1 rounded-full text-xs font-medium bg-gray-100 text-gray-800 dark:bg-gray-800 dark:text-gray-200"
>
Angkatan {tahun}: {count} mahasiswa
</span>
))}
</div>
</CardHeader>
<CardContent>
{/* Show entries selector */}
<div className="flex items-center gap-2 mb-4">
<span className="text-sm">Show</span>
<Select
value={pageSize.toString()}
onValueChange={handlePageSizeChange}
>
<SelectTrigger className="w-[80px]">
<SelectValue placeholder={pageSize.toString()} />
</SelectTrigger>
<SelectContent>
<SelectItem value="5">5</SelectItem>
<SelectItem value="10">10</SelectItem>
<SelectItem value="25">25</SelectItem>
<SelectItem value="50">50</SelectItem>
<SelectItem value="100">100</SelectItem>
</SelectContent>
</Select>
<span className="text-sm">entries</span>
</div>
<div className="border rounded-md overflow-hidden">
<Table>
<TableHeader>
<TableRow className="bg-gray-50 dark:bg-slate-800">
<TableHead className="font-semibold text-center">No</TableHead>
<TableHead className="font-semibold">NIM</TableHead>
<TableHead className="font-semibold">Nama Mahasiswa</TableHead>
<TableHead className="font-semibold text-center">Tahun Angkatan</TableHead>
<TableHead className="font-semibold text-center">IPK</TableHead>
<TableHead className="font-semibold text-center">Semester</TableHead>
<TableHead className="font-semibold text-center">SKS Total</TableHead>
<TableHead className="font-semibold">Alasan DO</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{paginatedData.length === 0 ? (
<TableRow>
<TableCell colSpan={8} className="text-center py-8 text-muted-foreground">
Tidak ada data yang tersedia
</TableCell>
</TableRow>
) : (
paginatedData.map((mahasiswa, index) => (
<TableRow
key={`${mahasiswa.nim}-${mahasiswa.tahun_angkatan}`}
className={index % 2 === 0 ? "bg-white dark:bg-slate-900" : "bg-gray-50/50 dark:bg-slate-800/50"}
>
<TableCell className="text-center font-medium dark:text-white">
{(currentPage - 1) * pageSize + index + 1}
</TableCell>
<TableCell className="font-medium dark:text-white">
{mahasiswa.nim}
</TableCell>
<TableCell className="dark:text-white">
{mahasiswa.nama}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.tahun_angkatan}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.ipk !== null ? mahasiswa.ipk.toFixed(2) : '-'}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.semester}
</TableCell>
<TableCell className="text-center dark:text-white">
{mahasiswa.sks_total !== null ? mahasiswa.sks_total : '-'}
</TableCell>
<TableCell className="dark:text-white text-sm">
{mahasiswa.alasan_do || '-'}
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</div>
{/* Pagination info and controls */}
{!loading && !error && mahasiswaData.length > 0 && (
<div className="flex flex-col sm:flex-row justify-between items-center gap-4 mt-4">
<div className="text-sm text-muted-foreground">
Showing {getDisplayRange().start} to {getDisplayRange().end} of {mahasiswaData.length} entries
</div>
<Pagination>
<PaginationContent>
<PaginationItem>
<PaginationPrevious
onClick={() => handlePageChange(Math.max(1, currentPage - 1))}
className={currentPage === 1 ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
{renderPaginationItems()}
<PaginationItem>
<PaginationNext
onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : "cursor-pointer"}
/>
</PaginationItem>
</PaginationContent>
</Pagination>
</div>
)}
</CardContent>
</Card>
);
// Calculate the range of entries being displayed
function getDisplayRange() {
if (mahasiswaData.length === 0) return { start: 0, end: 0 };
const start = (currentPage - 1) * pageSize + 1;
const end = Math.min(currentPage * pageSize, mahasiswaData.length);
return { start, end };
}
// Generate pagination items
function renderPaginationItems() {
const totalPages = getTotalPages();
const items = [];
// Always show first page
items.push(
<PaginationItem key="first">
<PaginationLink
isActive={currentPage === 1}
onClick={() => handlePageChange(1)}
className="cursor-pointer"
>
1
</PaginationLink>
</PaginationItem>
);
// Show ellipsis if needed
if (currentPage > 3) {
items.push(
<PaginationItem key="ellipsis-start">
<PaginationEllipsis />
</PaginationItem>
);
}
// Show pages around current page
for (let i = Math.max(2, currentPage - 1); i <= Math.min(totalPages - 1, currentPage + 1); i++) {
if (i === 1 || i === totalPages) continue; // Skip first and last pages as they're always shown
items.push(
<PaginationItem key={i}>
<PaginationLink
isActive={currentPage === i}
onClick={() => handlePageChange(i)}
className="cursor-pointer"
>
{i}
</PaginationLink>
</PaginationItem>
);
}
// Show ellipsis if needed
if (currentPage < totalPages - 2) {
items.push(
<PaginationItem key="ellipsis-end">
<PaginationEllipsis />
</PaginationItem>
);
}
// Always show last page if there's more than one page
if (totalPages > 1) {
items.push(
<PaginationItem key="last">
<PaginationLink
isActive={currentPage === totalPages}
onClick={() => handlePageChange(totalPages)}
className="cursor-pointer"
>
{totalPages}
</PaginationLink>
</PaginationItem>
);
}
return items;
}
}