"use client"; import { BannerIcon, CopyIcon, CreateIconIon, DeleteIcon, DotsYIcon, EyeIconMdi, SearchIcon, } from "@/components/icons"; import { close, error, loading, success, successToast } from "@/config/swal"; import { Article } from "@/types/globals"; import { convertDateFormat } from "@/utils/global"; import Link from "next/link"; import { Key, useCallback, useEffect, useState } from "react"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import Cookies from "js-cookie"; import { deleteArticle, getArticleByCategory, getArticlePagination, updateIsBannerArticle, } from "@/service/article"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "../ui/dropdown-menu"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem, } from "@/components/ui/select"; import { Table, TableHeader, TableBody, TableRow, TableHead, TableCell, } from "@/components/ui/table"; import CustomPagination from "../layout/custom-pagination"; const columns = [ { name: "No", uid: "no" }, { name: "Judul", uid: "title" }, { name: "Banner", uid: "isBanner" }, { name: "Kategori", uid: "category" }, { name: "Tanggal Unggah", uid: "createdAt" }, { name: "Kreator", uid: "createdByName" }, { name: "Status", uid: "isPublish" }, { name: "Aksi", uid: "actions" }, ]; const columnsOtherRole = [ { name: "No", uid: "no" }, { name: "Judul", uid: "title" }, { name: "Kategori", uid: "category" }, { name: "Tanggal Unggah", uid: "createdAt" }, { name: "Kreator", uid: "createdByName" }, { name: "Status", uid: "isPublish" }, { name: "Aksi", uid: "actions" }, ]; // interface Category { // id: number; // title: string; // } export default function ArticleTable() { const MySwal = withReactContent(Swal); const username = Cookies.get("username"); const userId = Cookies.get("uie"); const [page, setPage] = useState(1); const [totalPage, setTotalPage] = useState(1); const [article, setArticle] = useState([]); const [showData, setShowData] = useState("10"); const [search, setSearch] = useState(""); const [categories, setCategories] = useState([]); const [selectedCategories, setSelectedCategories] = useState(""); const [startDateValue, setStartDateValue] = useState({ startDate: null, endDate: null, }); useEffect(() => { initState(); getCategories(); }, []); async function getCategories() { const res = await getArticleByCategory(); const data = res?.data?.data; setCategories(data); } const initState = useCallback(async () => { loading(); const req = { limit: showData, page: page, search: search, // startDate: // startDateValue.startDate === null ? "" : startDateValue.startDate, // endDate: startDateValue.endDate === null ? "" : startDateValue.endDate, categorySlug: Array.from(selectedCategories).join(","), sort: "desc", sortBy: "created_at", }; const res = await getArticlePagination(req); await getTableNumber(parseInt(showData), res.data?.data); setTotalPage(res?.data?.meta?.totalPage); close(); }, [page]); const getTableNumber = async (limit: number, data: Article[]) => { if (data) { const startIndex = limit * (page - 1); let iterate = 0; const newData = data.map((value: any) => { iterate++; value.no = startIndex + iterate; return value; }); setArticle(newData); } else { setArticle([]); } }; async function doDelete(id: any) { // loading(); const resDelete = await deleteArticle(id); if (resDelete?.error) { error(resDelete.message); return false; } close(); success("Berhasil Hapus"); initState(); } const handleDelete = (id: any) => { MySwal.fire({ title: "Hapus Data", icon: "warning", showCancelButton: true, cancelButtonColor: "#3085d6", confirmButtonColor: "#d33", confirmButtonText: "Hapus", }).then((result) => { if (result.isConfirmed) { doDelete(id); } }); }; const handleBanner = async (id: number, status: boolean) => { const res = await updateIsBannerArticle(id, status); if (res?.error) { error(res?.message); return false; } initState(); }; const copyUrlArticle = async (id: number, slug: string) => { const url = `${window.location.protocol}//${window.location.host}` + "/news/detail/" + `${id}-${slug}`; try { await navigator.clipboard.writeText(url); successToast("Success", "Article Copy to Clipboard"); setTimeout(() => {}, 1500); } catch (err) { ("Failed to copy!"); } }; const renderCell = useCallback( (article: any, columnKey: Key) => { const cellValue = article[columnKey as keyof any]; switch (columnKey) { case "isPublish": return ( // //
// {article.status} //
//

{article.isPublish ? "Publish" : "Draft"}

); case "isBanner": return

{article.isBanner ? "Ya" : "Tidak"}

; case "createdAt": return

{convertDateFormat(article.createdAt)}

; case "category": return (

{article?.categories?.map((list: any) => list.title).join(", ") + " "}

); case "actions": return (
copyUrlArticle(article.id, article.slug)} > Copy Url Article Detail {(username === "admin-mabes" || Number(userId) === article.createdById) && ( Edit )} {username === "admin-mabes" && ( handleBanner(article.id, !article.isBanner) } > {article.isBanner ? "Hapus dari Banner" : "Jadikan Banner"} )} {(username === "admin-mabes" || Number(userId) === article.createdById) && ( handleDelete(article.id)}> Delete )}
); default: return cellValue; } }, [article, page] ); let typingTimer: NodeJS.Timeout; const doneTypingInterval = 1500; const handleKeyUp = () => { clearTimeout(typingTimer); typingTimer = setTimeout(doneTyping, doneTypingInterval); }; const handleKeyDown = () => { clearTimeout(typingTimer); }; async function doneTyping() { setPage(1); initState(); } return ( <>

Pencarian

setSearch(e.target.value)} onKeyUp={handleKeyUp} onKeyDown={handleKeyDown} />

Data

Kategori

{/*

Tanggal

setStartDateValue(e)} inputClassName="z-50 w-full text-sm bg-transparent border-1 border-gray-200 px-2 py-[6px] rounded-xl h-[40px] text-gray-600 dark:text-gray-300" />
*/}
{(username === "admin-mabes" ? columns : columnsOtherRole ).map((column) => ( {column.name} ))} {article.length > 0 ? ( article.map((item: any) => ( {(username === "admin-mabes" ? columns : columnsOtherRole ).map((column) => ( {renderCell(item, column.uid)} ))} )) ) : ( No data to display. )}
{/* setPage(page)} /> */} setPage(data)} />
); }