import React, { useState, useEffect, useRef, useCallback } from "react"; import axios from "axios"; import { Box, Typography, Grid, Paper, IconButton, Dialog, DialogContent, DialogTitle, DialogActions, FormControl, InputLabel, Select, MenuItem, TextField, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, Button, TablePagination, } from "@mui/material"; import { useParams, useNavigate } from "react-router-dom"; import { isAutheticated } from "../../auth"; import CancelIcon from "@mui/icons-material/Cancel"; // Add this import import { debounce } from "lodash"; import InvoiceTable from "../orders/invoiceTable"; import PendingOrderTable from "../orders/pendingOrderTable"; const SingleDistributorOrder = () => { const { id } = useParams(); const { distributortype } = useParams(); const [distributorDetails, setdistributorDetails] = useState(null); const [orders, setOrders] = useState([]); const [totalOrders, setTotalOrders] = useState(0); const [page, setPage] = useState(0); const [rowsPerPage, setRowsPerPage] = useState(5); const [loading, setLoading] = useState(true); const [searchField, setSearchField] = useState("Order ID"); const [searchText, setSearchText] = useState(""); const [userOrder, setUserOrder] = useState({ totalOrders: 0, totalValue: 0, lastPurchaseOrderDate: null, }); const token = isAutheticated(); const navigate = useNavigate(); const searchOrderIdRef = useRef(""); const searchStatusRef = useRef(""); // Debounced function to fetch orders const fetchOrdersDebounced = useRef( debounce((page, limit, orderId, status) => { fetchOrders(page, limit, orderId, status); }, 500) ).current; const handleSearchFieldChange = (event) => { const newSearchField = event.target.value; setSearchField(newSearchField); // Clear the search text and references setSearchText(""); searchOrderIdRef.current = ""; searchStatusRef.current = ""; // Reset page to 0 setPage(0); // Fetch total orders without any search filters fetchOrdersDebounced(1, rowsPerPage, "", ""); }; // When search text is typed const handleSearchChange = (event) => { setSearchText(event.target.value); if (searchField === "Order ID") { searchOrderIdRef.current = event.target.value; } else { searchStatusRef.current = event.target.value; } // Reset page to 0 and fetch orders with the new search term setPage(0); fetchOrdersDebounced( 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current ); }; const [openOrderModal, setopenOrderModal] = useState(false); const [singleorder, setSingleOrder] = useState(null); const handleCloseOrderModal = () => { setopenOrderModal(false); setSingleOrder(null); }; // Function to fetch order details const fetchOrderDetails = async (id) => { try { const response = await axios.get( distributortype === "principaldistributor" ? `/api/get-single-placed-order-pd/${id}` : `/api/get-single-placed-order-rd/${id}`, { headers: { Authorization: `Bearer ${token}`, }, } ); setSingleOrder(response.data?.singleOrder); setopenOrderModal(true); } catch (error) { console.error("Error fetching order details:", error); } }; const getUserDetails = useCallback(async () => { try { // Commented out the API call and using dummy data const response = await axios.get( distributortype === "principaldistributor" ? `/api/v1/admin/user/${id}` : `/api/getRD/${id}`, { headers: { "Access-Control-Allow-Origin": "*", Authorization: `Bearer ${token}`, "Content-Type": "multipart/form-data", }, } ); distributortype === "principaldistributor" ? setdistributorDetails(response.data.user) : setdistributorDetails(response.data); } catch (error) { console.error("Error fetching data: ", error); } }, [id, token, distributortype]); // Fetch Order Count and Total Value const getOrdersCount = useCallback(async () => { try { const response = await axios.get( distributortype === "principaldistributor" ? `/api/single-pd-ordercount/${id}` : `/api/single-rd-ordercount/${id}`, { headers: { Authorization: `Bearer ${token}`, }, } ); setUserOrder(response.data); } catch (error) { swal({ title: "Warning", text: error.message, icon: "error", button: "Close", dangerMode: true, }); } }, [id, token, distributortype]); // Fetch Orders with Pagination, Order ID, and Status search const fetchOrders = useCallback( async (page = 1, limit = rowsPerPage, orderId = "", status = "") => { setLoading(true); try { const response = await axios.get( distributortype === "principaldistributor" ? `/api/single-pd-order/${id}` : `/api/single-rd-order/${id}`, { headers: { Authorization: `Bearer ${token}` }, params: { page, limit, orderId, status }, } ); setOrders(response.data.orders || []); setTotalOrders(response.data.totalOrders || 0); } catch (error) { swal({ title: "Warning", text: error.message, icon: "error", button: "Close", dangerMode: true, }); } finally { setLoading(false); } }, [id, token, rowsPerPage, distributortype] ); useEffect(() => { fetchOrders( page + 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current ); }, [page, rowsPerPage]); useEffect(() => { getUserDetails(); getOrdersCount(); }, [id, getUserDetails, getOrdersCount, distributortype]); const handleCancel = () => { // Navigate based on distributor type navigate( distributortype === "principaldistributor" ? "/principal-distributor" : "/retail-distributor" ); }; if (!distributorDetails) { return Loading...; } // Handle page change const handleChangePage = (event, newPage) => { setPage(newPage); }; // Handle rows per page change const handleChangeRowsPerPage = (event) => { const newRowsPerPage = parseInt(event.target.value, 10); setRowsPerPage(newRowsPerPage); setPage(0); }; return ( {distributortype === "principaldistributor" ? "Principal Distributor Details" : "Retailers Details"} Distributor Details Name: {distributorDetails.name} Mobile Number:{" "} {distributortype === "principaldistributor" ? distributorDetails.phone : distributorDetails.mobile_number} Email: {distributorDetails.email} Last Purchase:{" "} {userOrder?.lastPurchaseOrderDate ? new Date(userOrder?.lastPurchaseOrderDate).toLocaleString( "en-IN", { weekday: "short", month: "short", day: "numeric", year: "numeric", hour: "numeric", minute: "numeric", hour12: true, } ) : "No Purchase"} Total Orders:{" "} {userOrder?.totalOrders ? userOrder?.totalOrders : 0} Total Spent:{" "} {userOrder?.totalValue ? userOrder?.totalValue : 0} Orders Search By Order ID Order Date Items Order Value Status Action {loading ? ( Loading... ) : orders.length === 0 ? ( No Orders Found ) : ( orders.map((order) => ( {order.uniqueId} {new Date(order.createdAt).toLocaleString()} {order.orderItem.length} ₹ {order.grandTotal} {order.status} )) )}
{/* Pagination */} Order Details Order Id : {singleorder?.uniqueId} {singleorder?.invoices?.length > 0 && ( <> Invoices )} Order Summary Product Price (₹) Order Quantity Subtotal (₹) GST (%) GST Amount (₹) Total with GST (₹) {singleorder?.orderItem.map((item, index) => { const subtotal = item.price * item.quantity; const gstAmount = ((item.GST * item.price) / 100) * item.quantity; const totalWithGST = subtotal + gstAmount; return ( {item.image.length > 0 && ( {item.name} )} {item.name} ₹{item.price} {item.quantity} ₹{subtotal} {item.GST}% ₹{gstAmount} ₹{totalWithGST} ); })}
{singleorder?.invoices?.length > 0 && ( <> Order Items{" "} {singleorder?.status == "pending" ? "to be Processed" : "Cancelled"} )}
); }; export default SingleDistributorOrder;