import React, { useState, useEffect, useRef, useCallback } from "react"; import { Link } from "react-router-dom"; import { Button } from "@mui/material"; import { useNavigate } from "react-router-dom"; import axios from "axios"; import { isAutheticated } from "src/auth"; import swal from "sweetalert"; import OrderDetails from "./orderDetails"; import debounce from "lodash.debounce"; import { toast } from "react-hot-toast"; const principalDistributor = () => { const token = isAutheticated(); const navigate = useNavigate(); const [loading, setLoading] = useState(true); const [loading1, setLoading1] = useState(true); const [success, setSuccess] = useState(true); const [users, setUsers] = useState([]); const [totalPages, setTotalPages] = useState(1); const [currentPage, setCurrentPage] = useState(1); const [itemPerPage, setItemPerPage] = useState(10); const [totalData, setTotalData] = useState(0); const nameRef = useRef(); const SBURef = useRef(); const getUsers = async () => { setLoading(true); try { const res = await axios.get(`/api/v1/admin/pd`, { headers: { Authorization: `Bearer ${token}`, }, params: { page: currentPage, show: itemPerPage, name: nameRef.current.value, SBU: SBURef.current.value, }, }); // console.log(res.data); setUsers(res.data.users); setTotalData(res.data?.total_data); setTotalPages(res.data?.total_pages); } catch (error) { swal({ title: error, text: "please login to access the resource or refresh the page ", icon: "error", button: "Retry", dangerMode: true, }); } finally { setLoading(false); } }; useEffect(() => { getUsers(); }, [itemPerPage, currentPage]); const debouncedSearch = useCallback( debounce(() => { setCurrentPage(1); getUsers(); }, 500), [] ); const handleSearchChange = () => { debouncedSearch(); }; // console.log(users); // const handleDelete = (id) => { // swal({ // title: "Are you sure?", // icon: "error", // buttons: { // Yes: { text: "Yes", value: true }, // Cancel: { text: "Cancel", value: "cancel" }, // }, // }).then((value) => { // if (value === true) { // axios // .delete(`/api/user-address/deleteAddress/${id}`, { // headers: { // "Access-Control-Allow-Origin": "*", // Authorization: `Bearer ${token}`, // }, // }) // .then((res) => { // swal({ // title: "Deleted", // text: "Address Deleted successfully!", // icon: "success", // button: "ok", // }); // setSuccess((prev) => !prev); // }) // .catch((err) => { // swal({ // title: "Warning", // text: "Something went wrong!", // icon: "error", // button: "Retry", // dangerMode: true, // }); // }); // } // }); // }; const handleDownloadReport = async () => { try { const response = await axios.get( `/api/v1/principaldistributor/download-report`, { headers: { Authorization: `Bearer ${token}`, }, responseType: "arraybuffer", } ); // Check if the request was successful if (response.status === 200) { // Convert response data into a Blob for download const url = window.URL.createObjectURL( new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", }) ); // Create a temporary download link and trigger the download const link = document.createElement("a"); link.href = url; link.download = "Principal_Distributor_Report.xlsx"; document.body.appendChild(link); link.click(); // Cleanup document.body.removeChild(link); window.URL.revokeObjectURL(url); // Release Blob URL memory // Show success message toast.success("Report downloaded successfully!"); } else { // If the response status is not 200, display an error message throw new Error("Failed to download report"); } } catch (err) { // Display a user-friendly error message const msg = err?.response?.data?.message || "Something went wrong!"; swal({ title: "Error", text: msg, icon: "error", button: "Retry", dangerMode: true, }); } }; const handleReset = async (id) => { try { const response = await axios.put( `https://cheminova-api1.onrender.com/api/v1/user/reset-password/${id}`, {}, // No body content required for this request { headers: { Authorization: `Bearer ${token}`, }, } ); if (response.data.success) { toast.success( "Password reset successfully! Email sent to Principal Distributor." ); } } catch (error) { toast.error( error.response?.data?.message || "Failed to reset the password. Please try again." ); } }; return (
All Principal Distributor
{loading ? ( ) : users.length > 0 ? ( users.map((user, i) => ( {/* {loading1 && ( <> )} */} {/* )) ) : ( )}
Unique Id SBU Name Email Date Registered Last Purchase Orders Mapping Action
Loading....
{user.uniqueId} {user.SBU ? user.SBU : "N/A"} {user.name} {user.email} {new Date(user.createdAt).toLocaleString( "en-IN", { // weekday: "short", month: "short", day: "numeric", year: "numeric", // hour: "numeric", // minute: "numeric", // hour12: true, } )} {user.lastOrderDate ? new Date(user.lastOrderDate).toLocaleString( "en-IN", { month: "short", day: "numeric", year: "numeric", } ) : "No purchase"} loading... loading... */} {/* */}
{/* View Button */} {/* Stock Button */} {/* OI Button */}
No Principal Distributor found!
); }; export default principalDistributor;