"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 { Eye, Trash2, CheckCheck } from "lucide-react"; import AgentDetailDialog from "../dialog/agent-dialog"; import PromoDetailDialog from "../dialog/promo-dialog"; import { deletePromotion, getPromotionPagination, approvePromotion, } from "@/service/promotion"; 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 PromotionTable() { 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 [openDetail, setOpenDetail] = useState(false); const [selectedPromo, setPromoDetail] = useState(null); const [selectedPromoId, setSelectedPromoId] = useState(null); const [startDateValue, setStartDateValue] = useState({ startDate: null, endDate: null, }); const [userLevelId, setUserLevelId] = useState(null); // 🔹 Ambil userlevelId dari cookies useEffect(() => { const ulne = Cookies.get("ulne"); // contoh: "3" setUserLevelId(ulne ?? null); }, []); useEffect(() => { initState(); }, []); const initState = useCallback(async () => { loading(); const req = { limit: showData, page: page, search: search, }; const res = await getPromotionPagination(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 deletePromotion(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 handleApprovePromotion = async (id: number) => { loading(); const res = await approvePromotion(id); if (res?.error) { error(res.message || "Gagal menyetujui promotion"); close(); return; } close(); success("Promotion berhasil disetujui"); 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(); } return ( <>
{/* Header */}
Daftar Product
{/* Table */} {/* HEADER */} NO DOKUMEN TANGGAL UPLOAD STATUS AKSI {/* BODY */} {article.length > 0 ? ( article.map((item, index) => ( {/* NO */} {index + 1} {/* NAMA */} {item.title ?? "—"} {/* HARGA PRODUK */} {new Date(item.created_at) .toLocaleDateString("id-ID") .replace(/\//g, "-")} {/* BANNER PRODUK */} {/* STATUS */} {item.status_id === 1 ? ( Menunggu ) : item.status_id === 2 ? ( Disetujui ) : ( {item.status_id || "Tidak Diketahui"} )} {/* AKSI */}
{/* Tombol Lihat */} {/* Tombol Edit */} {/* Tombol Approve - hanya untuk admin dan status pending */} {/* {userLevelId === "1" && item.status_id === 1 && ( )} */} {/* Tombol Hapus */}
)) ) : ( 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 */}
)} ); }