"use client"; import { BannerIcon, CloudUploadIcon, CreateIconIon, DeleteIcon, DotsYIcon, ExportIcon, EyeIconMdi, SearchIcon, TimesIcon, } from "@/components/icons"; import { close, error, loading, success } from "@/config/swal"; import { deleteArticle, getArticleByCategory, getListArticle, } from "@/services/article"; import { Article } from "@/types/globals"; import { convertDateFormat, convertDateFormatNoTime, convertDateFormatNoTimeV2, getUnixTimestamp, } from "@/utils/global"; import { Button } from "@heroui/button"; import { Calendar, Chip, ChipProps, Dropdown, DropdownItem, DropdownMenu, DropdownTrigger, Input, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader, Pagination, Popover, PopoverContent, PopoverTrigger, Select, SelectItem, Spinner, Switch, Table, TableBody, TableCell, TableColumn, TableHeader, TableRow, Textarea, useDisclosure, } from "@heroui/react"; import Link from "next/link"; import { Fragment, Key, useCallback, useEffect, useState } from "react"; import Cookies from "js-cookie"; import * as z from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; import { Controller, useForm } from "react-hook-form"; import Swal from "sweetalert2"; import withReactContent from "sweetalert2-react-content"; import { useDropzone } from "react-dropzone"; import Image from "next/image"; import SuggestionsChart from "@/components/main/dashboard/chart/suggestions-line-chart"; import { parseDate } from "@internationalized/date"; import { deleteFeedback, getFeedbacks, getFeedbacksById, } from "@/services/feedbacks"; import * as XLSX from "xlsx"; import { Document, Packer, Paragraph, Table as DocxTable, TableCell as DocxTableCell, TableRow as DocxTableRow, TextRun, WidthType, } from "docx"; import { timeStamp } from "console"; interface ExportData { no: string; commentFromName: string; commentFromEmail: string; message: string; } const columns = [ { name: "No", uid: "no" }, { name: "Nama", uid: "commentFromName" }, { name: "Email", uid: "commentFromEmail" }, { name: "Kritik & Saran", uid: "message" }, { name: "Aksi", uid: "actions" }, ]; const createArticleSchema = z.object({ id: z.string().optional(), commentFromName: z.string().min(2, { message: "Nama harus diisi", }), commentFromEmail: z.string().min(2, { message: "Email harus diisi", }), description: z.string().min(2, { message: "Pesan harus diisi", }), file: z.string().optional(), }); export default function SuggestionsTable() { const MySwal = withReactContent(Swal); const { isOpen, onOpen, onOpenChange, onClose } = useDisclosure(); const [page, setPage] = useState(1); const [totalPage, setTotalPage] = useState(1); const [article, setArticle] = useState([]); const [showData, setShowData] = useState("10"); const [search, setSearch] = useState(""); const [isReply, setIsReply] = useState(false); const [replyValue, setReplyValue] = useState(""); const [totalData, setTotalData] = useState(0); const [feedbackDate, setFeedbackDate] = useState({ startDate: parseDate( convertDateFormatNoTimeV2( new Date(new Date().setDate(new Date().getDate() - 7)) ) ), endDate: parseDate(convertDateFormatNoTimeV2(new Date())), }); const formOptions = { resolver: zodResolver(createArticleSchema), defaultValues: { commentFromName: "", description: "", commentFromEmail: "", file: "", }, }; type UserSettingSchema = z.infer; const { control, handleSubmit, setValue, formState: { errors }, } = useForm(formOptions); useEffect(() => { initState(); }, [page, showData, feedbackDate]); async function initState() { const getDate = (data: any) => { return `${data.year}-${data.month < 10 ? `0${data.month}` : data.month}-${ data.day < 10 ? `0${data.day}` : data.day }`; }; const res = await getFeedbacks({ limit: showData, search: search, startDate: getDate(feedbackDate.startDate), endDate: getDate(feedbackDate.endDate), timeStamp: getUnixTimestamp(), }); getTableNumber(parseInt(showData), res.data?.data); setTotalPage(res?.data?.meta?.totalPage); } const getTableNumber = (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: number) { loading(); const resDelete = await deleteFeedback(id); if (resDelete?.error) { error(resDelete.message); return false; } close(); success("Berhasil Hapus"); initState(); } const handleDelete = (id: number) => { MySwal.fire({ title: "Hapus Data", icon: "warning", showCancelButton: true, cancelButtonColor: "#3085d6", confirmButtonColor: "#d33", confirmButtonText: "Hapus", }).then((result) => { if (result.isConfirmed) { doDelete(id); } }); }; const onSubmit = async (values: z.infer) => { loading(); const formData = { commentFromName: values.commentFromName, message: values.description, commentFromEmail: values.commentFromEmail, }; console.log("dataas", formData); close(); // setRefresh(!refresh); // MySwal.fire({ // title: "Sukses", // icon: "success", // confirmButtonColor: "#3085d6", // confirmButtonText: "OK", // }).then((result) => { // if (result.isConfirmed) { // } // }); }; const openModal = async (id: number) => { const res = await getFeedbacksById(id); const data = res?.data?.data; setValue("id", String(data?.id)); setValue("commentFromName", data?.commentFromName); setValue("commentFromEmail", data?.commentFromEmail); setValue("description", data?.message); onOpen(); }; const getMonthYearName = (date: any) => { const newDate = new Date(date); const months = [ "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember", ]; const year = newDate.getFullYear(); const month = months[newDate.getMonth()]; return month + " " + year; }; const renderCell = useCallback( (suggestion: any, columnKey: Key) => { const cellValue = suggestion[columnKey as keyof any]; switch (columnKey) { case "actions": return (
{/* Detail */} openModal(suggestion.id)} > Detail exportToWord({ no: suggestion.no, commentFromName: suggestion.commentFromName, commentFromEmail: suggestion.commentFromEmail, message: suggestion.message, }) } > Export handleDelete(suggestion.id)} > Delete
); default: return cellValue; } }, [article] ); let typingTimer: NodeJS.Timeout; const doneTypingInterval = 1500; const handleKeyUp = () => { clearTimeout(typingTimer); typingTimer = setTimeout(doneTyping, doneTypingInterval); }; const handleKeyDown = () => { clearTimeout(typingTimer); }; async function doneTyping() { initState(); } const [startDateValue, setStartDateValue] = useState( parseDate(convertDateFormatNoTimeV2(new Date())) ); const [typeDate, setTypeDate] = useState("monthly"); const doExport = async () => { const res = await getFeedbacks({ limit: showData, search: search, timeStamp: getUnixTimestamp(), }); if (res?.data?.data) { exportRecap(res?.data?.data); } }; const exportRecap = (data: any) => { let temp: any = []; let no = 0; const worksheet = XLSX.utils.json_to_sheet([]); data.map((list: any) => { no += 1; const now = [ no, list.commentFromName, list.commentFromEmail, list.message, ]; temp.push(now); }); XLSX.utils.sheet_add_aoa( worksheet, [["No", "Nama", "Email", "Kritik & Saran"]], { origin: "A1", } ); XLSX.utils.sheet_add_json(worksheet, temp, { origin: "A2", skipHeader: true, }); worksheet["!cols"] = [{ wch: 7 }, { wch: 24 }, { wch: 24 }, { wch: 48 }]; const workbook = XLSX.utils.book_new(); XLSX.utils.book_append_sheet(workbook, worksheet, "ethic"); XLSX.writeFile(workbook, `Kritik Saran.xlsx`); }; const exportToWord = async (data: ExportData) => { const tableRows = [ new DocxTableRow({ children: ["No", "Nama", "Email", "Kritik & Saran"].map( (text) => new DocxTableCell({ children: [ new Paragraph({ children: [new TextRun({ text, bold: true })], }), ], width: { size: 25, type: WidthType.PERCENTAGE }, }) ), }), ]; tableRows.push( new DocxTableRow({ children: [ String(data.no) || "", data.commentFromName || "", data.commentFromEmail || "", data.message || "", ].map( (text) => new DocxTableCell({ children: [new Paragraph(text)], width: { size: 25, type: WidthType.PERCENTAGE }, }) ), }) ); const doc = new Document({ sections: [ { children: [ new Paragraph({ text: "Kritik & Saran", heading: "Heading1", }), new DocxTable({ rows: tableRows, width: { size: 100, type: WidthType.PERCENTAGE, }, }), ], }, ], }); const blob = await Packer.toBlob(doc); const url = URL.createObjectURL(blob); const link = document.createElement("a"); link.href = url; link.download = "KritikSaran.docx"; document.body.appendChild(link); link.click(); document.body.removeChild(link); URL.revokeObjectURL(url); }; return ( <>

Total : {totalData}

setTotalData(data)} />

Pencarian

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

Data

Start Date

{convertDateFormatNoTime(feedbackDate.startDate)} setFeedbackDate({ startDate: e, endDate: feedbackDate.endDate, }) } maxValue={feedbackDate.endDate} />

End Date

{convertDateFormatNoTime(feedbackDate.endDate)} setFeedbackDate({ startDate: feedbackDate.startDate, endDate: e, }) } minValue={feedbackDate.startDate} />
{/*
*/}
{(column) => ( {column.name} )} } > {(item: any) => ( {(columnKey) => ( {renderCell(item, columnKey)} )} )}
setPage(page)} />
{() => ( <> Kritik Saran

Nama

( )} /> {errors?.commentFromName && (

{errors.commentFromName?.message}

)}

Email

( )} /> {errors?.commentFromEmail && (

{errors.commentFromEmail?.message}

)}

Deskripsi

(