Add Kelola Data
This commit is contained in:
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