"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"; import { EditBannerDialog } from "../form/banner-edit-dialog"; import { deleteProduct, getProductPagination, approveProduct, rejectProduct, } from "@/service/product"; import { CheckCheck, Eye, X } from "lucide-react"; import { useRouter } from "next/navigation"; 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 ProductTable() { 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, }); const [userRoleId, setUserRoleId] = useState(null); const router = useRouter(); // 🔹 Ambil userRoleId dari cookies useEffect(() => { const urie = Cookies.get("urie"); // userRoleId dari cookies setUserRoleId(urie ?? 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, }; const res = await getProductPagination(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 deleteProduct(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 [openEditDialog, setOpenEditDialog] = useState(false); const [selectedBanner, setSelectedBanner] = useState(null); const [openPreview, setOpenPreview] = useState(false); const [previewImage, setPreviewImage] = useState(null); const handleUpdateBanner = (data: any) => { console.log("Updated banner data:", data); // TODO: panggil API update di sini // lalu refresh tabel }; const handlePreview = (imgUrl: string) => { setPreviewImage(imgUrl); setOpenPreview(true); }; const handleApproveProduct = async (id: number) => { loading(); const res = await approveProduct(id); if (res?.error) { error(res.message || "Gagal menyetujui product"); close(); return; } close(); success("Product berhasil disetujui"); initState(); // refresh table }; const handleRejectProduct = async (id: number) => { const MySwal = withReactContent(Swal); const { value: message } = await MySwal.fire({ title: "Tolak Product", input: "textarea", inputLabel: "Alasan penolakan (opsional)", inputPlaceholder: "Masukkan alasan penolakan...", inputAttributes: { "aria-label": "Masukkan alasan penolakan", }, showCancelButton: true, confirmButtonText: "Tolak", cancelButtonText: "Batal", confirmButtonColor: "#dc2626", }); if (message === undefined) { return; // User cancelled } loading(); const res = await rejectProduct(id, message || undefined); if (res?.error) { error(res.message || "Gagal menolak product"); close(); return; } close(); success("Product berhasil ditolak"); initState(); // refresh table }; 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(); } const formatRupiah = (value?: number | string) => { if (!value) return "Rp 0"; const number = typeof value === "string" ? Number(value.replace(/[^\d]/g, "")) : value; return `Rp ${number.toLocaleString("id-ID")}`; }; return ( <>
{/* Header */}
Daftar Product
{/* Table */} {/* HEADER */} NO NAMA HARGA PRODUK VARIAN BANNER PRODUK STATUS AKSI {/* BODY */} {article.length > 0 ? ( article.map((item, index) => ( {/* NO */} {index + 1} {/* NAMA */} {item.title ?? "—"}
{/* {item.isPublish ? ( Tampil di Landing ) : ( Draft )} */}
{/* HARGA PRODUK */} {formatRupiah(item.price)} {/* VARIAN */} {item.variant ?? "-"} {/* BANNER PRODUK */} {item.thumbnail_url ? ( {item.title} ) : (
No Image
)}
{/* STATUS */} {item.status_id === 1 ? ( Menunggu ) : item.status_id === 2 ? ( Disetujui ) : item.status_id === 3 ? ( Ditolak ) : ( {item.status_id || "Tidak Diketahui"} )} {/* AKSI */}
{userRoleId !== "1" && ( )} {userRoleId === "1" && item.status_id === 1 && ( <> )}
)) ) : ( Tidak ada data untuk ditampilkan. )}
{/* FOOTER PAGINATION */}

Menampilkan {article.length} dari {article.length} data

Halaman {page} dari {totalPage}

{/* Preview Dialog */} {openPreview && (
setOpenPreview(false)} >
e.stopPropagation()} > {/* HEADER */}
{/* Tombol close */}

JAEC00 J7 SHS-P

DELICATE OFF-ROAD SUV

{/* Status badge */}
Menunggu 1
{/* IMAGE PREVIEW */}
Preview
{/* FOOTER */}
)} ); }