Add Kelola Data
This commit is contained in:
@@ -111,14 +111,13 @@ export async function POST(request: NextRequest) {
|
||||
nim,
|
||||
nama_beasiswa,
|
||||
sumber_beasiswa,
|
||||
beasiswa_status,
|
||||
jenis_beasiswa
|
||||
} = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !beasiswa_status || !jenis_beasiswa) {
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !jenis_beasiswa) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Missing required fields: nim, nama_beasiswa, sumber_beasiswa, beasiswa_status, jenis_beasiswa' },
|
||||
{ message: 'Missing required fields: nim, nama_beasiswa, sumber_beasiswa, jenis_beasiswa' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -138,16 +137,8 @@ export async function POST(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Validate enum values
|
||||
const validStatus = ['Aktif', 'Selesai', 'Dibatalkan'];
|
||||
const validJenisBeasiswa = ['Pemerintah', 'Non-Pemerintah'];
|
||||
|
||||
if (!validStatus.includes(beasiswa_status)) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Invalid beasiswa_status value. Must be one of: Aktif, Selesai, Dibatalkan' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!validJenisBeasiswa.includes(jenis_beasiswa)) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Invalid jenis_beasiswa value. Must be one of: Pemerintah, Non-Pemerintah' },
|
||||
@@ -162,7 +153,6 @@ export async function POST(request: NextRequest) {
|
||||
id_mahasiswa: mahasiswaExists.id_mahasiswa,
|
||||
nama_beasiswa,
|
||||
sumber_beasiswa,
|
||||
beasiswa_status,
|
||||
jenis_beasiswa
|
||||
})
|
||||
.select()
|
||||
@@ -201,14 +191,13 @@ export async function PUT(request: NextRequest) {
|
||||
nim,
|
||||
nama_beasiswa,
|
||||
sumber_beasiswa,
|
||||
beasiswa_status,
|
||||
jenis_beasiswa
|
||||
} = body;
|
||||
|
||||
// Validate required fields
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !beasiswa_status || !jenis_beasiswa) {
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !jenis_beasiswa) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Missing required fields: nim, nama_beasiswa, sumber_beasiswa, beasiswa_status, jenis_beasiswa' },
|
||||
{ message: 'Missing required fields: nim, nama_beasiswa, sumber_beasiswa, jenis_beasiswa' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
@@ -239,16 +228,8 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
|
||||
// Validate enum values
|
||||
const validStatus = ['Aktif', 'Selesai', 'Dibatalkan'];
|
||||
const validJenisBeasiswa = ['Pemerintah', 'Non-Pemerintah'];
|
||||
|
||||
if (!validStatus.includes(beasiswa_status)) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Invalid beasiswa_status value. Must be one of: Aktif, Selesai, Dibatalkan' },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
if (!validJenisBeasiswa.includes(jenis_beasiswa)) {
|
||||
return NextResponse.json(
|
||||
{ message: 'Invalid jenis_beasiswa value. Must be one of: Pemerintah, Non-Pemerintah' },
|
||||
@@ -263,7 +244,6 @@ export async function PUT(request: NextRequest) {
|
||||
id_mahasiswa: mahasiswaExists.id_mahasiswa,
|
||||
nama_beasiswa,
|
||||
sumber_beasiswa,
|
||||
beasiswa_status,
|
||||
jenis_beasiswa
|
||||
})
|
||||
.eq('id_beasiswa', id);
|
||||
|
||||
@@ -2,6 +2,11 @@ import { NextRequest, NextResponse } from 'next/server';
|
||||
import * as XLSX from 'xlsx';
|
||||
import supabase from '@/lib/db';
|
||||
|
||||
// GET method for testing the route
|
||||
export async function GET() {
|
||||
return NextResponse.json({ message: 'Upload route is working' });
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
// Get form data from request
|
||||
@@ -12,6 +17,11 @@ export async function POST(request: NextRequest) {
|
||||
return NextResponse.json({ message: 'File tidak ditemukan' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate file size (max 10MB)
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
return NextResponse.json({ message: 'File terlalu besar. Maksimal 10MB' }, { status: 400 });
|
||||
}
|
||||
|
||||
// Process file data based on file type
|
||||
let validData = [];
|
||||
let errors: string[] = [];
|
||||
@@ -65,10 +75,18 @@ async function processExcelData(fileBuffer: ArrayBuffer) {
|
||||
// Parse Excel file
|
||||
const workbook = XLSX.read(fileBuffer, { type: 'array' });
|
||||
|
||||
if (!workbook.SheetNames || workbook.SheetNames.length === 0) {
|
||||
return { validData: [], errors: ['File Excel tidak memiliki sheet'] };
|
||||
}
|
||||
|
||||
// Get first sheet
|
||||
const sheetName = workbook.SheetNames[0];
|
||||
const worksheet = workbook.Sheets[sheetName];
|
||||
|
||||
if (!worksheet) {
|
||||
return { validData: [], errors: ['Sheet pertama tidak ditemukan'] };
|
||||
}
|
||||
|
||||
// Convert to JSON with proper typing
|
||||
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }) as any[][];
|
||||
|
||||
@@ -76,6 +94,10 @@ async function processExcelData(fileBuffer: ArrayBuffer) {
|
||||
return { validData: [], errors: ['File Excel kosong'] };
|
||||
}
|
||||
|
||||
if (jsonData.length < 2) {
|
||||
return { validData: [], errors: ['File Excel hanya memiliki header, tidak ada data'] };
|
||||
}
|
||||
|
||||
// Convert Excel data to CSV-like format for processing
|
||||
const headers = jsonData[0].map(h => String(h).toLowerCase());
|
||||
const rows = jsonData.slice(1);
|
||||
@@ -84,7 +106,7 @@ async function processExcelData(fileBuffer: ArrayBuffer) {
|
||||
return processData(headers, rows);
|
||||
} catch (error) {
|
||||
console.error('Error processing Excel data:', error);
|
||||
return { validData: [], errors: [(error as Error).message] };
|
||||
return { validData: [], errors: [`Error memproses file Excel: ${(error as Error).message}`] };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +135,6 @@ function processData(headers: string[], rows: any[][]) {
|
||||
nim: ['nim', 'nomor induk', 'nomor mahasiswa'],
|
||||
nama_beasiswa: ['nama_beasiswa', 'nama beasiswa', 'namabeasiswa', 'beasiswa', 'nama'],
|
||||
sumber_beasiswa: ['sumber_beasiswa', 'sumber beasiswa', 'sumberbeasiswa', 'sumber'],
|
||||
beasiswa_status: ['beasiswa_status', 'status beasiswa', 'statusbeasiswa', 'status'],
|
||||
jenis_beasiswa: ['jenis_beasiswa', 'jenis beasiswa', 'jenisbeasiswa', 'jenis']
|
||||
};
|
||||
|
||||
@@ -129,19 +150,18 @@ function processData(headers: string[], rows: any[][]) {
|
||||
}
|
||||
|
||||
// Check required headers
|
||||
const requiredHeaders = ['nim', 'nama_beasiswa', 'sumber_beasiswa', 'beasiswa_status', 'jenis_beasiswa'];
|
||||
const requiredHeaders = ['nim', 'nama_beasiswa', 'sumber_beasiswa', 'jenis_beasiswa'];
|
||||
const missingHeaders = requiredHeaders.filter(h => headerMap[h] === undefined);
|
||||
|
||||
if (missingHeaders.length > 0) {
|
||||
return {
|
||||
validData: [],
|
||||
errors: [`Kolom berikut tidak ditemukan: ${missingHeaders.join(', ')}. Pastikan file memiliki kolom: NIM, Nama Beasiswa, Sumber Beasiswa, Status Beasiswa, dan Jenis Beasiswa.`]
|
||||
errors: [`Kolom berikut tidak ditemukan: ${missingHeaders.join(', ')}. Pastikan file memiliki kolom: NIM, Nama Beasiswa, Sumber Beasiswa, dan Jenis Beasiswa.`]
|
||||
};
|
||||
}
|
||||
|
||||
const validData = [];
|
||||
const errors = [];
|
||||
const validStatuses = ['Aktif', 'Selesai', 'Dibatalkan'];
|
||||
const validJenis = ['Pemerintah', 'Non-Pemerintah'];
|
||||
|
||||
// Process data rows
|
||||
@@ -154,24 +174,14 @@ function processData(headers: string[], rows: any[][]) {
|
||||
const nim = String(values[headerMap.nim] || '').trim();
|
||||
const nama_beasiswa = String(values[headerMap.nama_beasiswa] || '').trim();
|
||||
const sumber_beasiswa = String(values[headerMap.sumber_beasiswa] || '').trim();
|
||||
let beasiswa_status = String(values[headerMap.beasiswa_status] || '').trim();
|
||||
let jenis_beasiswa = String(values[headerMap.jenis_beasiswa] || '').trim();
|
||||
|
||||
// Validate required fields
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !beasiswa_status || !jenis_beasiswa) {
|
||||
if (!nim || !nama_beasiswa || !sumber_beasiswa || !jenis_beasiswa) {
|
||||
errors.push(`Baris ${i+2}: Data tidak lengkap (NIM: ${nim || 'kosong'})`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Normalize status beasiswa
|
||||
beasiswa_status = normalizeBeasiswaStatus(beasiswa_status);
|
||||
|
||||
// Validate status beasiswa
|
||||
if (!validStatuses.includes(beasiswa_status)) {
|
||||
errors.push(`Baris ${i+2}: Status beasiswa tidak valid "${beasiswa_status}" untuk NIM ${nim}. Harus salah satu dari: ${validStatuses.join(', ')}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Normalize jenis beasiswa
|
||||
jenis_beasiswa = normalizeJenisBeasiswa(jenis_beasiswa);
|
||||
|
||||
@@ -186,7 +196,6 @@ function processData(headers: string[], rows: any[][]) {
|
||||
nim,
|
||||
nama_beasiswa,
|
||||
sumber_beasiswa,
|
||||
beasiswa_status,
|
||||
jenis_beasiswa
|
||||
});
|
||||
|
||||
@@ -198,25 +207,6 @@ function processData(headers: string[], rows: any[][]) {
|
||||
return { validData, errors };
|
||||
}
|
||||
|
||||
// Function to normalize beasiswa status values
|
||||
function normalizeBeasiswaStatus(value: string): string {
|
||||
const lowerValue = value.toLowerCase();
|
||||
|
||||
if (['aktif', 'active', 'a'].includes(lowerValue)) {
|
||||
return 'Aktif';
|
||||
}
|
||||
|
||||
if (['selesai', 'complete', 'completed', 's', 'finish', 'finished'].includes(lowerValue)) {
|
||||
return 'Selesai';
|
||||
}
|
||||
|
||||
if (['dibatalkan', 'cancel', 'cancelled', 'canceled', 'batal', 'd', 'c'].includes(lowerValue)) {
|
||||
return 'Dibatalkan';
|
||||
}
|
||||
|
||||
return value; // Return original if no match
|
||||
}
|
||||
|
||||
// Function to normalize jenis beasiswa values
|
||||
function normalizeJenisBeasiswa(value: string): string {
|
||||
const lowerValue = value.toLowerCase();
|
||||
@@ -238,22 +228,13 @@ async function insertDataToDatabase(data: any[]) {
|
||||
let errorCount = 0;
|
||||
const errorMessages: string[] = [];
|
||||
|
||||
console.log('=== DEBUG: Starting beasiswa data insertion process ===');
|
||||
console.log(`Total data items to process: ${data.length}`);
|
||||
console.log('Sample data items:', data.slice(0, 3));
|
||||
|
||||
// First, validate all NIMs exist before processing
|
||||
const uniqueNims = [...new Set(data.map(item => item.nim))];
|
||||
console.log(`Unique NIMs found: ${uniqueNims.length}`);
|
||||
console.log('Unique NIMs:', uniqueNims);
|
||||
|
||||
const nimValidationMap = new Map();
|
||||
|
||||
// Batch check all NIMs for existence
|
||||
console.log('=== DEBUG: Starting NIM validation ===');
|
||||
for (const nim of uniqueNims) {
|
||||
try {
|
||||
console.log(`Checking NIM: ${nim}`);
|
||||
const { data: mahasiswaData, error: checkError } = await supabase
|
||||
.from('mahasiswa')
|
||||
.select('id_mahasiswa, nama')
|
||||
@@ -261,45 +242,28 @@ async function insertDataToDatabase(data: any[]) {
|
||||
.single();
|
||||
|
||||
if (checkError || !mahasiswaData) {
|
||||
console.log(`❌ NIM ${nim}: NOT FOUND in database`);
|
||||
console.log(`Error details:`, checkError);
|
||||
nimValidationMap.set(nim, { exists: false, error: 'Mahasiswa dengan NIM ini tidak ditemukan dalam database' });
|
||||
} else {
|
||||
console.log(`✅ NIM ${nim}: FOUND - ID: ${mahasiswaData.id_mahasiswa}, Nama: ${mahasiswaData.nama}`);
|
||||
nimValidationMap.set(nim, { exists: true, id_mahasiswa: mahasiswaData.id_mahasiswa, nama: mahasiswaData.nama });
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(`❌ NIM ${nim}: ERROR during validation`);
|
||||
console.log(`Error details:`, error);
|
||||
nimValidationMap.set(nim, { exists: false, error: `Error checking NIM: ${(error as Error).message}` });
|
||||
}
|
||||
}
|
||||
|
||||
console.log('=== DEBUG: NIM validation results ===');
|
||||
console.log('Validation map:', Object.fromEntries(nimValidationMap));
|
||||
|
||||
// Process each data item
|
||||
console.log('=== DEBUG: Starting beasiswa data processing ===');
|
||||
for (const item of data) {
|
||||
try {
|
||||
console.log(`\n--- Processing beasiswa item: NIM ${item.nim} ---`);
|
||||
console.log('Item data:', item);
|
||||
|
||||
const nimValidation = nimValidationMap.get(item.nim);
|
||||
console.log('NIM validation result:', nimValidation);
|
||||
|
||||
if (!nimValidation || !nimValidation.exists) {
|
||||
errorCount++;
|
||||
const errorMsg = nimValidation?.error || `NIM ${item.nim}: Mahasiswa dengan NIM ini tidak ditemukan dalam database`;
|
||||
console.log(`❌ Skipping item - ${errorMsg}`);
|
||||
errorMessages.push(errorMsg);
|
||||
continue;
|
||||
}
|
||||
|
||||
console.log(`✅ NIM ${item.nim} is valid, proceeding with beasiswa check/insert`);
|
||||
|
||||
// Check if beasiswa already exists for this mahasiswa and nama_beasiswa
|
||||
console.log(`Checking existing beasiswa for mahasiswa ID: ${nimValidation.id_mahasiswa}, nama_beasiswa: ${item.nama_beasiswa}`);
|
||||
const { data: existingBeasiswa, error: beasiswaCheckError } = await supabase
|
||||
.from('beasiswa_mahasiswa')
|
||||
.select('id_beasiswa')
|
||||
@@ -307,18 +271,12 @@ async function insertDataToDatabase(data: any[]) {
|
||||
.eq('nama_beasiswa', item.nama_beasiswa)
|
||||
.single();
|
||||
|
||||
if (beasiswaCheckError && beasiswaCheckError.code !== 'PGRST116') {
|
||||
console.log(`❌ Error checking existing beasiswa:`, beasiswaCheckError);
|
||||
}
|
||||
|
||||
if (existingBeasiswa) {
|
||||
console.log(`📝 Updating existing beasiswa (ID: ${existingBeasiswa.id_beasiswa})`);
|
||||
// Update existing beasiswa
|
||||
const { error: updateError } = await supabase
|
||||
.from('beasiswa_mahasiswa')
|
||||
.update({
|
||||
sumber_beasiswa: item.sumber_beasiswa,
|
||||
beasiswa_status: item.beasiswa_status,
|
||||
jenis_beasiswa: item.jenis_beasiswa
|
||||
})
|
||||
.eq('id_beasiswa', existingBeasiswa.id_beasiswa);
|
||||
@@ -326,14 +284,10 @@ async function insertDataToDatabase(data: any[]) {
|
||||
if (updateError) {
|
||||
errorCount++;
|
||||
const errorMsg = `NIM ${item.nim} (${nimValidation.nama}): Gagal memperbarui beasiswa: ${updateError.message}`;
|
||||
console.log(`❌ Update failed: ${errorMsg}`);
|
||||
errorMessages.push(errorMsg);
|
||||
continue;
|
||||
} else {
|
||||
console.log(`✅ Beasiswa updated successfully`);
|
||||
}
|
||||
} else {
|
||||
console.log(`📝 Inserting new beasiswa for mahasiswa ID: ${nimValidation.id_mahasiswa}`);
|
||||
// Insert new beasiswa
|
||||
const { error: insertError } = await supabase
|
||||
.from('beasiswa_mahasiswa')
|
||||
@@ -341,34 +295,23 @@ async function insertDataToDatabase(data: any[]) {
|
||||
id_mahasiswa: nimValidation.id_mahasiswa,
|
||||
nama_beasiswa: item.nama_beasiswa,
|
||||
sumber_beasiswa: item.sumber_beasiswa,
|
||||
beasiswa_status: item.beasiswa_status,
|
||||
jenis_beasiswa: item.jenis_beasiswa
|
||||
});
|
||||
|
||||
if (insertError) {
|
||||
errorCount++;
|
||||
const errorMsg = `NIM ${item.nim} (${nimValidation.nama}): Gagal menyimpan beasiswa: ${insertError.message}`;
|
||||
console.log(`❌ Insert failed: ${errorMsg}`);
|
||||
errorMessages.push(errorMsg);
|
||||
continue;
|
||||
} else {
|
||||
console.log(`✅ Beasiswa inserted successfully`);
|
||||
}
|
||||
}
|
||||
|
||||
imported++;
|
||||
console.log(`✅ Item processed successfully. Imported count: ${imported}`);
|
||||
} catch (error) {
|
||||
console.error(`❌ Error processing record for NIM ${item.nim}:`, error);
|
||||
errorCount++;
|
||||
errorMessages.push(`NIM ${item.nim}: Terjadi kesalahan: ${(error as Error).message}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log('=== DEBUG: Final results ===');
|
||||
console.log(`Total imported: ${imported}`);
|
||||
console.log(`Total errors: ${errorCount}`);
|
||||
console.log(`Error messages:`, errorMessages);
|
||||
|
||||
return { imported, errorCount, errorMessages };
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import ClientLayout from '@/components/ClientLayout';
|
||||
|
||||
export default function DashboardLayout({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return <ClientLayout>{children}</ClientLayout>;
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import FilterJenisBeasiswa from "@/components/FilterJenisBeasiswa";
|
||||
import TotalBeasiswaChart from "@/components/charts/TotalBeasiswaChart";
|
||||
import TotalBeasiswaPieChart from "@/components/charts/TotalBeasiswaPieChart";
|
||||
import NamaBeasiswaChart from "@/components/charts/NamaBeasiswaChart";
|
||||
import NamaBeasiswaPieChart from "@/components/charts/NamaBeasiswaPieChart";
|
||||
import JenisPendaftaranBeasiswaChart from "@/components/charts/JenisPendaftaranBeasiswaChart";
|
||||
import JenisPendaftaranBeasiswaPieChart from "@/components/charts/JenisPendaftaranBeasiswaPieChart";
|
||||
import AsalDaerahBeasiswaChart from "@/components/charts/AsalDaerahBeasiswaChart";
|
||||
import IPKBeasiswaChart from "@/components/charts/IPKBeasiswaChart";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function BeasiswaMahasiswaPage() {
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
const [selectedJenisBeasiswa, setSelectedJenisBeasiswa] = useState<string>("Pemerintah");
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-4">Mahasiswa Beasiswa</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<p className="text-gray-600 dark:text-gray-300">
|
||||
Mahasiswa yang mendapatkan beasiswa di program studi Informatika Fakultas Teknik Universitas Tanjungpura.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
<FilterJenisBeasiswa
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
onJenisBeasiswaChange={setSelectedJenisBeasiswa}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<>
|
||||
<TotalBeasiswaChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
<NamaBeasiswaChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
<JenisPendaftaranBeasiswaChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<TotalBeasiswaPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
<NamaBeasiswaPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
<JenisPendaftaranBeasiswaPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AsalDaerahBeasiswaChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
|
||||
{selectedYear === "all" && (
|
||||
<IPKBeasiswaChart
|
||||
selectedJenisBeasiswa={selectedJenisBeasiswa}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import FilterJenisPrestasi from "@/components/FilterJenisPrestasi";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import TotalPrestasiChart from "@/components/charts/TotalPrestasiChart";
|
||||
import TotalPrestasiPieChart from "@/components/charts/TotalPrestasiPieChart";
|
||||
import TingkatPrestasiChart from "@/components/charts/TingkatPrestasiChart";
|
||||
import TingkatPrestasiPieChart from "@/components/charts/TingkatPrestasiPieChart";
|
||||
import JenisPendaftaranPrestasiChart from "@/components/charts/JenisPendaftaranPrestasiChart";
|
||||
import JenisPendaftaranPrestasiPieChart from "@/components/charts/JenisPendaftaranPrestasiPieChart";
|
||||
import AsalDaerahPrestasiChart from "@/components/charts/AsalDaerahPrestasiChart";
|
||||
import IPKPrestasiChart from "@/components/charts/IPKPrestasiChart";
|
||||
|
||||
export default function BerprestasiMahasiswaPage() {
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
const [selectedJenisPrestasi, setSelectedJenisPrestasi] = useState<string>("Akademik");
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-4">Mahasiswa Berprestasi</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<p className="text-gray-600 dark:text-gray-300">
|
||||
Mahasiswa yang mendapatkan prestasi akademik dan non akademik di program studi Informatika Fakultas Teknik Universitas Tanjungpura.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
<FilterJenisPrestasi
|
||||
selectedJenisPrestasi={selectedJenisPrestasi}
|
||||
onJenisPrestasiChange={setSelectedJenisPrestasi}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<>
|
||||
<TotalPrestasiChart selectedJenisPrestasi={selectedJenisPrestasi} />
|
||||
<TingkatPrestasiChart selectedJenisPrestasi={selectedJenisPrestasi} />
|
||||
<JenisPendaftaranPrestasiChart selectedJenisPrestasi={selectedJenisPrestasi} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<TotalPrestasiPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisPrestasi={selectedJenisPrestasi}
|
||||
/>
|
||||
<TingkatPrestasiPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisPrestasi={selectedJenisPrestasi}
|
||||
/>
|
||||
<JenisPendaftaranPrestasiPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedJenisPrestasi={selectedJenisPrestasi}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AsalDaerahPrestasiChart selectedYear={selectedYear} selectedJenisPrestasi={selectedJenisPrestasi} />
|
||||
|
||||
{selectedYear === "all" && (
|
||||
<IPKPrestasiChart selectedJenisPrestasi={selectedJenisPrestasi} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import LulusTepatWaktuChart from "@/components/charts/LulusTepatWaktuChart";
|
||||
import LulusTepatWaktuPieChart from "@/components/charts/LulusTepatWaktuPieChart";
|
||||
import JenisPendaftaranLulusChart from "@/components/charts/JenisPendaftaranLulusChart";
|
||||
import JenisPendaftaranLulusPieChart from "@/components/charts/JenisPendaftaranLulusPieChart";
|
||||
import AsalDaerahLulusChart from "@/components/charts/AsalDaerahLulusChart";
|
||||
import IPKLulusTepatChart from "@/components/charts/IPKLulusTepatChart";
|
||||
|
||||
export default function LulusTepatWaktuPage() {
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-4">Mahasiswa Lulus Tepat Waktu</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<p className="text-gray-600 dark:text-gray-300">
|
||||
Mahasiswa yang lulus tepat waktu sesuai dengan masa studi ≤ 4 tahun program studi Informatika Fakultas Teknik Universitas Tanjungpura.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<>
|
||||
<LulusTepatWaktuChart selectedYear={selectedYear} />
|
||||
<JenisPendaftaranLulusChart selectedYear={selectedYear} />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<LulusTepatWaktuPieChart selectedYear={selectedYear} />
|
||||
<JenisPendaftaranLulusPieChart selectedYear={selectedYear} />
|
||||
</>
|
||||
)}
|
||||
|
||||
<AsalDaerahLulusChart selectedYear={selectedYear} />
|
||||
{selectedYear === "all" && (
|
||||
<IPKLulusTepatChart selectedYear={selectedYear} />
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
'use client';
|
||||
|
||||
export default function ProfilePage() {
|
||||
return (
|
||||
<div className="container mx-auto p-4 w-full max-w-4xl">
|
||||
<div className="text-center text-muted-foreground">
|
||||
Sedang dalam pengembangan :)
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,86 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import FilterStatusKuliah from "@/components/FilterStatusKuliah";
|
||||
import StatusMahasiswaFilterChart from "@/components/charts/StatusMahasiswaFilterChart";
|
||||
import StatusMahasiswaFilterPieChart from "@/components/charts/StatusMahasiswaFilterPieChart";
|
||||
import JenisPendaftaranStatusChart from "@/components/charts/JenisPendaftaranStatusChart";
|
||||
import JenisPendaftaranStatusPieChart from "@/components/charts/JenisPendaftaranStatusPieChart";
|
||||
import AsalDaerahStatusChart from '@/components/charts/AsalDaerahStatusChart';
|
||||
import IpkStatusChart from '@/components/charts/IpkStatusChart';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function StatusMahasiswaPage() {
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
const [selectedStatus, setSelectedStatus] = useState<string>("Aktif");
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-4">Status Mahasiswa</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<p className="text-gray-600 dark:text-gray-300">
|
||||
Mahasiswa status adalah status kuliah mahasiswa program studi Informatika Fakultas Teknik Universitas Tanjungpura.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
<FilterStatusKuliah
|
||||
selectedStatus={selectedStatus}
|
||||
onStatusChange={setSelectedStatus}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<>
|
||||
<StatusMahasiswaFilterChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
<JenisPendaftaranStatusChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<StatusMahasiswaFilterPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
<JenisPendaftaranStatusPieChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AsalDaerahStatusChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
|
||||
{selectedYear === "all" && (
|
||||
<IpkStatusChart
|
||||
selectedYear={selectedYear}
|
||||
selectedStatus={selectedStatus}
|
||||
/>
|
||||
)}
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from "react";
|
||||
import StatistikMahasiswaChart from "@/components/charts/StatistikMahasiswaChart";
|
||||
import StatistikPerAngkatanChart from "@/components/charts/StatistikPerAngkatanChart";
|
||||
import JenisPendaftaranChart from "@/components/charts/JenisPendaftaranChart";
|
||||
import AsalDaerahChart from "@/components/charts/AsalDaerahChart";
|
||||
import IPKChart from "@/components/charts/IPKChart";
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import JenisPendaftaranPerAngkatanChart from "@/components/charts/JenisPendaftaranPerAngkatanChart";
|
||||
import AsalDaerahPerAngkatanChart from "@/components/charts/AsalDaerahPerAngkatanChart";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
|
||||
export default function TotalMahasiswaPage() {
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-4">Total Mahasiswa</h1>
|
||||
|
||||
<div className="mb-4">
|
||||
<p className="text-gray-600 dark:text-gray-300">
|
||||
Mahasiswa total adalah jumlah mahasiswa program studi Informatika Fakultas Teknik Universitas Tanjungpura.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<>
|
||||
<StatistikMahasiswaChart />
|
||||
<JenisPendaftaranChart />
|
||||
<AsalDaerahChart />
|
||||
<IPKChart />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<StatistikPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
<JenisPendaftaranPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
<AsalDaerahPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Users, GraduationCap, Trophy, BookOpen } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTheme } from "next-themes";
|
||||
import StatusMahasiswaChart from "@/components/charts/StatusMahasiswaChart";
|
||||
import StatistikMahasiswaChart from "@/components/charts/StatistikMahasiswaChart";
|
||||
import JenisPendaftaranChart from "@/components/charts/JenisPendaftaranChart";
|
||||
import AsalDaerahChart from "@/components/charts/AsalDaerahChart";
|
||||
import IPKChart from '@/components/charts/IPKChart';
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import StatistikPerAngkatanChart from "@/components/charts/StatistikPerAngkatanChart";
|
||||
import JenisPendaftaranPerAngkatanChart from "@/components/charts/JenisPendaftaranPerAngkatanChart";
|
||||
import AsalDaerahPerAngkatanChart from "@/components/charts/AsalDaerahPerAngkatanChart";
|
||||
|
||||
interface MahasiswaTotal {
|
||||
total_mahasiswa: number;
|
||||
mahasiswa_aktif: number;
|
||||
total_lulus: number;
|
||||
pria_lulus: number;
|
||||
wanita_lulus: number;
|
||||
total_berprestasi: number;
|
||||
prestasi_akademik: number;
|
||||
prestasi_non_akademik: number;
|
||||
ipk_rata_rata_aktif: number;
|
||||
ipk_rata_rata_lulus: number;
|
||||
total_mahasiswa_aktif_lulus: number;
|
||||
}
|
||||
|
||||
// Skeleton loading component
|
||||
const CardSkeleton = () => (
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<div className="h-4 w-24 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
|
||||
<div className="h-4 w-4 bg-gray-200 dark:bg-gray-700 rounded-full animate-pulse"></div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-8 w-16 bg-gray-200 dark:bg-gray-700 rounded animate-pulse mb-2"></div>
|
||||
<div className="flex justify-between">
|
||||
<div className="h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
|
||||
<div className="h-3 w-20 bg-gray-200 dark:bg-gray-700 rounded animate-pulse"></div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
|
||||
export default function DashboardPage() {
|
||||
const { theme } = useTheme();
|
||||
const [mahasiswaData, setMahasiswaData] = useState<MahasiswaTotal>({
|
||||
total_mahasiswa: 0,
|
||||
mahasiswa_aktif: 0,
|
||||
total_lulus: 0,
|
||||
pria_lulus: 0,
|
||||
wanita_lulus: 0,
|
||||
total_berprestasi: 0,
|
||||
prestasi_akademik: 0,
|
||||
prestasi_non_akademik: 0,
|
||||
ipk_rata_rata_aktif: 0,
|
||||
ipk_rata_rata_lulus: 0,
|
||||
total_mahasiswa_aktif_lulus: 0
|
||||
});
|
||||
const [selectedYear, setSelectedYear] = useState<string>("all");
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
// Menggunakan cache API untuk mempercepat loading
|
||||
const cacheKey = 'mahasiswa-total-data';
|
||||
const cachedData = sessionStorage.getItem(cacheKey);
|
||||
const cachedTimestamp = sessionStorage.getItem(`${cacheKey}-timestamp`);
|
||||
|
||||
// Cek apakah data cache masih valid (kurang dari 60 detik)
|
||||
const isCacheValid = cachedTimestamp &&
|
||||
(Date.now() - parseInt(cachedTimestamp)) < 60000;
|
||||
|
||||
if (cachedData && isCacheValid) {
|
||||
setMahasiswaData(JSON.parse(cachedData));
|
||||
}
|
||||
|
||||
// Fetch data total mahasiswa
|
||||
const totalResponse = await fetch('/api/mahasiswa/total', {
|
||||
cache: 'no-store',
|
||||
});
|
||||
|
||||
if (!totalResponse.ok) {
|
||||
throw new Error('Failed to fetch total data');
|
||||
}
|
||||
|
||||
const totalData = await totalResponse.json();
|
||||
setMahasiswaData(totalData);
|
||||
|
||||
// Menyimpan data dan timestamp ke sessionStorage
|
||||
sessionStorage.setItem(cacheKey, JSON.stringify(totalData));
|
||||
sessionStorage.setItem(`${cacheKey}-timestamp`, Date.now().toString());
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'An error occurred');
|
||||
console.error('Error fetching data:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
fetchData();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-8">Dashboard Portal Data Informatika</h1>
|
||||
|
||||
{loading ? (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
<CardSkeleton />
|
||||
</div>
|
||||
) : error ? (
|
||||
<div className="bg-red-50 border-l-4 border-red-500 p-4 mb-4">
|
||||
<div className="flex">
|
||||
<div className="flex-shrink-0">
|
||||
<svg className="h-5 w-5 text-red-500" viewBox="0 0 20 20" fill="currentColor">
|
||||
<path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
|
||||
</svg>
|
||||
</div>
|
||||
<div className="ml-3">
|
||||
<p className="text-sm text-red-700">{error}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4 mb-8">
|
||||
{/* Kartu Total Mahasiswa */}
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Total Mahasiswa
|
||||
</CardTitle>
|
||||
<Users className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold dark:text-white">{mahasiswaData.total_mahasiswa}</div>
|
||||
<div className="flex justify-between mt-2 text-xs text-muted-foreground">
|
||||
<span className="dark:text-white">Aktif: <span className="text-green-500">{mahasiswaData.mahasiswa_aktif}</span></span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Kartu Total Kelulusan */}
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Total Kelulusan
|
||||
</CardTitle>
|
||||
<GraduationCap className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold dark:text-white">{mahasiswaData.total_lulus}</div>
|
||||
<div className="flex justify-between mt-2 text-xs text-muted-foreground">
|
||||
<span className="dark:text-white">Laki-laki: <span className="text-blue-500">{mahasiswaData.pria_lulus}</span></span>
|
||||
<span className="dark:text-white">Perempuan: <span className="text-pink-500">{mahasiswaData.wanita_lulus}</span></span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Kartu Total Prestasi */}
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Mahasiswa Berprestasi
|
||||
</CardTitle>
|
||||
<Trophy className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold dark:text-white">{mahasiswaData.total_berprestasi}</div>
|
||||
<div className="flex justify-between mt-2 text-xs text-muted-foreground">
|
||||
<span className="dark:text-white">Akademik: <span className="text-yellow-500">{mahasiswaData.prestasi_akademik}</span></span>
|
||||
<span className="dark:text-white">Non-Akademik: <span className="text-purple-500">{mahasiswaData.prestasi_non_akademik}</span></span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Kartu Rata-rata IPK */}
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Rata-rata IPK
|
||||
</CardTitle>
|
||||
<BookOpen className="h-4 w-4 text-muted-foreground" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold dark:text-white">{mahasiswaData.mahasiswa_aktif}</div>
|
||||
<div className="flex justify-between mt-2 text-xs text-muted-foreground">
|
||||
<span className="dark:text-white">Aktif: <span className="text-green-500">{mahasiswaData.ipk_rata_rata_aktif}</span></span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Card className="bg-white dark:bg-slate-900 shadow-lg dark:text-white">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium dark:text-white">
|
||||
Filter Data
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row items-start sm:items-center gap-4 sm:space-x-4">
|
||||
<FilterTahunAngkatan
|
||||
selectedYear={selectedYear}
|
||||
onYearChange={setSelectedYear}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{selectedYear === "all" ? (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<StatistikMahasiswaChart />
|
||||
<JenisPendaftaranChart />
|
||||
<StatusMahasiswaChart />
|
||||
<IPKChart />
|
||||
<AsalDaerahChart />
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<StatistikPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
<JenisPendaftaranPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
<AsalDaerahPerAngkatanChart tahunAngkatan={selectedYear} />
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import DataTableBeasiswaMahasiswa from "@/components/datatable/data-table-beasiswa-mahasiswa";
|
||||
|
||||
export default function BeasiswaPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 px-4 md:gap-6 md:py-6">
|
||||
<h1>Beasiswa</h1>
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<DataTableBeasiswaMahasiswa />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import DataTablePrestasiMahasiswa from "@/components/datatable/data-table-prestasi-mahasiswa";
|
||||
|
||||
export default function PrestasiPage() {
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4 px-4 md:gap-6 md:py-6">
|
||||
<h1>Prestasi</h1>
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<DataTablePrestasiMahasiswa />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import type { Metadata } from 'next';
|
||||
import { Geist, Geist_Mono } from 'next/font/google';
|
||||
import './globals.css';
|
||||
import ClientLayout from '@/components/ClientLayout';
|
||||
import { ToastProvider } from "@/components/ui/toast-provider";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: '--font-geist-sans',
|
||||
@@ -33,7 +34,9 @@ export default function RootLayout({
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
</head>
|
||||
<body suppressHydrationWarning className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-screen`}>
|
||||
<ClientLayout>{children}</ClientLayout>
|
||||
<ToastProvider>
|
||||
<ClientLayout>{children}</ClientLayout>
|
||||
</ToastProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -4,15 +4,9 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Users, GraduationCap, Trophy, BookOpen } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTheme } from "next-themes";
|
||||
import StatusMahasiswaChart from "@/components/charts/StatusMahasiswaChart";
|
||||
import StatistikMahasiswaChart from "@/components/charts/StatistikMahasiswaChart";
|
||||
import JenisPendaftaranChart from "@/components/charts/JenisPendaftaranChart";
|
||||
import AsalDaerahChart from "@/components/charts/AsalDaerahChart";
|
||||
import IPKChart from '@/components/charts/IPKChart';
|
||||
import FilterTahunAngkatan from "@/components/FilterTahunAngkatan";
|
||||
import StatistikPerAngkatanChart from "@/components/charts/StatistikPerAngkatanChart";
|
||||
import JenisPendaftaranPerAngkatanChart from "@/components/charts/JenisPendaftaranPerAngkatanChart";
|
||||
import AsalDaerahPerAngkatanChart from "@/components/charts/AsalDaerahPerAngkatanChart";
|
||||
|
||||
interface MahasiswaTotal {
|
||||
total_mahasiswa: number;
|
||||
@@ -108,7 +102,7 @@ export default function DashboardPage() {
|
||||
|
||||
return (
|
||||
<div className="container mx-auto p-4 space-y-6">
|
||||
<h1 className="text-3xl font-bold mb-8">Dashboard Portal Data Informatika</h1>
|
||||
<h1 className="text-3xl font-bold mb-8">Visualisasi Data Mahasiswa Informatika</h1>
|
||||
|
||||
{loading ? (
|
||||
<div className="grid gap-6 md:grid-cols-2 lg:grid-cols-4">
|
||||
|
||||
685
components/datatable/data-table-beasiswa-mahasiswa.tsx
Normal file
685
components/datatable/data-table-beasiswa-mahasiswa.tsx
Normal file
@@ -0,0 +1,685 @@
|
||||
"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,
|
||||
Filter
|
||||
} from "lucide-react";
|
||||
import UploadExcelBeasiswaMahasiswa from "@/components/datatable/upload-file-beasiswa-mahasiswa";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
// Define the BeasiswaMahasiswa type
|
||||
interface BeasiswaMahasiswa {
|
||||
id_beasiswa: number;
|
||||
nim: string;
|
||||
nama: string;
|
||||
nama_beasiswa: string;
|
||||
sumber_beasiswa: string;
|
||||
jenis_beasiswa: "Pemerintah" | "Non-Pemerintah";
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function DataTableBeasiswaMahasiswa() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
|
||||
// State for data
|
||||
const [beasiswaMahasiswa, setBeasiswaMahasiswa] = useState<BeasiswaMahasiswa[]>([]);
|
||||
const [filteredData, setFilteredData] = useState<BeasiswaMahasiswa[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// State for filtering
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [filterJenisBeasiswa, setFilterJenisBeasiswa] = useState<string>("");
|
||||
|
||||
// State for pagination
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [paginatedData, setPaginatedData] = useState<BeasiswaMahasiswa[]>([]);
|
||||
|
||||
// State for form
|
||||
const [formMode, setFormMode] = useState<"add" | "edit">("add");
|
||||
const [formData, setFormData] = useState<Partial<BeasiswaMahasiswa>>({
|
||||
jenis_beasiswa: "Pemerintah"
|
||||
});
|
||||
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(() => {
|
||||
fetchBeasiswaMahasiswa();
|
||||
}, []);
|
||||
|
||||
// Filter data when search term or filter changes
|
||||
useEffect(() => {
|
||||
filterData();
|
||||
}, [searchTerm, filterJenisBeasiswa, beasiswaMahasiswa]);
|
||||
|
||||
// Update paginated data when filtered data or pagination settings change
|
||||
useEffect(() => {
|
||||
paginateData();
|
||||
}, [filteredData, currentPage, pageSize]);
|
||||
|
||||
// Fetch beasiswa mahasiswa data from API
|
||||
const fetchBeasiswaMahasiswa = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
let url = "/api/keloladata/data-beasiswa-mahasiswa";
|
||||
|
||||
// Add filters to URL if they exist
|
||||
const params = new URLSearchParams();
|
||||
if (searchTerm) {
|
||||
params.append("search", searchTerm);
|
||||
}
|
||||
if (filterJenisBeasiswa && filterJenisBeasiswa !== "all") {
|
||||
params.append("jenis_beasiswa", filterJenisBeasiswa);
|
||||
}
|
||||
|
||||
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();
|
||||
setBeasiswaMahasiswa(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 and filters
|
||||
const filterData = () => {
|
||||
let filtered = [...beasiswaMahasiswa];
|
||||
|
||||
// Filter by search term
|
||||
if (searchTerm) {
|
||||
filtered = filtered.filter(
|
||||
(item) =>
|
||||
(item.nim?.toLowerCase() || "").includes(searchTerm.toLowerCase()) ||
|
||||
(item.nama?.toLowerCase() || "").includes(searchTerm.toLowerCase()) ||
|
||||
(item.nama_beasiswa?.toLowerCase() || "").includes(searchTerm.toLowerCase()) ||
|
||||
(item.sumber_beasiswa?.toLowerCase() || "").includes(searchTerm.toLowerCase())
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by jenis beasiswa
|
||||
if (filterJenisBeasiswa && filterJenisBeasiswa !== "all") {
|
||||
filtered = filtered.filter((item) => item.jenis_beasiswa === filterJenisBeasiswa);
|
||||
}
|
||||
|
||||
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({
|
||||
jenis_beasiswa: "Pemerintah"
|
||||
});
|
||||
};
|
||||
|
||||
// Handle form input changes
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Handle select input changes
|
||||
const handleSelectChange = (name: string, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Open form dialog for adding new beasiswa
|
||||
const handleAdd = () => {
|
||||
setFormMode("add");
|
||||
resetForm();
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
// Open form dialog for editing beasiswa
|
||||
const handleEdit = (data: BeasiswaMahasiswa) => {
|
||||
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 beasiswa
|
||||
const response = await fetch("/api/keloladata/data-beasiswa-mahasiswa", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific NIM not found error
|
||||
if (response.status === 404 && responseData.message.includes("tidak terdaftar")) {
|
||||
showError("Gagal!", `NIM ${formData.nim} tidak terdaftar dalam database. Silakan cek kembali NIM yang dimasukkan.`);
|
||||
throw new Error(`NIM ${formData.nim} tidak terdaftar. Silakan cek kembali NIM yang dimasukkan.`);
|
||||
}
|
||||
showError("Gagal!", "Gagal menambahkan beasiswa");
|
||||
throw new Error(responseData.message || "Failed to add beasiswa");
|
||||
}
|
||||
|
||||
// Show success message with student info
|
||||
showSuccess("Berhasil!", "Beasiswa mahasiswa berhasil ditambahkan");
|
||||
} else {
|
||||
// Edit existing beasiswa
|
||||
const response = await fetch(`/api/keloladata/data-beasiswa-mahasiswa?id=${formData.id_beasiswa}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific NIM not found error
|
||||
if (response.status === 404 && responseData.message.includes("tidak terdaftar")) {
|
||||
throw new Error(`NIM ${formData.nim} tidak terdaftar. Silakan cek kembali NIM yang dimasukkan.`);
|
||||
}
|
||||
showError("Gagal!", responseData.message || "Failed to update beasiswa");
|
||||
throw new Error(responseData.message || "Failed to update beasiswa");
|
||||
}
|
||||
|
||||
showSuccess("Berhasil!", "Beasiswa mahasiswa berhasil diperbarui");
|
||||
}
|
||||
|
||||
// Refresh data after successful operation
|
||||
await fetchBeasiswaMahasiswa();
|
||||
setIsDialogOpen(false);
|
||||
resetForm();
|
||||
} catch (err) {
|
||||
console.error("Error submitting form:", err);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete beasiswa
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
|
||||
try {
|
||||
setIsDeleting(true);
|
||||
|
||||
const response = await fetch(`/api/keloladata/data-beasiswa-mahasiswa?id=${deleteId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || "Failed to delete beasiswa");
|
||||
}
|
||||
|
||||
// Refresh data after successful deletion
|
||||
await fetchBeasiswaMahasiswa();
|
||||
setIsDeleteDialogOpen(false);
|
||||
setDeleteId(null);
|
||||
showSuccess("Berhasil!", "Beasiswa mahasiswa berhasil dihapus");
|
||||
} catch (err) {
|
||||
console.error("Error deleting beasiswa:", 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 Beasiswa Mahasiswa</h2>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<UploadExcelBeasiswaMahasiswa onUploadSuccess={fetchBeasiswaMahasiswa} />
|
||||
<Button onClick={handleAdd}>
|
||||
<PlusCircle className="mr-2 h-4 w-4" />
|
||||
Tambah Beasiswa
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<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 NIM, nama, nama beasiswa, atau sumber..."
|
||||
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>
|
||||
<Select
|
||||
value={filterJenisBeasiswa}
|
||||
onValueChange={(value) => setFilterJenisBeasiswa(value)}
|
||||
>
|
||||
<SelectTrigger className="w-[200px]">
|
||||
<SelectValue placeholder="Jenis Beasiswa" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Semua Jenis</SelectItem>
|
||||
<SelectItem value="Pemerintah">Pemerintah</SelectItem>
|
||||
<SelectItem value="Non-Pemerintah">Non-Pemerintah</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</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 className="w-[100px]">NIM</TableHead>
|
||||
<TableHead>Nama</TableHead>
|
||||
<TableHead>Nama Beasiswa</TableHead>
|
||||
<TableHead>Sumber Beasiswa</TableHead>
|
||||
<TableHead>Jenis Beasiswa</TableHead>
|
||||
{/* <TableHead>Tanggal</TableHead> */}
|
||||
<TableHead className="text-right">Aksi</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedData.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={9} className="text-center py-8">
|
||||
Tidak ada data yang sesuai dengan filter
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
paginatedData.map((beasiswa) => (
|
||||
<TableRow key={beasiswa.id_beasiswa}>
|
||||
{/* <TableCell>{beasiswa.id_beasiswa}</TableCell> */}
|
||||
<TableCell className="font-medium">{beasiswa.nim}</TableCell>
|
||||
<TableCell>{beasiswa.nama}</TableCell>
|
||||
<TableCell>{beasiswa.nama_beasiswa}</TableCell>
|
||||
<TableCell>{beasiswa.sumber_beasiswa}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||
beasiswa.jenis_beasiswa === "Pemerintah"
|
||||
? "bg-purple-100 text-purple-800"
|
||||
: "bg-orange-100 text-orange-800"
|
||||
}`}
|
||||
>
|
||||
{beasiswa.jenis_beasiswa}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleEdit(beasiswa)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDeleteConfirm(beasiswa.id_beasiswa)}
|
||||
>
|
||||
<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-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{formMode === "add" ? "Tambah Beasiswa" : "Edit Beasiswa"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nim" className="text-sm font-medium">
|
||||
NIM <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nim"
|
||||
name="nim"
|
||||
value={formData.nim || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
maxLength={11}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nama_beasiswa" className="text-sm font-medium">
|
||||
Nama Beasiswa <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nama_beasiswa"
|
||||
name="nama_beasiswa"
|
||||
value={formData.nama_beasiswa || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="sumber_beasiswa" className="text-sm font-medium">
|
||||
Sumber Beasiswa <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="sumber_beasiswa"
|
||||
name="sumber_beasiswa"
|
||||
value={formData.sumber_beasiswa || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="jenis_beasiswa" className="text-sm font-medium">
|
||||
Jenis Beasiswa <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Select
|
||||
value={formData.jenis_beasiswa || "Pemerintah"}
|
||||
onValueChange={(value) => handleSelectChange("jenis_beasiswa", value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Pemerintah">Pemerintah</SelectItem>
|
||||
<SelectItem value="Non-Pemerintah">Non-Pemerintah</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</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 beasiswa 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>
|
||||
);
|
||||
}
|
||||
@@ -47,7 +47,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import EditJenisPendaftaran from "@/components/datatable/edit-jenis-pendaftaran";
|
||||
import UploadExcelMahasiswa from "@/components/datatable/upload-excel-mahasiswa";
|
||||
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
// Define the Mahasiswa type based on API route structure
|
||||
interface Mahasiswa {
|
||||
nim: string;
|
||||
@@ -68,6 +68,7 @@ interface Mahasiswa {
|
||||
}
|
||||
|
||||
export default function DataTableMahasiswa() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
// State for data
|
||||
const [mahasiswa, setMahasiswa] = useState<Mahasiswa[]>([]);
|
||||
const [filteredData, setFilteredData] = useState<Mahasiswa[]>([]);
|
||||
@@ -161,12 +162,14 @@ export default function DataTableMahasiswa() {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || "Failed to update semesters");
|
||||
}
|
||||
|
||||
|
||||
|
||||
showSuccess("Berhasil!", "Semester mahasiswa aktif berhasil diperbarui");
|
||||
|
||||
// Refresh data after successful update
|
||||
await fetchMahasiswa();
|
||||
} catch (err) {
|
||||
console.error("Error updating semesters:", err);
|
||||
showError("Gagal!", (err as Error).message);
|
||||
} finally {
|
||||
setIsUpdatingSemester(false);
|
||||
}
|
||||
@@ -337,7 +340,7 @@ export default function DataTableMahasiswa() {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || "Failed to add mahasiswa");
|
||||
}
|
||||
|
||||
showSuccess("Data mahasiswa berhasil ditambahkan!");
|
||||
} else {
|
||||
// Edit existing mahasiswa
|
||||
const response = await fetch(`/api/keloladata/data-mahasiswa?nim=${formData.nim}`, {
|
||||
@@ -352,8 +355,8 @@ export default function DataTableMahasiswa() {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || "Failed to update mahasiswa");
|
||||
}
|
||||
|
||||
}
|
||||
showSuccess("Data mahasiswa berhasil diperbarui!");
|
||||
}
|
||||
|
||||
// Refresh data after successful operation
|
||||
await fetchMahasiswa();
|
||||
@@ -361,6 +364,7 @@ export default function DataTableMahasiswa() {
|
||||
resetForm();
|
||||
} catch (err) {
|
||||
console.error("Error submitting form:", err);
|
||||
showError(`Gagal ${formMode === "add" ? "menambahkan" : "memperbarui"} data mahasiswa.`);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
@@ -387,8 +391,10 @@ export default function DataTableMahasiswa() {
|
||||
await fetchMahasiswa();
|
||||
setIsDeleteDialogOpen(false);
|
||||
setDeleteNim(null);
|
||||
showSuccess("Data mahasiswa berhasil dihapus!");
|
||||
} catch (err) {
|
||||
console.error("Error deleting mahasiswa:", err);
|
||||
showError("Gagal menghapus data mahasiswa.");
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
|
||||
797
components/datatable/data-table-prestasi-mahasiswa.tsx
Normal file
797
components/datatable/data-table-prestasi-mahasiswa.tsx
Normal file
@@ -0,0 +1,797 @@
|
||||
"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,
|
||||
Filter,
|
||||
Trophy
|
||||
} from "lucide-react";
|
||||
import UploadFilePrestasiMahasiswa from "@/components/datatable/upload-file-prestasi-mahasiswa";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
// Define the PrestasiMahasiswa type
|
||||
interface PrestasiMahasiswa {
|
||||
id_prestasi: number;
|
||||
nim: string;
|
||||
nama: string;
|
||||
jenis_prestasi: "Akademik" | "Non-Akademik";
|
||||
nama_prestasi: string;
|
||||
tingkat_prestasi: "Kabupaten" | "Provinsi" | "Nasional" | "Internasional";
|
||||
peringkat: string;
|
||||
tanggal_prestasi: string;
|
||||
keterangan: string | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function DataTablePrestasiMahasiswa() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
// State for data
|
||||
const [prestasiMahasiswa, setPrestasiMahasiswa] = useState<PrestasiMahasiswa[]>([]);
|
||||
const [filteredData, setFilteredData] = useState<PrestasiMahasiswa[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// State for filtering
|
||||
const [searchTerm, setSearchTerm] = useState("");
|
||||
const [filterJenisPrestasi, setFilterJenisPrestasi] = useState<string>("");
|
||||
const [filterTingkat, setFilterTingkat] = useState<string>("");
|
||||
|
||||
// State for pagination
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(10);
|
||||
const [paginatedData, setPaginatedData] = useState<PrestasiMahasiswa[]>([]);
|
||||
|
||||
// State for form
|
||||
const [formMode, setFormMode] = useState<"add" | "edit">("add");
|
||||
const [formData, setFormData] = useState<Partial<PrestasiMahasiswa>>({
|
||||
jenis_prestasi: "Akademik",
|
||||
tingkat_prestasi: "Nasional"
|
||||
});
|
||||
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(() => {
|
||||
fetchPrestasiMahasiswa();
|
||||
}, []);
|
||||
|
||||
// Filter data when search term or filter changes
|
||||
useEffect(() => {
|
||||
filterData();
|
||||
}, [searchTerm, filterJenisPrestasi, filterTingkat, prestasiMahasiswa]);
|
||||
|
||||
// Update paginated data when filtered data or pagination settings change
|
||||
useEffect(() => {
|
||||
paginateData();
|
||||
}, [filteredData, currentPage, pageSize]);
|
||||
|
||||
// Fetch prestasi mahasiswa data from API
|
||||
const fetchPrestasiMahasiswa = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
let url = "/api/keloladata/data-prestasi-mahasiswa";
|
||||
|
||||
// Add filters to URL if they exist
|
||||
const params = new URLSearchParams();
|
||||
if (searchTerm) {
|
||||
params.append("search", searchTerm);
|
||||
}
|
||||
if (filterJenisPrestasi && filterJenisPrestasi !== "all") {
|
||||
params.append("jenis_prestasi", filterJenisPrestasi);
|
||||
}
|
||||
if (filterTingkat && filterTingkat !== "all") {
|
||||
params.append("tingkat_prestasi", filterTingkat);
|
||||
}
|
||||
|
||||
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();
|
||||
setPrestasiMahasiswa(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 and filters
|
||||
const filterData = () => {
|
||||
let filtered = [...prestasiMahasiswa];
|
||||
|
||||
// Filter by search term
|
||||
if (searchTerm) {
|
||||
filtered = filtered.filter(
|
||||
(item) =>
|
||||
(item.nim && item.nim.toLowerCase().includes(searchTerm.toLowerCase())) ||
|
||||
(item.nama && item.nama.toLowerCase().includes(searchTerm.toLowerCase())) ||
|
||||
(item.nama_prestasi && item.nama_prestasi.toLowerCase().includes(searchTerm.toLowerCase())) ||
|
||||
(item.peringkat && item.peringkat.toLowerCase().includes(searchTerm.toLowerCase())) ||
|
||||
(item.keterangan && item.keterangan.toLowerCase().includes(searchTerm.toLowerCase()))
|
||||
);
|
||||
}
|
||||
|
||||
// Filter by jenis prestasi
|
||||
if (filterJenisPrestasi && filterJenisPrestasi !== "all") {
|
||||
filtered = filtered.filter((item) => item.jenis_prestasi === filterJenisPrestasi);
|
||||
}
|
||||
|
||||
// Filter by tingkat
|
||||
if (filterTingkat && filterTingkat !== "all") {
|
||||
filtered = filtered.filter((item) => item.tingkat_prestasi === filterTingkat);
|
||||
}
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
// Format date for display
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleDateString("id-ID", {
|
||||
day: "numeric",
|
||||
month: "long",
|
||||
year: "numeric",
|
||||
});
|
||||
};
|
||||
|
||||
// Reset form data
|
||||
const resetForm = () => {
|
||||
setFormData({
|
||||
jenis_prestasi: "Akademik",
|
||||
tingkat_prestasi: "Nasional"
|
||||
});
|
||||
};
|
||||
|
||||
// Handle form input changes
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
|
||||
const { name, value } = e.target;
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Handle select input changes
|
||||
const handleSelectChange = (name: string, value: string) => {
|
||||
setFormData((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
// Open form dialog for adding new prestasi
|
||||
const handleAdd = () => {
|
||||
setFormMode("add");
|
||||
resetForm();
|
||||
setIsDialogOpen(true);
|
||||
};
|
||||
|
||||
// Open form dialog for editing prestasi
|
||||
const handleEdit = (data: PrestasiMahasiswa) => {
|
||||
setFormMode("edit");
|
||||
// Format the date for the input field (YYYY-MM-DD)
|
||||
const formattedData = {
|
||||
...data,
|
||||
tanggal_prestasi: new Date(data.tanggal_prestasi).toISOString().split('T')[0]
|
||||
};
|
||||
setFormData(formattedData);
|
||||
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 prestasi
|
||||
const response = await fetch("/api/keloladata/data-prestasi-mahasiswa", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific NIM not found error
|
||||
if (response.status === 404 && responseData.message.includes("tidak terdaftar")) {
|
||||
throw new Error(`NIM ${formData.nim} tidak terdaftar dalam database. Silakan cek kembali NIM yang dimasukkan.`);
|
||||
}
|
||||
throw new Error(responseData.message || "Failed to add prestasi");
|
||||
}
|
||||
|
||||
// Show success message with student info
|
||||
showSuccess("Berhasil!", "Prestasi mahasiswa berhasil ditambahkan");
|
||||
} else {
|
||||
// Edit existing prestasi
|
||||
const response = await fetch(`/api/keloladata/data-prestasi-mahasiswa?id=${formData.id_prestasi}`, {
|
||||
method: "PUT",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
const responseData = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
// Handle specific NIM not found error
|
||||
if (response.status === 404 && responseData.message.includes("tidak terdaftar")) {
|
||||
throw new Error(`NIM ${formData.nim} tidak terdaftar dalam database. Silakan cek kembali NIM yang dimasukkan.`);
|
||||
}
|
||||
throw new Error(responseData.message || "Failed to update prestasi");
|
||||
}
|
||||
|
||||
showSuccess("Berhasil!", "Prestasi mahasiswa berhasil diperbarui");
|
||||
}
|
||||
|
||||
// Refresh data after successful operation
|
||||
await fetchPrestasiMahasiswa();
|
||||
setIsDialogOpen(false);
|
||||
resetForm();
|
||||
} catch (err) {
|
||||
console.error("Error submitting form:", err);
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
// Delete prestasi
|
||||
const handleDelete = async () => {
|
||||
if (!deleteId) return;
|
||||
|
||||
try {
|
||||
setIsDeleting(true);
|
||||
|
||||
const response = await fetch(`/api/keloladata/data-prestasi-mahasiswa?id=${deleteId}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json();
|
||||
throw new Error(errorData.message || "Failed to delete prestasi");
|
||||
}
|
||||
|
||||
// Refresh data after successful deletion
|
||||
await fetchPrestasiMahasiswa();
|
||||
setIsDeleteDialogOpen(false);
|
||||
setDeleteId(null);
|
||||
showSuccess("Berhasil!", "Prestasi mahasiswa berhasil dihapus");
|
||||
} catch (err) {
|
||||
console.error("Error deleting prestasi:", 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 };
|
||||
};
|
||||
|
||||
// Get badge color based on tingkat
|
||||
const getTingkatBadgeColor = (tingkat: string) => {
|
||||
switch (tingkat) {
|
||||
case "Kabupaten":
|
||||
return "bg-green-100 text-green-800";
|
||||
case "Provinsi":
|
||||
return "bg-blue-100 text-blue-800";
|
||||
case "Nasional":
|
||||
return "bg-purple-100 text-purple-800";
|
||||
case "Internasional":
|
||||
return "bg-red-100 text-red-800";
|
||||
default:
|
||||
return "bg-gray-100 text-gray-800";
|
||||
}
|
||||
};
|
||||
|
||||
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 Prestasi Mahasiswa</h2>
|
||||
<div className="flex flex-col sm:flex-row gap-2">
|
||||
<UploadFilePrestasiMahasiswa onUploadSuccess={fetchPrestasiMahasiswa} />
|
||||
<Button onClick={handleAdd}>
|
||||
<PlusCircle className="mr-2 h-4 w-4" />
|
||||
Tambah Prestasi
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Filters */}
|
||||
<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 NIM, nama, nama prestasi, peringkat..."
|
||||
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>
|
||||
<Select
|
||||
value={filterJenisPrestasi}
|
||||
onValueChange={(value) => setFilterJenisPrestasi(value)}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Jenis Prestasi" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Semua Jenis</SelectItem>
|
||||
<SelectItem value="Akademik">Akademik</SelectItem>
|
||||
<SelectItem value="Non-Akademik">Non-Akademik</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select
|
||||
value={filterTingkat}
|
||||
onValueChange={(value) => setFilterTingkat(value)}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Tingkat" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Semua Tingkat</SelectItem>
|
||||
<SelectItem value="Kabupaten">Kabupaten</SelectItem>
|
||||
<SelectItem value="Provinsi">Provinsi</SelectItem>
|
||||
<SelectItem value="Nasional">Nasional</SelectItem>
|
||||
<SelectItem value="Internasional">Internasional</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</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 className="w-[100px]">NIM</TableHead>
|
||||
<TableHead>Nama</TableHead>
|
||||
<TableHead>Jenis</TableHead>
|
||||
<TableHead>Nama Prestasi</TableHead>
|
||||
<TableHead>Tingkat</TableHead>
|
||||
<TableHead>Peringkat</TableHead>
|
||||
<TableHead>Tanggal</TableHead>
|
||||
<TableHead className="text-right">Aksi</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{paginatedData.length === 0 ? (
|
||||
<TableRow>
|
||||
<TableCell colSpan={9} className="text-center py-8">
|
||||
Tidak ada data yang sesuai dengan filter
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
) : (
|
||||
paginatedData.map((prestasi) => (
|
||||
<TableRow key={prestasi.id_prestasi}>
|
||||
{/* <TableCell>{prestasi.id_prestasi}</TableCell> */}
|
||||
<TableCell className="font-medium">{prestasi.nim}</TableCell>
|
||||
<TableCell>{prestasi.nama}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${
|
||||
prestasi.jenis_prestasi === "Akademik"
|
||||
? "bg-blue-100 text-blue-800"
|
||||
: "bg-orange-100 text-orange-800"
|
||||
}`}
|
||||
>
|
||||
{prestasi.jenis_prestasi}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>{prestasi.nama_prestasi}</TableCell>
|
||||
<TableCell>
|
||||
<span
|
||||
className={`px-2 py-1 rounded-full text-xs font-medium ${getTingkatBadgeColor(prestasi.tingkat_prestasi)}`}
|
||||
>
|
||||
{prestasi.tingkat_prestasi}
|
||||
</span>
|
||||
</TableCell>
|
||||
<TableCell>{prestasi.peringkat}</TableCell>
|
||||
<TableCell>{formatDate(prestasi.tanggal_prestasi)}</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<div className="flex justify-end gap-2">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => handleEdit(prestasi)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="text-destructive hover:bg-destructive/10"
|
||||
onClick={() => handleDeleteConfirm(prestasi.id_prestasi)}
|
||||
>
|
||||
<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-[600px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{formMode === "add" ? "Tambah Prestasi" : "Edit Prestasi"}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div className="grid gap-4 py-4">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nim" className="text-sm font-medium">
|
||||
NIM <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nim"
|
||||
name="nim"
|
||||
value={formData.nim || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
maxLength={11}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="jenis_prestasi" className="text-sm font-medium">
|
||||
Jenis Prestasi <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Select
|
||||
value={formData.jenis_prestasi || "Akademik"}
|
||||
onValueChange={(value) => handleSelectChange("jenis_prestasi", value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Akademik">Akademik</SelectItem>
|
||||
<SelectItem value="Non-Akademik">Non-Akademik</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="nama_prestasi" className="text-sm font-medium">
|
||||
Nama Prestasi <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="nama_prestasi"
|
||||
name="nama_prestasi"
|
||||
value={formData.nama_prestasi || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="tingkat_prestasi" className="text-sm font-medium">
|
||||
Tingkat <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Select
|
||||
value={formData.tingkat_prestasi || "Nasional"}
|
||||
onValueChange={(value) => handleSelectChange("tingkat_prestasi", value)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="Kabupaten">Kabupaten</SelectItem>
|
||||
<SelectItem value="Provinsi">Provinsi</SelectItem>
|
||||
<SelectItem value="Nasional">Nasional</SelectItem>
|
||||
<SelectItem value="Internasional">Internasional</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="peringkat" className="text-sm font-medium">
|
||||
Peringkat <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="peringkat"
|
||||
name="peringkat"
|
||||
value={formData.peringkat || ""}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Contoh: Juara 1, Medali Emas, Finalis"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label htmlFor="tanggal_prestasi" className="text-sm font-medium">
|
||||
Tanggal Prestasi <span className="text-destructive">*</span>
|
||||
</label>
|
||||
<Input
|
||||
id="tanggal_prestasi"
|
||||
name="tanggal_prestasi"
|
||||
type="date"
|
||||
value={formData.tanggal_prestasi || ""}
|
||||
onChange={handleInputChange}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2 sm:col-span-2">
|
||||
<label htmlFor="keterangan" className="text-sm font-medium">
|
||||
Keterangan
|
||||
</label>
|
||||
<textarea
|
||||
id="keterangan"
|
||||
name="keterangan"
|
||||
className="w-full min-h-[100px] px-3 py-2 rounded-md border border-input bg-background ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
|
||||
value={formData.keterangan || ""}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Informasi tambahan tentang prestasi"
|
||||
/>
|
||||
</div>
|
||||
</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 prestasi 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>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
SelectValue
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, Settings } from "lucide-react";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
interface JenisPendaftaran {
|
||||
jenis_pendaftaran: string;
|
||||
@@ -29,7 +30,7 @@ interface EditJenisPendaftaranProps {
|
||||
}
|
||||
|
||||
export default function EditJenisPendaftaran({ onUpdateSuccess }: EditJenisPendaftaranProps) {
|
||||
// Toast hook
|
||||
const { showSuccess, showError } = useToast();
|
||||
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [jenisPendaftaranList, setJenisPendaftaranList] = useState<JenisPendaftaran[]>([]);
|
||||
@@ -124,7 +125,8 @@ export default function EditJenisPendaftaran({ onUpdateSuccess }: EditJenisPenda
|
||||
await fetchJenisPendaftaran();
|
||||
|
||||
// Show success message
|
||||
|
||||
showSuccess("Berhasil!", "Jenis pendaftaran berhasil diperbarui");
|
||||
|
||||
// Close dialog
|
||||
setIsDialogOpen(false);
|
||||
|
||||
@@ -135,6 +137,7 @@ export default function EditJenisPendaftaran({ onUpdateSuccess }: EditJenisPenda
|
||||
} catch (err) {
|
||||
setError((err as Error).message);
|
||||
console.error("Error updating jenis pendaftaran:", err);
|
||||
showError("Gagal!", (err as Error).message);
|
||||
} finally {
|
||||
setUpdating(false);
|
||||
}
|
||||
|
||||
@@ -16,12 +16,14 @@ import {
|
||||
Loader2,
|
||||
AlertCircle
|
||||
} from "lucide-react";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
|
||||
interface UploadExcelMahasiswaProps {
|
||||
onUploadSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function UploadExcelMahasiswa({ onUploadSuccess }: UploadExcelMahasiswaProps) {
|
||||
const { showSuccess, showError } = useToast();
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
@@ -78,7 +80,7 @@ export default function UploadExcelMahasiswa({ onUploadSuccess }: UploadExcelMah
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch('/api/data-mahasiswa/upload', {
|
||||
const response = await fetch('/api/keloladata/data-mahasiswa/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
@@ -92,10 +94,11 @@ export default function UploadExcelMahasiswa({ onUploadSuccess }: UploadExcelMah
|
||||
setIsDialogOpen(false);
|
||||
setFile(null);
|
||||
onUploadSuccess();
|
||||
|
||||
showSuccess("Berhasil!", "Data mahasiswa berhasil diunggah");
|
||||
} catch (err) {
|
||||
console.error('Error uploading file:', err);
|
||||
setError((err as Error).message || 'Terjadi kesalahan saat mengunggah file');
|
||||
showError("Gagal!", (err as Error).message);
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
|
||||
160
components/datatable/upload-file-beasiswa-mahasiswa.tsx
Normal file
160
components/datatable/upload-file-beasiswa-mahasiswa.tsx
Normal file
@@ -0,0 +1,160 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
DialogClose
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
FileUp,
|
||||
Loader2,
|
||||
AlertCircle
|
||||
} from "lucide-react";
|
||||
|
||||
interface UploadFileBeasiswaMahasiswaProps {
|
||||
onUploadSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function UploadFileBeasiswaMahasiswa({ onUploadSuccess }: UploadFileBeasiswaMahasiswaProps) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFile = e.target.files?.[0];
|
||||
setError(null);
|
||||
|
||||
if (!selectedFile) {
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check file type
|
||||
const fileType = selectedFile.type;
|
||||
const validTypes = [
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/csv',
|
||||
'application/csv',
|
||||
'text/plain'
|
||||
];
|
||||
|
||||
if (!validTypes.includes(fileType) &&
|
||||
!selectedFile.name.endsWith('.xlsx') &&
|
||||
!selectedFile.name.endsWith('.xls') &&
|
||||
!selectedFile.name.endsWith('.csv')) {
|
||||
setError("Format file tidak valid. Harap unggah file Excel (.xlsx, .xls) atau CSV (.csv)");
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check file size (max 5MB)
|
||||
if (selectedFile.size > 5 * 1024 * 1024) {
|
||||
setError("Ukuran file terlalu besar. Maksimum 5MB");
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setFile(selectedFile);
|
||||
};
|
||||
|
||||
const handleUpload = async () => {
|
||||
if (!file) {
|
||||
setError("Pilih file terlebih dahulu");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUploading(true);
|
||||
setError(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch('/api/keloladata/data-beasiswa-mahasiswa/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.message || 'Terjadi kesalahan saat mengunggah file');
|
||||
}
|
||||
|
||||
setIsDialogOpen(false);
|
||||
setFile(null);
|
||||
onUploadSuccess();
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error uploading file:', err);
|
||||
setError((err as Error).message || 'Terjadi kesalahan saat mengunggah file');
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<FileUp className="mr-2 h-4 w-4" />
|
||||
Upload Beasiswa
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Data Beasiswa Mahasiswa</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>Upload file Excel (.xlsx, .xls) atau CSV (.csv)</p>
|
||||
</div>
|
||||
|
||||
<div className="grid w-full max-w-sm items-center gap-1.5">
|
||||
<label htmlFor="file-upload" className="text-sm font-medium">
|
||||
Pilih File
|
||||
</label>
|
||||
<input
|
||||
id="file-upload"
|
||||
type="file"
|
||||
className="file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 text-sm text-muted-foreground"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{file && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
File terpilih: {file.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-destructive/10 text-destructive text-sm p-2 rounded-md flex items-start">
|
||||
<AlertCircle className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Batal
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button onClick={handleUpload} disabled={!file || isUploading}>
|
||||
{isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Upload
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
161
components/datatable/upload-file-prestasi-mahasiswa.tsx
Normal file
161
components/datatable/upload-file-prestasi-mahasiswa.tsx
Normal file
@@ -0,0 +1,161 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
DialogFooter,
|
||||
DialogClose
|
||||
} from "@/components/ui/dialog";
|
||||
import {
|
||||
FileUp,
|
||||
Loader2,
|
||||
AlertCircle
|
||||
} from "lucide-react";
|
||||
|
||||
interface UploadFilePrestasiMahasiswaProps {
|
||||
onUploadSuccess: () => void;
|
||||
}
|
||||
|
||||
export default function UploadFilePrestasiMahasiswa({ onUploadSuccess }: UploadFilePrestasiMahasiswaProps) {
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const [isUploading, setIsUploading] = useState(false);
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const selectedFile = e.target.files?.[0];
|
||||
setError(null);
|
||||
|
||||
if (!selectedFile) {
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check file type
|
||||
const fileType = selectedFile.type;
|
||||
const validTypes = [
|
||||
'application/vnd.ms-excel',
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'text/csv',
|
||||
'application/csv',
|
||||
'text/plain'
|
||||
];
|
||||
|
||||
if (!validTypes.includes(fileType) &&
|
||||
!selectedFile.name.endsWith('.xlsx') &&
|
||||
!selectedFile.name.endsWith('.xls') &&
|
||||
!selectedFile.name.endsWith('.csv')) {
|
||||
setError("Format file tidak valid. Harap unggah file Excel (.xlsx, .xls) atau CSV (.csv)");
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check file size (max 5MB)
|
||||
if (selectedFile.size > 5 * 1024 * 1024) {
|
||||
setError("Ukuran file terlalu besar. Maksimum 5MB");
|
||||
setFile(null);
|
||||
return;
|
||||
}
|
||||
|
||||
setFile(selectedFile);
|
||||
};
|
||||
|
||||
const handleUpload = async () => {
|
||||
if (!file) {
|
||||
setError("Pilih file terlebih dahulu");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setIsUploading(true);
|
||||
setError(null);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
|
||||
const response = await fetch('/api/keloladata/data-prestasi-mahasiswa/upload', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(result.message || 'Terjadi kesalahan saat mengunggah file');
|
||||
}
|
||||
|
||||
setIsDialogOpen(false);
|
||||
setFile(null);
|
||||
onUploadSuccess();
|
||||
|
||||
} catch (err) {
|
||||
console.error('Error uploading file:', err);
|
||||
setError((err as Error).message || 'Terjadi kesalahan saat mengunggah file');
|
||||
} finally {
|
||||
setIsUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<FileUp className="mr-2 h-4 w-4" />
|
||||
Upload Prestasi
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Upload Data Prestasi Mahasiswa</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="text-sm text-muted-foreground">
|
||||
<p>Upload file Excel (.xlsx, .xls) atau CSV (.csv)</p>
|
||||
<p className="mt-1">Format kolom: NIM, Jenis Prestasi, Nama Prestasi, Tingkat Prestasi, Peringkat, Tanggal (DD-MM-YYYY, DD/MM/YYYY, atau YYYY-MM-DD)</p>
|
||||
</div>
|
||||
|
||||
<div className="grid w-full max-w-sm items-center gap-1.5">
|
||||
<label htmlFor="file-upload" className="text-sm font-medium">
|
||||
Pilih File
|
||||
</label>
|
||||
<input
|
||||
id="file-upload"
|
||||
type="file"
|
||||
className="file:mr-4 file:py-2 file:px-4 file:rounded-md file:border-0 file:text-sm file:font-semibold file:bg-primary file:text-primary-foreground hover:file:bg-primary/90 text-sm text-muted-foreground"
|
||||
accept=".xlsx,.xls,.csv"
|
||||
onChange={handleFileChange}
|
||||
/>
|
||||
{file && (
|
||||
<p className="text-xs text-muted-foreground mt-1">
|
||||
File terpilih: {file.name}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="bg-destructive/10 text-destructive text-sm p-2 rounded-md flex items-start">
|
||||
<AlertCircle className="h-4 w-4 mr-2 mt-0.5 flex-shrink-0" />
|
||||
<span>{error}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
Batal
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button onClick={handleUpload} disabled={!file || isUploading}>
|
||||
{isUploading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
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, School, GraduationCap, Clock, BookOpen, Award, Home, LogOut, User } from 'lucide-react';
|
||||
import { Menu, ChevronDown, BarChart, Database, School, GraduationCap, Clock, BookOpen, Award, Home, LogOut, User } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Sheet, SheetContent, SheetTrigger } from '@/components/ui/sheet';
|
||||
import {
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import Link from 'next/link';
|
||||
import LoginDialog from './login-dialog';
|
||||
import { useToast } from '@/components/ui/use-toast';
|
||||
import { useToast } from '@/components/ui/toast-provider';
|
||||
|
||||
interface UserData {
|
||||
id_user: number;
|
||||
@@ -27,7 +27,7 @@ interface UserData {
|
||||
const Navbar = () => {
|
||||
const [user, setUser] = useState<UserData | null>(null);
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const { toast } = useToast();
|
||||
const { showSuccess, showError } = useToast ();
|
||||
const router = useRouter();
|
||||
|
||||
// Check for existing user session on mount
|
||||
@@ -61,20 +61,13 @@ const Navbar = () => {
|
||||
|
||||
if (response.ok) {
|
||||
setUser(null);
|
||||
toast({
|
||||
title: "Logout Berhasil",
|
||||
description: "Anda telah keluar dari sistem",
|
||||
});
|
||||
showSuccess("Berhasil!", "Anda telah keluar dari sistem");
|
||||
// Redirect to root page after successful logout
|
||||
router.push('/');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Terjadi kesalahan saat logout",
|
||||
});
|
||||
showError("Gagal!", "Terjadi kesalahan saat logout");
|
||||
}
|
||||
};
|
||||
|
||||
@@ -111,7 +104,7 @@ const Navbar = () => {
|
||||
<div className="hidden md:flex items-center gap-4">
|
||||
{/* Beranda - Always visible */}
|
||||
<Link href="/" className="flex items-center gap-2 px-3 py-2 text-sm font-medium hover:text-primary transition-colors">
|
||||
<Home className="h-4 w-4" />
|
||||
<School className="h-4 w-4" />
|
||||
Beranda
|
||||
</Link>
|
||||
|
||||
@@ -120,7 +113,7 @@ const Navbar = () => {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="flex items-center gap-2 px-3 py-2 text-sm font-medium">
|
||||
<School className="h-4 w-4" />
|
||||
<BarChart className="h-4 w-4" />
|
||||
Visualisasi
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -165,7 +158,7 @@ const Navbar = () => {
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" className="flex items-center gap-2 px-3 py-2 text-sm font-medium">
|
||||
<School className="h-4 w-4" />
|
||||
<Database className="h-4 w-4" />
|
||||
Kelola Data
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
@@ -189,12 +182,6 @@ const Navbar = () => {
|
||||
Prestasi
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link href="/keloladata/kelompokkeahlian" className="flex items-center gap-2 w-full">
|
||||
<Award className="h-4 w-4" />
|
||||
Kelompok Keahlian
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
@@ -202,7 +189,6 @@ const Navbar = () => {
|
||||
|
||||
{/* Right Side - Theme Toggle, Login/User Menu, and Mobile Menu */}
|
||||
<div className="flex items-center gap-4">
|
||||
<ThemeToggle />
|
||||
|
||||
{user ? (
|
||||
<DropdownMenu>
|
||||
@@ -215,7 +201,7 @@ const Navbar = () => {
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuItem disabled>
|
||||
<User className="h-4 w-4 mr-2" />
|
||||
{user.role_user === 'ketuajurusan' ? user.nip : user.username}
|
||||
{user.role_user === 'ketuajurusan' ? user.username : user.username}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem onClick={handleLogout}>
|
||||
@@ -227,6 +213,7 @@ const Navbar = () => {
|
||||
) : (
|
||||
<LoginDialog onLoginSuccess={handleLoginSuccess} />
|
||||
)}
|
||||
<ThemeToggle />
|
||||
|
||||
{/* Mobile Menu Button */}
|
||||
<div className="md:hidden">
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { useToast } from "@/components/ui/toast-provider";
|
||||
import { LogIn, User, Key } from "lucide-react";
|
||||
|
||||
interface LoginDialogProps {
|
||||
@@ -20,9 +20,10 @@ interface LoginDialogProps {
|
||||
}
|
||||
|
||||
export default function LoginDialog({ onLoginSuccess }: LoginDialogProps) {
|
||||
const { showSuccess, showError } = useToast();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
|
||||
// Ketua Jurusan form state
|
||||
const [ketuaForm, setKetuaForm] = useState({
|
||||
@@ -56,26 +57,15 @@ export default function LoginDialog({ onLoginSuccess }: LoginDialogProps) {
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: "Login Berhasil",
|
||||
description: "Selamat datang, Ketua Jurusan!",
|
||||
});
|
||||
showSuccess("Berhasil!", "Selamat datang, Ketua Jurusan!");
|
||||
onLoginSuccess(data);
|
||||
setIsOpen(false);
|
||||
setKetuaForm({ nip: "", password: "" });
|
||||
} else {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Login Gagal",
|
||||
description: data.message || "NIP atau password salah",
|
||||
});
|
||||
showError("Gagal!", data.message || "NIP atau password salah");
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Terjadi kesalahan saat login",
|
||||
});
|
||||
showError("Gagal!", "Terjadi kesalahan saat login");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
@@ -101,26 +91,15 @@ export default function LoginDialog({ onLoginSuccess }: LoginDialogProps) {
|
||||
const data = await response.json();
|
||||
|
||||
if (response.ok) {
|
||||
toast({
|
||||
title: "Login Berhasil",
|
||||
description: "Selamat datang, Admin!",
|
||||
});
|
||||
showSuccess("Berhasil!", "Selamat datang, Admin!");
|
||||
onLoginSuccess(data);
|
||||
setIsOpen(false);
|
||||
setAdminForm({ username: "", password: "" });
|
||||
} else {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Login Gagal",
|
||||
description: data.message || "Username atau password salah",
|
||||
});
|
||||
showError("Gagal!", data.message || "Username atau password salah");
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
variant: "destructive",
|
||||
title: "Error",
|
||||
description: "Terjadi kesalahan saat login",
|
||||
});
|
||||
showError("Gagal!", "Terjadi kesalahan saat login");
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
|
||||
135
components/ui/toast-provider.tsx
Normal file
135
components/ui/toast-provider.tsx
Normal file
@@ -0,0 +1,135 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext, useState, useCallback } from "react";
|
||||
import { Toast, ToastTitle, ToastDescription, ToastClose } from "./toast";
|
||||
import { CheckCircle, AlertCircle, AlertTriangle, Info, X } from "lucide-react";
|
||||
|
||||
interface ToastMessage {
|
||||
id: string;
|
||||
type: "success" | "error" | "warning" | "info";
|
||||
title: string;
|
||||
description?: string;
|
||||
duration?: number;
|
||||
}
|
||||
|
||||
interface ToastContextType {
|
||||
showToast: (message: Omit<ToastMessage, "id">) => void;
|
||||
showSuccess: (title: string, description?: string) => void;
|
||||
showError: (title: string, description?: string) => void;
|
||||
showWarning: (title: string, description?: string) => void;
|
||||
showInfo: (title: string, description?: string) => void;
|
||||
}
|
||||
|
||||
const ToastContext = createContext<ToastContextType | undefined>(undefined);
|
||||
|
||||
export const useToast = () => {
|
||||
const context = useContext(ToastContext);
|
||||
if (!context) {
|
||||
throw new Error("useToast must be used within a ToastProvider");
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
interface ToastProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const ToastProvider: React.FC<ToastProviderProps> = ({ children }) => {
|
||||
const [toasts, setToasts] = useState<ToastMessage[]>([]);
|
||||
|
||||
const removeToast = useCallback((id: string) => {
|
||||
setToasts((prev) => prev.filter((toast) => toast.id !== id));
|
||||
}, []);
|
||||
|
||||
const showToast = useCallback((message: Omit<ToastMessage, "id">) => {
|
||||
const id = Math.random().toString(36).substr(2, 9);
|
||||
const newToast: ToastMessage = {
|
||||
...message,
|
||||
id,
|
||||
duration: message.duration || 5000,
|
||||
};
|
||||
|
||||
setToasts((prev) => [...prev, newToast]);
|
||||
|
||||
// Auto remove toast after duration
|
||||
setTimeout(() => {
|
||||
removeToast(id);
|
||||
}, newToast.duration);
|
||||
}, [removeToast]);
|
||||
|
||||
const showSuccess = useCallback((title: string, description?: string) => {
|
||||
showToast({ type: "success", title, description });
|
||||
}, [showToast]);
|
||||
|
||||
const showError = useCallback((title: string, description?: string) => {
|
||||
showToast({ type: "error", title, description });
|
||||
}, [showToast]);
|
||||
|
||||
const showWarning = useCallback((title: string, description?: string) => {
|
||||
showToast({ type: "warning", title, description });
|
||||
}, [showToast]);
|
||||
|
||||
const showInfo = useCallback((title: string, description?: string) => {
|
||||
showToast({ type: "info", title, description });
|
||||
}, [showToast]);
|
||||
|
||||
const getToastVariant = (type: ToastMessage["type"]) => {
|
||||
switch (type) {
|
||||
case "success":
|
||||
return "success";
|
||||
case "error":
|
||||
return "destructive";
|
||||
case "warning":
|
||||
return "warning";
|
||||
case "info":
|
||||
return "info";
|
||||
default:
|
||||
return "default";
|
||||
}
|
||||
};
|
||||
|
||||
const getToastIcon = (type: ToastMessage["type"]) => {
|
||||
switch (type) {
|
||||
case "success":
|
||||
return <CheckCircle className="h-5 w-5 text-green-600" />;
|
||||
case "error":
|
||||
return <AlertCircle className="h-5 w-5 text-red-600" />;
|
||||
case "warning":
|
||||
return <AlertTriangle className="h-5 w-5 text-yellow-600" />;
|
||||
case "info":
|
||||
return <Info className="h-5 w-5 text-blue-600" />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ToastContext.Provider
|
||||
value={{ showToast, showSuccess, showError, showWarning, showInfo }}
|
||||
>
|
||||
{children}
|
||||
|
||||
{/* Toast Container */}
|
||||
<div className="fixed top-4 right-4 z-50 space-y-2">
|
||||
{toasts.map((toast) => (
|
||||
<Toast
|
||||
key={toast.id}
|
||||
variant={getToastVariant(toast.type)}
|
||||
className="min-w-[300px]"
|
||||
>
|
||||
<div className="flex items-start space-x-3">
|
||||
{getToastIcon(toast.type)}
|
||||
<div className="flex-1">
|
||||
<ToastTitle>{toast.title}</ToastTitle>
|
||||
{toast.description && (
|
||||
<ToastDescription>{toast.description}</ToastDescription>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<ToastClose onClick={() => removeToast(toast.id)} />
|
||||
</Toast>
|
||||
))}
|
||||
</div>
|
||||
</ToastContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -1,63 +1,48 @@
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
"use client";
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
const ToastProvider = ToastPrimitives.Provider
|
||||
|
||||
const ToastViewport = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Viewport>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastViewport.displayName = ToastPrimitives.Viewport.displayName
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
import { X, CheckCircle, AlertCircle, AlertTriangle, Info } from "lucide-react";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const toastVariants = cva(
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[swipe=end]:slide-out-to-right-full sm:data-[state=open]:slide-in-from-bottom-full",
|
||||
"group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border bg-background text-foreground",
|
||||
destructive:
|
||||
"destructive group border-destructive bg-destructive text-destructive-foreground",
|
||||
"destructive border-destructive bg-destructive text-destructive-foreground",
|
||||
success: "border-green-200 bg-green-50 text-green-900",
|
||||
warning: "border-yellow-200 bg-yellow-50 text-yellow-900",
|
||||
info: "border-blue-200 bg-blue-50 text-blue-900",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
||||
VariantProps<typeof toastVariants>
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(toastVariants({ variant }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
})
|
||||
Toast.displayName = ToastPrimitives.Root.displayName
|
||||
);
|
||||
});
|
||||
Toast.displayName = "Toast";
|
||||
|
||||
const ToastAction = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Action>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
|
||||
HTMLButtonElement,
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Action
|
||||
<button
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
|
||||
@@ -65,14 +50,14 @@ const ToastAction = React.forwardRef<
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastAction.displayName = ToastPrimitives.Action.displayName
|
||||
));
|
||||
ToastAction.displayName = "ToastAction";
|
||||
|
||||
const ToastClose = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Close>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Close>
|
||||
HTMLButtonElement,
|
||||
React.ButtonHTMLAttributes<HTMLButtonElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Close
|
||||
<button
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
|
||||
@@ -82,46 +67,55 @@ const ToastClose = React.forwardRef<
|
||||
{...props}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</ToastPrimitives.Close>
|
||||
))
|
||||
ToastClose.displayName = ToastPrimitives.Close.displayName
|
||||
</button>
|
||||
));
|
||||
ToastClose.displayName = "ToastClose";
|
||||
|
||||
const ToastTitle = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Title>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Title
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastTitle.displayName = ToastPrimitives.Title.displayName
|
||||
));
|
||||
ToastTitle.displayName = "ToastTitle";
|
||||
|
||||
const ToastDescription = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Description>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<ToastPrimitives.Description
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn("text-sm opacity-90", className)}
|
||||
{...props}
|
||||
/>
|
||||
))
|
||||
ToastDescription.displayName = ToastPrimitives.Description.displayName
|
||||
));
|
||||
ToastDescription.displayName = "ToastDescription";
|
||||
|
||||
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>
|
||||
const ToastViewport = React.forwardRef<
|
||||
HTMLDivElement,
|
||||
React.HTMLAttributes<HTMLDivElement>
|
||||
>(({ className, ...props }, ref) => (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
));
|
||||
ToastViewport.displayName = "ToastViewport";
|
||||
|
||||
type ToastActionElement = React.ReactElement<typeof ToastAction>
|
||||
const ToastProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
return <>{children}</>;
|
||||
};
|
||||
ToastProvider.displayName = "ToastProvider";
|
||||
|
||||
export {
|
||||
type ToastProps,
|
||||
type ToastActionElement,
|
||||
ToastProvider,
|
||||
ToastViewport,
|
||||
Toast,
|
||||
ToastTitle,
|
||||
ToastDescription,
|
||||
ToastClose,
|
||||
ToastAction,
|
||||
}
|
||||
export { Toast, ToastAction, ToastClose, ToastTitle, ToastDescription, ToastViewport, ToastProvider };
|
||||
|
||||
export type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
|
||||
export type ToastActionElement = React.ReactElement<typeof ToastAction>;
|
||||
164
components/ui/toast/README.md
Normal file
164
components/ui/toast/README.md
Normal file
@@ -0,0 +1,164 @@
|
||||
# Toast Notification Component
|
||||
|
||||
Komponen toast notification yang dinamis menggunakan Lucide React icons.
|
||||
|
||||
## Fitur
|
||||
|
||||
- ✅ 4 jenis toast: Success, Error, Warning, Info
|
||||
- ✅ Auto-dismiss setelah durasi tertentu
|
||||
- ✅ Manual close dengan tombol X
|
||||
- ✅ Animasi smooth
|
||||
- ✅ Responsive design
|
||||
- ✅ TypeScript support
|
||||
- ✅ Context-based state management
|
||||
|
||||
## Cara Penggunaan
|
||||
|
||||
### 1. Setup Provider
|
||||
|
||||
Bungkus aplikasi Anda dengan `ToastProvider`:
|
||||
|
||||
```tsx
|
||||
import { ToastProvider } from "@/components/ui/toast";
|
||||
|
||||
export default function RootLayout({ children }) {
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
<ToastProvider>{children}</ToastProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Gunakan Hook useToast
|
||||
|
||||
```tsx
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
|
||||
export default function MyComponent() {
|
||||
const { showSuccess, showError, showWarning, showInfo } = useToast();
|
||||
|
||||
const handleSuccess = () => {
|
||||
showSuccess("Berhasil!", "Data telah disimpan dengan sukses.");
|
||||
};
|
||||
|
||||
const handleError = () => {
|
||||
showError("Gagal!", "Terjadi kesalahan saat menyimpan data.");
|
||||
};
|
||||
|
||||
const handleWarning = () => {
|
||||
showWarning("Peringatan!", "Data akan dihapus secara permanen.");
|
||||
};
|
||||
|
||||
const handleInfo = () => {
|
||||
showInfo("Informasi", "Sistem sedang dalam maintenance.");
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={handleSuccess}>Show Success</button>
|
||||
<button onClick={handleError}>Show Error</button>
|
||||
<button onClick={handleWarning}>Show Warning</button>
|
||||
<button onClick={handleInfo}>Show Info</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Custom Toast
|
||||
|
||||
```tsx
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
|
||||
export default function MyComponent() {
|
||||
const { showToast } = useToast();
|
||||
|
||||
const handleCustomToast = () => {
|
||||
showToast({
|
||||
type: "success",
|
||||
title: "Custom Toast",
|
||||
description: "Ini adalah toast kustom dengan durasi 10 detik",
|
||||
duration: 10000, // 10 detik
|
||||
});
|
||||
};
|
||||
|
||||
return <button onClick={handleCustomToast}>Show Custom Toast</button>;
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### useToast Hook
|
||||
|
||||
```tsx
|
||||
const {
|
||||
showToast, // Fungsi umum untuk menampilkan toast
|
||||
showSuccess, // Menampilkan toast success
|
||||
showError, // Menampilkan toast error
|
||||
showWarning, // Menampilkan toast warning
|
||||
showInfo, // Menampilkan toast info
|
||||
} = useToast();
|
||||
```
|
||||
|
||||
### showToast Parameters
|
||||
|
||||
```tsx
|
||||
showToast({
|
||||
type: "success" | "error" | "warning" | "info",
|
||||
title: string,
|
||||
description: string,
|
||||
duration: number, // dalam milliseconds, default: 5000
|
||||
});
|
||||
```
|
||||
|
||||
### showSuccess/showError/showWarning/showInfo Parameters
|
||||
|
||||
```tsx
|
||||
showSuccess(title: string, description?: string);
|
||||
showError(title: string, description?: string);
|
||||
showWarning(title: string, description?: string);
|
||||
showInfo(title: string, description?: string);
|
||||
```
|
||||
|
||||
## Styling
|
||||
|
||||
Toast menggunakan Tailwind CSS dengan variant yang dapat dikustomisasi:
|
||||
|
||||
- `success`: Green theme
|
||||
- `error`: Red theme (destructive)
|
||||
- `warning`: Yellow theme
|
||||
- `info`: Blue theme
|
||||
- `default`: Default theme
|
||||
|
||||
## Contoh Integrasi dengan Form
|
||||
|
||||
```tsx
|
||||
import { useToast } from "@/components/ui/toast";
|
||||
|
||||
export default function MyForm() {
|
||||
const { showSuccess, showError } = useToast();
|
||||
|
||||
const handleSubmit = async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/data", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(formData),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
showSuccess("Berhasil!", "Data telah disimpan.");
|
||||
} else {
|
||||
showError("Gagal!", "Terjadi kesalahan saat menyimpan data.");
|
||||
}
|
||||
} catch (error) {
|
||||
showError("Error!", "Koneksi terputus.");
|
||||
}
|
||||
};
|
||||
|
||||
return <form onSubmit={handleSubmit}>{/* form fields */}</form>;
|
||||
}
|
||||
```
|
||||
2
components/ui/toast/index.ts
Normal file
2
components/ui/toast/index.ts
Normal file
@@ -0,0 +1,2 @@
|
||||
export { Toast, ToastAction, ToastClose, ToastTitle, ToastDescription } from "../toast";
|
||||
export { ToastProvider, useToast } from "../toast-provider";
|
||||
@@ -14,6 +14,8 @@ type ToasterToast = ToastProps & {
|
||||
title?: React.ReactNode
|
||||
description?: React.ReactNode
|
||||
action?: ToastActionElement
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
}
|
||||
|
||||
const actionTypes = {
|
||||
@@ -26,7 +28,7 @@ const actionTypes = {
|
||||
let count = 0
|
||||
|
||||
function genId() {
|
||||
count = (count + 1) % Number.MAX_VALUE
|
||||
count = (count + 1) % Number.MAX_SAFE_INTEGER
|
||||
return count.toString()
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user