"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, formatDate } 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"; import DatePicker from "react-datepicker"; 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: "customCreatorName" }, { name: "Status", uid: "isPublish" }, { name: "Aksi", uid: "actions" }, ]; const columnsOtherRole = [ { name: "No", uid: "no" }, { name: "Judul", uid: "title" }, { name: "Source", uid: "source" }, { name: "Kategori", uid: "category" }, { name: "Tanggal Unggah", uid: "createdAt" }, { name: "Kreator", uid: "customCreatorName" }, { name: "Status", uid: "publishStatus" }, { 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 [selectedCategoryId, setSelectedCategoryId] = useState(""); const [selectedSource, setSelectedSource] = useState(""); const [selectedStatus, setSelectedStatus] = useState(""); const [dateRange, setDateRange] = useState({ startDate: null, endDate: null, }); useEffect(() => { initState(); getCategories(); }, []); async function getCategories() { const res = await getArticleByCategory(); const data = res?.data?.data; setCategories(data); console.log("category", data); } useEffect(() => { initState(); }, [ page, showData, search, selectedCategoryId, selectedSource, dateRange, selectedStatus, ]); async function initState() { loading(); const req = { limit: showData, page: page, search: search, category: selectedCategoryId || "", source: selectedSource || "", isPublish: selectedStatus !== "" ? selectedStatus === "publish" : undefined, startDate: formatDate(dateRange.startDate), endDate: formatDate(dateRange.endDate), sort: "desc", sortBy: "created_at", }; const res = await getArticlePagination(req); let data = res.data?.data || []; await getTableNumber(parseInt(showData), data); setTotalPage(res?.data?.meta?.totalPage); close(); } // panggil ulang setiap state berubah useEffect(() => { initState(); }, [page, showData, search, selectedCategories]); 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 (slug: any) => { const url = `${window.location.protocol}//${window.location.host}` + "/details/" + `${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 "customCreatorName": return (

{article.customCreatorName && article.customCreatorName.trim() !== "" ? article.customCreatorName : article.createdByName}

); case "publishStatus": return ( // //
// {article.status} //
//

{article.publishStatus}

); 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.slug)} > Copy Url Article Detail Edit {username === "admin-mabes" && ( handleBanner(article.id, !article.isBanner) } > {article.isBanner ? "Hapus dari Banner" : "Jadikan Banner"} )} 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

Source

Status

Tanggal

{ setDateRange({ startDate: update[0], endDate: update[1], }); }} isClearable dateFormat="dd/MM/yyyy" className="z-50 w-full text-sm bg-transparent border border-gray-200 px-2 py-[6px] rounded-xl h-[40px] text-gray-600 dark:text-gray-300" placeholderText="Pilih rentang tanggal" />
{(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)} />
); }