ayo bisa
This commit is contained in:
@@ -50,7 +50,7 @@ export default function AsalDaerahChart({
|
||||
distributed: false,
|
||||
barHeight: '90%',
|
||||
dataLabels: {
|
||||
position: 'top',
|
||||
position: 'center',
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -60,10 +60,9 @@ export default function AsalDaerahChart({
|
||||
return val.toString();
|
||||
},
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontSize: '12px',
|
||||
colors: [theme === 'dark' ? '#fff' : '#000']
|
||||
},
|
||||
offsetX: 10,
|
||||
},
|
||||
stroke: {
|
||||
show: true,
|
||||
@@ -268,7 +267,7 @@ export default function AsalDaerahChart({
|
||||
const calculateHeight = () => {
|
||||
const minHeight = 100;
|
||||
const barHeight = 15; // Tinggi per bar dalam piksel
|
||||
const padding = 50; // Ruang ekstra untuk judul, legenda, dll
|
||||
const padding = 100; // Ruang ekstra untuk judul, legenda, dll
|
||||
const dynamicHeight = Math.max(minHeight, (data.length * barHeight) + padding);
|
||||
return `${dynamicHeight}px`;
|
||||
};
|
||||
@@ -292,7 +291,7 @@ export default function AsalDaerahChart({
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className={`${height} w-full max-w-xl mx-auto`}
|
||||
className={`${height} w-full`}
|
||||
style={{ height: calculateHeight() }}
|
||||
>
|
||||
<Chart
|
||||
|
||||
@@ -61,7 +61,7 @@ export default function AsalDaerahPerAngkatanChart({ tahunAngkatan }: Props) {
|
||||
distributed: false,
|
||||
barHeight: '90%',
|
||||
dataLabels: {
|
||||
position: 'top'
|
||||
position: 'center'
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -71,10 +71,9 @@ export default function AsalDaerahPerAngkatanChart({ tahunAngkatan }: Props) {
|
||||
return val.toString();
|
||||
},
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontSize: '12px',
|
||||
colors: [theme === 'dark' ? '#fff' : '#000']
|
||||
},
|
||||
offsetX: 10,
|
||||
},
|
||||
stroke: {
|
||||
show: true,
|
||||
@@ -303,7 +302,7 @@ export default function AsalDaerahPerAngkatanChart({ tahunAngkatan }: Props) {
|
||||
const calculateHeight = () => {
|
||||
const minHeight = 100;
|
||||
const barHeight = 15; // Tinggi per bar dalam piksel
|
||||
const padding = 50; // Ruang ekstra untuk judul, legenda, dll
|
||||
const padding = 100; // Ruang ekstra untuk judul, legenda, dll
|
||||
const dynamicHeight = Math.max(minHeight, (data.length * barHeight) + padding);
|
||||
return `${dynamicHeight}px`;
|
||||
};
|
||||
@@ -317,7 +316,7 @@ export default function AsalDaerahPerAngkatanChart({ tahunAngkatan }: Props) {
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className="w-full max-w-xl mx-auto"
|
||||
className="w-full"
|
||||
style={{ height: calculateHeight() }}
|
||||
>
|
||||
<Chart
|
||||
|
||||
341
components/charts/BimbinganDosenChart.tsx
Normal file
341
components/charts/BimbinganDosenChart.tsx
Normal file
@@ -0,0 +1,341 @@
|
||||
'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";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ExternalLink } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
// Import ApexCharts secara dinamis untuk menghindari masalah SSR
|
||||
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
|
||||
|
||||
interface BimbinganDosenData {
|
||||
id_dosen: number;
|
||||
nama_dosen: string;
|
||||
selesai: number;
|
||||
belum_selesai: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface BimbinganDosenChartProps {
|
||||
height?: string;
|
||||
showDetailButton?: boolean;
|
||||
}
|
||||
|
||||
export default function BimbinganDosenChart({
|
||||
height = "h-[400px] sm:h-[450px] md:h-[500px] lg:h-[600px]",
|
||||
showDetailButton = true
|
||||
}: BimbinganDosenChartProps = {}) {
|
||||
const { theme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [data, setData] = useState<BimbinganDosenData[]>([]);
|
||||
const [series, setSeries] = useState<ApexAxisChartSeries>([
|
||||
{
|
||||
name: 'Selesai',
|
||||
data: []
|
||||
},
|
||||
{
|
||||
name: 'Belum Selesai',
|
||||
data: []
|
||||
}
|
||||
]);
|
||||
const [options, setOptions] = useState<ApexOptions>({
|
||||
chart: {
|
||||
type: 'bar',
|
||||
stacked: true,
|
||||
toolbar: {
|
||||
show: true,
|
||||
},
|
||||
},
|
||||
plotOptions: {
|
||||
bar: {
|
||||
horizontal: true,
|
||||
columnWidth: '85%',
|
||||
distributed: false,
|
||||
barHeight: '90%',
|
||||
dataLabels: {
|
||||
position: 'center',
|
||||
},
|
||||
},
|
||||
},
|
||||
dataLabels: {
|
||||
enabled: true,
|
||||
formatter: function (val: number) {
|
||||
return val > 0 ? val.toString() : '';
|
||||
},
|
||||
style: {
|
||||
fontSize: '12px',
|
||||
colors: [theme === 'dark' ? '#fff' : '#000']
|
||||
},
|
||||
},
|
||||
stroke: {
|
||||
show: true,
|
||||
width: 1,
|
||||
colors: [theme === 'dark' ? '#374151' : '#E5E7EB'],
|
||||
},
|
||||
xaxis: {
|
||||
categories: [],
|
||||
title: {
|
||||
text: 'Jumlah Bimbingan',
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '12px',
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
yaxis: {
|
||||
title: {
|
||||
text: 'Nama Dosen',
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
},
|
||||
maxWidth: 200,
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
position: 'top',
|
||||
fontSize: '14px',
|
||||
markers: {
|
||||
size: 12,
|
||||
},
|
||||
itemMargin: {
|
||||
horizontal: 10,
|
||||
},
|
||||
horizontalAlign: 'center',
|
||||
labels: {
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
fill: {
|
||||
opacity: 1,
|
||||
},
|
||||
colors: ['#10B981', '#F59E0B'], // Hijau untuk Selesai, Kuning untuk Belum Selesai
|
||||
tooltip: {
|
||||
theme: theme === 'dark' ? 'dark' : 'light',
|
||||
y: {
|
||||
formatter: function (val: number) {
|
||||
return val + " mahasiswa";
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Perbarui tema saat berubah
|
||||
useEffect(() => {
|
||||
setOptions(prev => ({
|
||||
...prev,
|
||||
chart: {
|
||||
...prev.chart,
|
||||
background: theme === 'dark' ? '#0F172B' : '#fff',
|
||||
},
|
||||
xaxis: {
|
||||
...prev.xaxis,
|
||||
title: {
|
||||
...prev.xaxis?.title,
|
||||
style: {
|
||||
...prev.xaxis?.title?.style,
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
...prev.xaxis?.labels,
|
||||
style: {
|
||||
...prev.xaxis?.labels?.style,
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
yaxis: {
|
||||
...prev.yaxis,
|
||||
title: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title : prev.yaxis?.title),
|
||||
style: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title?.style : prev.yaxis?.title?.style),
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels : prev.yaxis?.labels),
|
||||
style: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels?.style : prev.yaxis?.labels?.style),
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
...prev.legend,
|
||||
labels: {
|
||||
...prev.legend?.labels,
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
...prev.tooltip,
|
||||
theme: theme === 'dark' ? 'dark' : 'light'
|
||||
}
|
||||
}));
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch('/api/mahasiswa/bimbingan-dosen');
|
||||
|
||||
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('Format data tidak valid diterima dari server');
|
||||
}
|
||||
|
||||
// Urutkan data berdasarkan nama dosen A-Z
|
||||
const sortedResult = result.sort((a, b) => a.nama_dosen.localeCompare(b.nama_dosen));
|
||||
setData(sortedResult);
|
||||
|
||||
// Proses data untuk chart
|
||||
const namaDosen = sortedResult.map(item => item.nama_dosen);
|
||||
const selesaiData = sortedResult.map(item => item.selesai);
|
||||
const belumSelesaiData = sortedResult.map(item => item.belum_selesai);
|
||||
|
||||
setSeries([
|
||||
{
|
||||
name: 'Selesai',
|
||||
data: selesaiData
|
||||
},
|
||||
{
|
||||
name: 'Belum Selesai',
|
||||
data: belumSelesaiData
|
||||
}
|
||||
]);
|
||||
|
||||
setOptions(prev => ({
|
||||
...prev,
|
||||
xaxis: {
|
||||
...prev.xaxis,
|
||||
categories: namaDosen,
|
||||
},
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error('Error in fetchData:', err);
|
||||
setError(err instanceof Error ? err.message : 'Terjadi kesalahan saat mengambil data');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
if (!mounted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-bold dark:text-white">
|
||||
Loading...
|
||||
</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">
|
||||
Tidak ada data bimbingan yang tersedia
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Hitung tinggi dinamis berdasarkan jumlah dosen
|
||||
const calculateHeight = () => {
|
||||
const minHeight = 200;
|
||||
const barHeight = 25; // Tinggi per bar dalam piksel
|
||||
const padding = 100; // Ruang ekstra untuk judul, legenda, dll
|
||||
const dynamicHeight = Math.max(minHeight, (data.length * barHeight) + padding);
|
||||
return `${dynamicHeight}px`;
|
||||
};
|
||||
|
||||
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">
|
||||
Bimbingan Dosen
|
||||
</CardTitle>
|
||||
{showDetailButton && (
|
||||
<Link href="/detail/bimbingan-dosen" 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`}
|
||||
style={{ height: calculateHeight() }}
|
||||
>
|
||||
<Chart
|
||||
options={options}
|
||||
series={series}
|
||||
type="bar"
|
||||
height="100%"
|
||||
width="100%"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
358
components/charts/BimbinganDosenPerAngkatanChart.tsx
Normal file
358
components/charts/BimbinganDosenPerAngkatanChart.tsx
Normal file
@@ -0,0 +1,358 @@
|
||||
'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";
|
||||
|
||||
// Import ApexCharts secara dinamis untuk menghindari masalah SSR
|
||||
const Chart = dynamic(() => import('react-apexcharts'), { ssr: false });
|
||||
|
||||
interface BimbinganDosenData {
|
||||
id_dosen: number;
|
||||
nama_dosen: string;
|
||||
selesai: number;
|
||||
belum_selesai: number;
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
tahunAngkatan: string;
|
||||
}
|
||||
|
||||
export default function BimbinganDosenPerAngkatanChart({ tahunAngkatan }: Props) {
|
||||
const { theme } = useTheme();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [data, setData] = useState<BimbinganDosenData[]>([]);
|
||||
const [series, setSeries] = useState<ApexAxisChartSeries>([
|
||||
{
|
||||
name: 'Selesai',
|
||||
data: []
|
||||
},
|
||||
{
|
||||
name: 'Belum Selesai',
|
||||
data: []
|
||||
}
|
||||
]);
|
||||
const [options, setOptions] = useState<ApexOptions>({
|
||||
chart: {
|
||||
type: 'bar',
|
||||
stacked: true,
|
||||
toolbar: {
|
||||
show: true,
|
||||
tools: {
|
||||
download: true,
|
||||
selection: true,
|
||||
zoom: true,
|
||||
zoomin: true,
|
||||
zoomout: true,
|
||||
pan: true,
|
||||
reset: true,
|
||||
customIcons: []
|
||||
},
|
||||
export: {
|
||||
csv: {
|
||||
filename: `bimbingan-dosen-angkatan`,
|
||||
columnDelimiter: ',',
|
||||
headerCategory: 'Nama Dosen',
|
||||
headerValue: 'Jumlah Bimbingan'
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
plotOptions: {
|
||||
bar: {
|
||||
horizontal: true,
|
||||
columnWidth: '85%',
|
||||
distributed: false,
|
||||
barHeight: '90%',
|
||||
dataLabels: {
|
||||
position: 'center'
|
||||
}
|
||||
}
|
||||
},
|
||||
dataLabels: {
|
||||
enabled: true,
|
||||
formatter: function (val: number) {
|
||||
return val > 0 ? val.toString() : '';
|
||||
},
|
||||
style: {
|
||||
fontSize: '12px',
|
||||
colors: [theme === 'dark' ? '#fff' : '#000']
|
||||
},
|
||||
},
|
||||
stroke: {
|
||||
show: true,
|
||||
width: 1,
|
||||
colors: [theme === 'dark' ? '#374151' : '#E5E7EB'],
|
||||
},
|
||||
xaxis: {
|
||||
categories: [],
|
||||
title: {
|
||||
text: 'Jumlah Bimbingan',
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '12px',
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
yaxis: {
|
||||
title: {
|
||||
text: 'Nama Dosen',
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
fontWeight: 'bold',
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
style: {
|
||||
fontSize: '14px',
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
},
|
||||
maxWidth: 200,
|
||||
},
|
||||
},
|
||||
legend: {
|
||||
position: 'top',
|
||||
horizontalAlign: 'center',
|
||||
labels: {
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
grid: {
|
||||
padding: {
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0
|
||||
}
|
||||
},
|
||||
fill: {
|
||||
opacity: 1,
|
||||
},
|
||||
colors: ['#10B981', '#F59E0B'], // Hijau untuk Selesai, Kuning untuk Belum Selesai
|
||||
tooltip: {
|
||||
theme: theme === 'dark' ? 'dark' : 'light',
|
||||
y: {
|
||||
formatter: function (val: number) {
|
||||
return val + " mahasiswa";
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Perbarui tema saat berubah
|
||||
useEffect(() => {
|
||||
setOptions(prev => ({
|
||||
...prev,
|
||||
chart: {
|
||||
...prev.chart,
|
||||
background: theme === 'dark' ? '#0F172B' : '#fff',
|
||||
},
|
||||
xaxis: {
|
||||
...prev.xaxis,
|
||||
title: {
|
||||
...prev.xaxis?.title,
|
||||
style: {
|
||||
...prev.xaxis?.title?.style,
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
...prev.xaxis?.labels,
|
||||
style: {
|
||||
...prev.xaxis?.labels?.style,
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
yaxis: {
|
||||
...prev.yaxis,
|
||||
title: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title : prev.yaxis?.title),
|
||||
style: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.title?.style : prev.yaxis?.title?.style),
|
||||
color: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
labels: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels : prev.yaxis?.labels),
|
||||
style: {
|
||||
...(Array.isArray(prev.yaxis) ? prev.yaxis[0]?.labels?.style : prev.yaxis?.labels?.style),
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
}
|
||||
},
|
||||
legend: {
|
||||
...prev.legend,
|
||||
labels: {
|
||||
...prev.legend?.labels,
|
||||
colors: theme === 'dark' ? '#fff' : '#000'
|
||||
}
|
||||
},
|
||||
tooltip: {
|
||||
...prev.tooltip,
|
||||
theme: theme === 'dark' ? 'dark' : 'light'
|
||||
}
|
||||
}));
|
||||
}, [theme]);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch(`/api/mahasiswa/bimbingan-dosen?tahun_angkatan=${tahunAngkatan}`);
|
||||
|
||||
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('Format data tidak valid diterima dari server');
|
||||
}
|
||||
|
||||
// Urutkan data berdasarkan nama dosen A-Z
|
||||
const sortedResult = result.sort((a, b) => a.nama_dosen.localeCompare(b.nama_dosen));
|
||||
setData(sortedResult);
|
||||
|
||||
// Proses data untuk chart
|
||||
const namaDosen = sortedResult.map(item => item.nama_dosen);
|
||||
const selesaiData = sortedResult.map(item => item.selesai);
|
||||
const belumSelesaiData = sortedResult.map(item => item.belum_selesai);
|
||||
|
||||
setSeries([
|
||||
{
|
||||
name: 'Selesai',
|
||||
data: selesaiData
|
||||
},
|
||||
{
|
||||
name: 'Belum Selesai',
|
||||
data: belumSelesaiData
|
||||
}
|
||||
]);
|
||||
|
||||
setOptions(prev => ({
|
||||
...prev,
|
||||
xaxis: {
|
||||
...prev.xaxis,
|
||||
categories: namaDosen,
|
||||
},
|
||||
chart: {
|
||||
...prev.chart,
|
||||
toolbar: {
|
||||
...prev.chart?.toolbar,
|
||||
export: {
|
||||
...prev.chart?.toolbar?.export,
|
||||
csv: {
|
||||
...prev.chart?.toolbar?.export?.csv,
|
||||
filename: `bimbingan-dosen-angkatan-${tahunAngkatan}`,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
} catch (err) {
|
||||
console.error('Error in fetchData:', err);
|
||||
setError(err instanceof Error ? err.message : 'Terjadi kesalahan saat mengambil data');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (tahunAngkatan) {
|
||||
fetchData();
|
||||
}
|
||||
}, [tahunAngkatan]);
|
||||
|
||||
if (!mounted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-bold dark:text-white">
|
||||
Loading...
|
||||
</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">
|
||||
Tidak ada data bimbingan yang tersedia untuk angkatan {tahunAngkatan}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Hitung tinggi dinamis berdasarkan jumlah dosen
|
||||
const calculateHeight = () => {
|
||||
const minHeight = 200;
|
||||
const barHeight = 25; // Tinggi per bar dalam piksel
|
||||
const padding = 100; // Ruang ekstra untuk judul, legenda, dll
|
||||
const dynamicHeight = Math.max(minHeight, (data.length * barHeight) + padding);
|
||||
return `${dynamicHeight}px`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-xl font-bold dark:text-white">
|
||||
Bimbingan Dosen Angkatan {tahunAngkatan}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div
|
||||
className="w-full"
|
||||
style={{ height: calculateHeight() }}
|
||||
>
|
||||
<Chart
|
||||
options={options}
|
||||
series={series}
|
||||
type="bar"
|
||||
height="100%"
|
||||
width="100%"
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
617
components/datatable/data-table-dosen.tsx
Normal file
617
components/datatable/data-table-dosen.tsx
Normal file
@@ -0,0 +1,617 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow
|
||||
} from "@/components/ui/table";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogClose
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Pagination,
|
||||
PaginationContent,
|
||||
PaginationEllipsis,
|
||||
PaginationItem,
|
||||
PaginationLink,
|
||||
PaginationNext,
|
||||
PaginationPrevious,
|
||||
} from "@/components/ui/pagination";
|
||||
import {
|
||||
PlusCircle,
|
||||
Pencil,
|
||||
Trash2,
|
||||
Search,
|
||||
X,
|
||||
Loader2
|
||||
} from "lucide-react";
|
||||
import UploadExcelDosen from "@/components/datatable/upload-file-dosen";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
// Define the Dosen type
|
||||
interface Dosen {
|
||||
id_dosen: number;
|
||||
nama_dosen: string;
|
||||
nip: string;
|
||||
}
|
||||
|
||||
export default function DataTableDosen() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
|
||||
// State for data
|
||||
const [dosen, setDosen] = useState<Dosen[]>([]);
|
||||
const [filteredData, setFilteredData] = useState<Dosen[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// State for filtering
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
|
||||
// State for pagination
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [paginatedData, setPaginatedData] = useState<Dosen[]>([]);
|
||||
|
||||
// State for form
|
||||
const [formMode, setFormMode] = useState<"add" | "edit">("add");
|
||||
const [formData, setFormData] = useState<Partial<Dosen>>({});
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
|
||||
// State for delete confirmation
|
||||
const [deleteId, setDeleteId] = useState<number | null>(null);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
|
||||
|
||||
// Fetch data on component mount
|
||||
useEffect(() => {
|
||||
fetchDosen();
|
||||
}, []);
|
||||
|
||||
// Filter data when search term changes
|
||||
useEffect(() => {
|
||||
filterData();
|
||||
}, [searchTerm, dosen]);
|
||||
|
||||
// Update paginated data when filtered data or pagination settings change
|
||||
useEffect(() => {
|
||||
paginateData();
|
||||
}, [filteredData, currentPage, pageSize]);
|
||||
|
||||
// Fetch dosen data from API
|
||||
const fetchDosen = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
let url = "/api/keloladata/data-dosen";
|
||||
|
||||
// Add search to URL if it exists
|
||||
const params = new URLSearchParams();
|
||||
if (searchTerm) {
|
||||
params.append("search", searchTerm);
|
||||
}
|
||||
|
||||
if (params.toString()) {
|
||||
url += `?${params.toString()}`;
|
||||
}
|
||||
|
||||
const response = await fetch(url);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch data");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setDosen(data);
|
||||
setFilteredData(data);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError("Error fetching data. Please try again later.");
|
||||
console.error("Error fetching data:", err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Filter data based on search term
|
||||
const filterData = () => {
|
||||
let filtered = [...dosen];
|
||||
|
||||
// Filter by search term
|
||||
if (searchTerm) {
|
||||
filtered = filtered.filter(
|
||||
(item) =>
|
||||
(item.nama_dosen?.toLowerCase() || "").includes(searchTerm.toLowerCase()) ||
|
||||
(item.nip?.toLowerCase() || "").includes(searchTerm.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
setFilteredData(filtered);
|
||||
// Reset to first page when filters change
|
||||
setCurrentPage(1);
|
||||
};
|
||||
|
||||
// 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
|
||||
};
|
||||
|
||||
// Reset form data
|
||||
const resetForm = () => {
|
||||
setFormData({});
|
||||
};
|
||||
|
||||
// Handle form input changes
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Open form dialog for adding new dosen
|
||||
const handleAdd = () => {
|
||||
setFormMode("add");
|
||||
resetForm();
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
// Open form dialog for editing dosen
|
||||
const handleEdit = (data: Dosen) => {
|
||||
setFormMode("edit");
|
||||
setFormData(data);
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
// Open delete confirmation dialog
|
||||
const handleDeleteConfirm = (id: number) => {
|
||||
setDeleteId(id);
|
||||
setIsDeleteDialogOpen(true);
|
||||
};
|
||||
|
||||
// Submit form for add/edit
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
setIsSubmitting(true);
|
||||
|
||||
if (formMode === "add") {
|
||||
// Add new dosen
|
||||
const response = await fetch("/api/keloladata/data-dosen", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific errors
|
||||
if (response.status === 409) {
|
||||
showError("Gagal!", responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
}
|
||||
if (response.status === 400) {
|
||||
showError("Gagal!", responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
}
|
||||
showError("Gagal!", "Gagal menambahkan dosen");
|
||||
throw new Error(responseData.message || "Failed to add dosen");
|
||||
}
|
||||
|
||||
showSuccess("Berhasil!", "Dosen berhasil ditambahkan");
|
||||
} else {
|
||||
// Edit existing dosen
|
||||
const response = await fetch(`/api/keloladata/data-dosen?id=${formData.id_dosen}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific errors
|
||||
if (response.status === 409) {
|
||||
showError("Gagal!", responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
}
|
||||
if (response.status === 400) {
|
||||
showError("Gagal!", responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
}
|
||||
showError("Gagal!", responseData.message || "Failed to update dosen");
|
||||
throw new Error(responseData.message || "Failed to update dosen");
|
||||
}
|
||||
|
||||
showSuccess("Berhasil!", "Dosen berhasil diperbarui");
|
||||
}
|
||||
|
||||
// Refresh data after successful operation
|
||||
await fetchDosen();
|
||||
setIsDialogOpen(false);
|
||||
resetForm();
|
||||
} catch (err) {
|
||||
console.error("Error submitting form:", err);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete dosen
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
|
||||
try {
|
||||
setIsDeleting(true);
|
||||
|
||||
const response = await fetch(`/api/keloladata/data-dosen?id=${deleteId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) {
|
||||
showError("Gagal!", responseData.message);
|
||||
throw new Error(responseData.message);
|
||||
}
|
||||
showError("Gagal!", responseData.message || "Failed to delete dosen");
|
||||
throw new Error(responseData.message || "Failed to delete dosen");
|
||||
}
|
||||
|
||||
// Refresh data after successful deletion
|
||||
await fetchDosen();
|
||||
setIsDeleteDialogOpen(false);
|
||||
setDeleteId(null);
|
||||
showSuccess("Berhasil!", "Dosen berhasil dihapus");
|
||||
} catch (err) {
|
||||
console.error("Error deleting dosen:", err);
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Generate pagination items
|
||||
const renderPaginationItems = () => {
|
||||
const totalPages = getTotalPages();
|
||||
const items = [];
|
||||
|
||||
// Always show first page
|
||||
items.push(
|
||||
<PaginationItem key="first">
|
||||
<PaginationLink
|
||||
isActive={currentPage === 1}
|
||||
onClick={() => handlePageChange(1)}
|
||||
>
|
||||
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)}
|
||||
>
|
||||
{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)}
|
||||
>
|
||||
{totalPages}
|
||||
</PaginationLink>
|
||||
</PaginationItem>
|
||||
);
|
||||
}
|
||||
|
||||
return items;
|
||||
};
|
||||
|
||||
// Calculate the range of entries being displayed
|
||||
const 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 };
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
|
||||
<h2 className="text-2xl font-bold">Data Dosen</h2>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<Button onClick={handleAdd}>
|
||||
<PlusCircle className="mr-2 h-4 w-4" />
|
||||
Tambah Dosen
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Search */}
|
||||
<div className="flex flex-col sm:flex-row gap-4">
|
||||
<div className="relative flex-1">
|
||||
<Search className="absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Cari berdasarkan nama dosen atau NIP..."
|
||||
className="pl-8"
|
||||
value={searchTerm}
|
||||
onChange={(e) => setSearchTerm(e.target.value)}
|
||||
/>
|
||||
{searchTerm && (
|
||||
<X
|
||||
className="absolute right-2.5 top-2.5 h-4 w-4 text-muted-foreground cursor-pointer"
|
||||
onClick={() => setSearchTerm("")}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Show entries selector */}
|
||||
<div className="flex items-center gap-2">
|
||||
<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>
|
||||
|
||||
{/* Table */}
|
||||
{loading ? (
|
||||
<div className="flex justify-center items-center py-8">
|
||||
<Loader2 className="h-8 w-8 animate-spin text-primary" />
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="bg-destructive/10 p-4 rounded-md text-destructive text-center">
|
||||
{error}
|
||||
</div>
|
||||
) : (
|
||||
<div className="border rounded-md">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
{/* <TableHead className="w-[80px]">ID</TableHead> */}
|
||||
<TableHead>Nama Dosen</TableHead>
|
||||
<TableHead>NIP</TableHead>
|
||||
<TableHead className="text-right">Aksi</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedData.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={4} className="text-center py-8">
|
||||
Tidak ada data yang sesuai dengan pencarian
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
paginatedData.map((dosenItem) => (
|
||||
<TableRow key={dosenItem.id_dosen}>
|
||||
{/* <TableCell>{dosenItem.id_dosen}</TableCell> */}
|
||||
<TableCell className="font-medium">{dosenItem.nama_dosen}</TableCell>
|
||||
<TableCell>{dosenItem.nip}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleEdit(dosenItem)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDeleteConfirm(dosenItem.id_dosen)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</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">
|
||||
<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" : ""}
|
||||
/>
|
||||
</PaginationItem>
|
||||
|
||||
{renderPaginationItems()}
|
||||
|
||||
<PaginationItem>
|
||||
<PaginationNext
|
||||
onClick={() => handlePageChange(Math.min(getTotalPages(), currentPage + 1))}
|
||||
className={currentPage === getTotalPages() ? "pointer-events-none opacity-50" : ""}
|
||||
/>
|
||||
</PaginationItem>
|
||||
</PaginationContent>
|
||||
</Pagination>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add/Edit Dialog */}
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{formMode === "add" ? "Tambah Dosen" : "Edit Dosen"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nama_dosen" className="text-sm font-medium">
|
||||
Nama Dosen <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nama_dosen"
|
||||
name="nama_dosen"
|
||||
value={formData.nama_dosen || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
maxLength={120}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nip" className="text-sm font-medium">
|
||||
NIP <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nip"
|
||||
name="nip"
|
||||
value={formData.nip || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
maxLength={18}
|
||||
placeholder="18 karakter"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
NIP harus terdiri dari 18 karakter
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Batal
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={isSubmitting}>
|
||||
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{formMode === "add" ? "Tambah" : "Simpan"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Delete Confirmation Dialog */}
|
||||
<Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
|
||||
<DialogContent className="sm:max-w-[400px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Konfirmasi Hapus</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="py-4">
|
||||
<p>Apakah Anda yakin ingin menghapus data dosen ini?</p>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Tindakan ini tidak dapat dibatalkan.
|
||||
</p>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Batal
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
disabled={isDeleting}
|
||||
>
|
||||
{isDeleting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Hapus
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -66,6 +66,11 @@ interface Mahasiswa {
|
||||
nama_kelompok_keahlian: string | null;
|
||||
status_kuliah: "Aktif" | "Cuti" | "Lulus" | "Non-Aktif";
|
||||
semester: number;
|
||||
pembimbing_1: number | null;
|
||||
nama_pembimbing_1: string | null;
|
||||
pembimbing_2: number | null;
|
||||
nama_pembimbing_2: string | null;
|
||||
status_bimbingan: "Selesai" | "Belum Selesai";
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
@@ -76,6 +81,13 @@ interface KelompokKeahlian {
|
||||
nama_kelompok: string;
|
||||
}
|
||||
|
||||
// Define the Dosen type
|
||||
interface Dosen {
|
||||
id_dosen: number;
|
||||
nama_dosen: string;
|
||||
nip: string;
|
||||
}
|
||||
|
||||
export default function DataTableMahasiswa() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
// State for data
|
||||
@@ -125,6 +137,9 @@ export default function DataTableMahasiswa() {
|
||||
const [deleteKelompokKeahlianId, setDeleteKelompokKeahlianId] = useState<number | null>(null);
|
||||
const [isKelompokKeahlianDeleting, setIsKelompokKeahlianDeleting] = useState(false);
|
||||
const [isKelompokKeahlianDeleteDialogOpen, setIsKelompokKeahlianDeleteDialogOpen] = useState(false);
|
||||
|
||||
// State for dosen data
|
||||
const [dosenData, setDosenData] = useState<Dosen[]>([]);
|
||||
|
||||
// Fetch data on component mount
|
||||
useEffect(() => {
|
||||
@@ -132,6 +147,7 @@ export default function DataTableMahasiswa() {
|
||||
fetchJenisPendaftaranOptions();
|
||||
fetchKelompokKeahlianOptions();
|
||||
fetchKelompokKeahlianData();
|
||||
fetchDosenData();
|
||||
}, []);
|
||||
|
||||
// Filter data when search term or filter changes
|
||||
@@ -267,7 +283,8 @@ export default function DataTableMahasiswa() {
|
||||
setFormData({
|
||||
jk: "Pria",
|
||||
status_kuliah: "Aktif",
|
||||
semester: 1
|
||||
semester: 1,
|
||||
status_bimbingan: "Belum Selesai"
|
||||
});
|
||||
};
|
||||
|
||||
@@ -291,6 +308,9 @@ export default function DataTableMahasiswa() {
|
||||
} else if (name === "semester") {
|
||||
const numValue = value === "" ? 1 : parseInt(value);
|
||||
setFormData((prev) => ({ ...prev, [name]: numValue }));
|
||||
} else if (name === "pembimbing_1" || name === "pembimbing_2") {
|
||||
const numValue = value === "null" || value === "" ? null : parseInt(value);
|
||||
setFormData((prev) => ({ ...prev, [name]: numValue }));
|
||||
} else {
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
}
|
||||
@@ -329,6 +349,22 @@ export default function DataTableMahasiswa() {
|
||||
}
|
||||
};
|
||||
|
||||
// Fetch dosen data from API
|
||||
const fetchDosenData = async () => {
|
||||
try {
|
||||
const response = await fetch("/api/keloladata/data-dosen");
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Failed to fetch dosen data");
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
setDosenData(data);
|
||||
} catch (err) {
|
||||
console.error("Error fetching dosen data:", err);
|
||||
}
|
||||
};
|
||||
|
||||
// Open form dialog for adding new mahasiswa
|
||||
const handleAdd = () => {
|
||||
setFormMode("add");
|
||||
@@ -337,6 +373,7 @@ export default function DataTableMahasiswa() {
|
||||
// Make sure we have the latest options
|
||||
fetchJenisPendaftaranOptions();
|
||||
fetchKelompokKeahlianOptions();
|
||||
fetchDosenData();
|
||||
};
|
||||
|
||||
// Open form dialog for editing mahasiswa
|
||||
@@ -347,6 +384,7 @@ export default function DataTableMahasiswa() {
|
||||
// Make sure we have the latest options
|
||||
fetchJenisPendaftaranOptions();
|
||||
fetchKelompokKeahlianOptions();
|
||||
fetchDosenData();
|
||||
};
|
||||
|
||||
// Open delete confirmation dialog
|
||||
@@ -748,13 +786,16 @@ export default function DataTableMahasiswa() {
|
||||
<TableHead>IPK</TableHead>
|
||||
<TableHead>Status Kuliah</TableHead>
|
||||
<TableHead>Kelompok Keahlian</TableHead>
|
||||
<TableHead>Pembimbing 1</TableHead>
|
||||
<TableHead>Pembimbing 2</TableHead>
|
||||
<TableHead>Status Bimbingan</TableHead>
|
||||
<TableHead className="text-right">Aksi</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedData.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={13} className="text-center py-8">
|
||||
<TableCell colSpan={16} className="text-center py-8">
|
||||
Tidak ada data yang sesuai dengan filter
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
@@ -787,6 +828,19 @@ export default function DataTableMahasiswa() {
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>{mhs.nama_kelompok_keahlian || "-"}</TableCell>
|
||||
<TableCell>{mhs.nama_pembimbing_1 || "-"}</TableCell>
|
||||
<TableCell>{mhs.nama_pembimbing_2 || "-"}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||
mhs.status_bimbingan === "Selesai"
|
||||
? "bg-green-100 text-green-800"
|
||||
: "bg-orange-100 text-orange-800"
|
||||
}`}
|
||||
>
|
||||
{mhs.status_bimbingan}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<BiodataMahasiswaDialog nim={mhs.nim} nama={mhs.nama} />
|
||||
@@ -1026,6 +1080,65 @@ export default function DataTableMahasiswa() {
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="pembimbing_1" className="text-sm font-medium">
|
||||
Pembimbing 1
|
||||
</label>
|
||||
<Select
|
||||
value={formData.pembimbing_1?.toString() || "null"}
|
||||
onValueChange={(value) => handleSelectChange("pembimbing_1", value)}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Pilih Pembimbing 1" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="null">-- Tidak Ada --</SelectItem>
|
||||
{dosenData.map((dosen) => (
|
||||
<SelectItem key={dosen.id_dosen} value={dosen.id_dosen.toString()}>
|
||||
{dosen.nama_dosen}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="pembimbing_2" className="text-sm font-medium">
|
||||
Pembimbing 2
|
||||
</label>
|
||||
<Select
|
||||
value={formData.pembimbing_2?.toString() || "null"}
|
||||
onValueChange={(value) => handleSelectChange("pembimbing_2", value)}
|
||||
>
|
||||
<SelectTrigger className="w-full">
|
||||
<SelectValue placeholder="Pilih Pembimbing 2" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="null">-- Tidak Ada --</SelectItem>
|
||||
{dosenData.map((dosen) => (
|
||||
<SelectItem key={dosen.id_dosen} value={dosen.id_dosen.toString()}>
|
||||
{dosen.nama_dosen}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="status_bimbingan" className="text-sm font-medium">
|
||||
Status Bimbingan <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Select
|
||||
value={formData.status_bimbingan || "Belum Selesai"}
|
||||
onValueChange={(value) => handleSelectChange("status_bimbingan", value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Belum Selesai">Belum Selesai</SelectItem>
|
||||
<SelectItem value="Selesai">Selesai</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter className="flex flex-col sm:flex-row gap-2 sm:gap-0">
|
||||
|
||||
225
components/datatable/upload-file-dosen.tsx
Normal file
225
components/datatable/upload-file-dosen.tsx
Normal file
@@ -0,0 +1,225 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
DialogClose
|
||||
} from "@/components/ui/dialog";
|
||||
import { Upload, FileText, Loader2, X, CheckCircle, AlertCircle } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
interface UploadExcelDosenProps {
|
||||
onUploadSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function UploadExcelDosen({ onUploadSuccess }: UploadExcelDosenProps) {
|
||||
const { showSuccess, showError } = useToast();
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [uploadResult, setUploadResult] = useState<any>(null);
|
||||
|
||||
// Handle file selection
|
||||
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
// Validate file type
|
||||
const allowedTypes = [
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-excel',
|
||||
'text/csv'
|
||||
];
|
||||
|
||||
if (allowedTypes.includes(file.type)) {
|
||||
setSelectedFile(file);
|
||||
} else {
|
||||
showError("File tidak valid", "Silakan pilih file Excel (.xlsx, .xls) atau CSV (.csv)");
|
||||
e.target.value = '';
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Handle file upload
|
||||
const handleUpload = async () => {
|
||||
if (!selectedFile) {
|
||||
showError("Tidak ada file", "Silakan pilih file terlebih dahulu");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUploading(true);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', selectedFile);
|
||||
|
||||
const response = await fetch('/api/keloladata/data-dosen/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.message || 'Upload failed');
|
||||
}
|
||||
|
||||
setUploadResult(result);
|
||||
|
||||
if (result.details.successCount > 0) {
|
||||
showSuccess("Upload berhasil!", result.message);
|
||||
onUploadSuccess(); // Refresh the main table
|
||||
} else {
|
||||
showError("Upload gagal", "Tidak ada data yang berhasil diupload");
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
showError("Error", error instanceof Error ? error.message : "Terjadi kesalahan saat upload");
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Reset dialog
|
||||
const resetDialog = () => {
|
||||
setSelectedFile(null);
|
||||
setUploadResult(null);
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
// Close dialog
|
||||
const handleDialogClose = () => {
|
||||
setIsDialogOpen(false);
|
||||
resetDialog();
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button variant="outline" onClick={() => setIsDialogOpen(true)}>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Upload Excel
|
||||
</Button>
|
||||
|
||||
<Dialog open={isDialogOpen} onOpenChange={handleDialogClose}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Data Dosen</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4 py-4">
|
||||
{/* Instructions */}
|
||||
<div className="bg-blue-50 p-4 rounded-lg">
|
||||
<h4 className="font-medium text-blue-900 mb-2">Petunjuk Upload:</h4>
|
||||
<ul className="text-sm text-blue-800 space-y-1">
|
||||
<li>• File harus berformat Excel (.xlsx, .xls) atau CSV (.csv)</li>
|
||||
<li>• Kolom yang diperlukan: <strong>nama_dosen</strong>, <strong>nip</strong></li>
|
||||
<li>• NIP harus terdiri dari 18 karakter</li>
|
||||
<li>• Jika NIP sudah ada, data akan diupdate</li>
|
||||
<li>• Baris pertama harus berisi header kolom</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
{/* File Input */}
|
||||
<div className="space-y-2">
|
||||
<label className="text-sm font-medium">Pilih File:</label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
onChange={handleFileSelect}
|
||||
className="flex-1"
|
||||
/>
|
||||
{selectedFile && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={resetDialog}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{selectedFile && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||
<FileText className="h-4 w-4" />
|
||||
<span>{selectedFile.name}</span>
|
||||
<span className="text-muted-foreground">
|
||||
({(selectedFile.size / 1024).toFixed(1)} KB)
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Upload Result */}
|
||||
{uploadResult && (
|
||||
<div className="space-y-3">
|
||||
<div className="bg-gray-50 p-4 rounded-lg">
|
||||
<h4 className="font-medium mb-2">Hasil Upload:</h4>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="flex items-center gap-2 text-green-600">
|
||||
<CheckCircle className="h-4 w-4" />
|
||||
<span>Berhasil: {uploadResult.details.successCount}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-red-600">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<span>Gagal: {uploadResult.details.failedCount}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground mt-2">
|
||||
Total baris: {uploadResult.details.totalRows}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Show errors if any */}
|
||||
{uploadResult.details.errors && uploadResult.details.errors.length > 0 && (
|
||||
<div className="bg-red-50 p-4 rounded-lg max-h-60 overflow-y-auto">
|
||||
<h5 className="font-medium text-red-900 mb-2">Error Details:</h5>
|
||||
<div className="space-y-1">
|
||||
{uploadResult.details.errors.slice(0, 10).map((error: string, index: number) => (
|
||||
<div key={index} className="text-sm text-red-800">
|
||||
{error}
|
||||
</div>
|
||||
))}
|
||||
{uploadResult.details.errors.length > 10 && (
|
||||
<div className="text-sm text-red-600 font-medium">
|
||||
... dan {uploadResult.details.errors.length - 10} error lainnya
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Tutup
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button
|
||||
onClick={handleUpload}
|
||||
disabled={!selectedFile || isUploading}
|
||||
>
|
||||
{isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isUploading ? "Uploading..." : "Upload"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { ThemeToggle } from '@/components/theme-toggle';
|
||||
import { Menu, ChevronDown, BarChart, Database, CircleCheck, School, GraduationCap, Clock, BookOpen, Award, Home, LogOut, User } from 'lucide-react';
|
||||
import { Menu, ChevronDown, BarChart, Database, CircleCheck, School, GraduationCap, Clock, BookOpen, Award, Home, LogOut, User, Users } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import {
|
||||
@@ -194,6 +194,12 @@ const Navbar = () => {
|
||||
Prestasi
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/keloladata/dosen" className="flex items-center gap-2 w-full">
|
||||
<Users className="h-4 w-4" />
|
||||
Dosen
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
|
||||
Reference in New Issue
Block a user