diff --git a/src/views/PrincipalDistributors/orderDetails.js b/src/views/PrincipalDistributors/orderDetails.js index 294fb40..3554ad7 100644 --- a/src/views/PrincipalDistributors/orderDetails.js +++ b/src/views/PrincipalDistributors/orderDetails.js @@ -10,12 +10,12 @@ const OrderDetails = ({ _id, setLoading1 }) => { const getOrders = async () => { try { - const response = await axios.get(`/api/v1/admin/users/orders/${_id}`, { + const response = await axios.get(`/api/single-pd-order/${_id}`, { headers: { Authorization: `Bearer ${token}`, }, }); - setUserOrder(response.data.order); + setUserOrder(response.data.orders); setLoading1(false); } catch (error) { console.error("Error fetching orders:", error); diff --git a/src/views/PrincipalDistributors/principalDistributor.js b/src/views/PrincipalDistributors/principalDistributor.js index b2d0668..1b8c661 100644 --- a/src/views/PrincipalDistributors/principalDistributor.js +++ b/src/views/PrincipalDistributors/principalDistributor.js @@ -23,8 +23,7 @@ const principalDistributor = () => { const getUsers = async () => { setLoading(true); try { - const res = await axios - .get(`/api/v1/admin/users`, { + const res = await axios.get(`/api/v1/admin/pd`, { headers: { Authorization: `Bearer ${token}`, }, @@ -35,21 +34,21 @@ const principalDistributor = () => { 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); - } + // 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(() => { @@ -168,8 +167,8 @@ const principalDistributor = () => { setItemPerPage(Number(e.target.value)); setCurrentPage(1); // Reset to first page when changing items per page }} - className="form-control" - disabled={loading} + className="form-control" + disabled={loading} > @@ -257,7 +256,21 @@ const principalDistributor = () => { } )} - {loading1 && ( + + {user.lastOrderDate + ? new Date(user.lastOrderDate).toLocaleString( + "en-IN", + { + month: "short", + day: "numeric", + year: "numeric", + } + ) + : "No purchase"} + + + {user.totalOrders} + {/* {loading1 && ( <> loading... loading... @@ -267,23 +280,23 @@ const principalDistributor = () => { + /> */} - + - - + RD + + + {/* { - const [user, setUser] = useState(); - const [userOrder, setUserOrder] = useState(); + const [user, setUser] = useState(null); + const [userOrder, setUserOrder] = useState({ totalOrders: 0, totalValue: 0 }); const [userAllAddress, setUserAllAddress] = useState([]); - const token = isAutheticated(); - // const [loading, setLoading] = useState(true); - const _id = useParams()?._id; - // Get Shipping address of individual user - const getUserAddress = () => { - // setLoading(true); - axios - .get(`/api/shipping/address/user/address/${_id}`, { - headers: { - "Access-Control-Allow-Origin": "*", - Authorization: `Bearer ${token}`, - }, - }) - .then((res) => { - // console.log(res.data); - setUserAllAddress(res.data?.UserShippingAddress || []); - // toast.success(res.data.message ? res.data.message : "Address fetch!"); + const [orders, setOrders] = useState([]); + const [totalOrders, setTotalOrders] = useState(0); + const [page, setPage] = useState(0); + const [rowsPerPage, setRowsPerPage] = useState(10); + const [loading, setLoading] = useState(true); + const [searchField, setSearchField] = useState("Order ID"); + const [searchText, setSearchText] = useState(""); - // setLoading(false); - }) - .catch((error) => { - // setLoading(false); - swal({ - title: "Warning", - text: error.message, - icon: "error", - button: "Close", - dangerMode: true, - }); - }); + const token = isAutheticated(); + const { _id } = useParams(); + 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) => { + setSearchField(event.target.value); + setSearchText(""); }; - const getOrders = async () => { + const handleSearchChange = (event) => { + setSearchText(event.target.value); + if (searchField === "Order ID") { + searchOrderIdRef.current = event.target.value; + } else { + searchStatusRef.current = event.target.value; + } + // Call the debounced function to fetch orders + fetchOrdersDebounced( + page + 1, + rowsPerPage, + searchOrderIdRef.current, + searchStatusRef.current + ); + }; + const [openTMModal, setOpenTMModal] = useState(false); + const [singleorder, setSingleOrder] = useState(null); // State to hold fetched order details + + const handleCloseTMModal = () => { + setOpenTMModal(false); + setSingleOrder(null); // Clear the order details when closing the modal + }; + + // Function to fetch order details + const fetchOrderDetails = async (id) => { try { - const response = await axios.get(`/api/v1/admin/users/orders/${_id}`, { + const response = await axios.get(`/api/get-single-placed-order-pd/${id}`, { headers: { Authorization: `Bearer ${token}`, }, }); - setUserOrder(response.data.order); - // setLoading1(false); + setSingleOrder(response.data?.singleOrder); + setOpenTMModal(true); + } catch (error) { + console.error('Error fetching order details:', error); + + } + }; + + // Fetch Shipping address of the individual user + const getUserAddress = useCallback(async () => { + try { + const response = await axios.get( + `/api/shipping/address/user/address/${_id}`, + { + headers: { + Authorization: `Bearer ${token}`, + }, + } + ); + setUserAllAddress(response.data?.UserShippingAddress || []); } catch (error) { - console.error("Error fetching orders:", error); swal({ title: "Warning", text: error.message, @@ -59,65 +119,116 @@ const SinglePrincipalDistributorAllDetails = () => { button: "Close", dangerMode: true, }); - // setLoading1(false); } - }; - const getUserDetails = useCallback(async () => { - let resp = await axios.get(`/api/v1/admin/user/${_id}`, { - headers: { - Authorization: `Bearer ${token}`, - }, - }); - setUser(resp.data.user); - }, [token]); + }, [_id, token]); - // useEffect(() => { - // getUserDetails(); - // }, [getUserDetails]); + // Fetch Order Count and Total Value + const getOrdersCount = useCallback(async () => { + try { + const response = await axios.get(`/api/single-pd-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]); + + // Fetch User Details + const getUserDetails = useCallback(async () => { + try { + const response = await axios.get(`/api/v1/admin/user/${_id}`, { + headers: { + Authorization: `Bearer ${token}`, + }, + }); + setUser(response.data.user); + } catch (error) { + swal({ + title: "Warning", + text: error.message, + icon: "error", + button: "Close", + dangerMode: true, + }); + } + }, [_id, token]); + + // Fetch Orders with Pagination, Order ID, and Status search + const fetchOrders = useCallback(async () => { + setLoading(true); + try { + const response = await axios.get(`/api/single-pd-order/${_id}`, { + headers: { + Authorization: `Bearer ${token}`, + }, + params: { + page: page + 1, + limit: rowsPerPage, + orderId: searchOrderIdRef.current, + status: searchStatusRef.current, + }, + }); + 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, page, rowsPerPage]); useEffect(() => { - getOrders(); + getOrdersCount(); getUserAddress(); getUserDetails(); - }, [_id]); - // console.log(userOrder, " Single user order data "); - // console.log(userAllAddress, "user all address "); - // console.log(user, "user "); - let totalSpent = 0; + fetchOrders(); + }, [_id, getOrdersCount, getUserAddress, getUserDetails, fetchOrders]); - // Iterate through each order and sum up the total_amount - userOrder?.forEach((order) => { - totalSpent += order.total_amount; - }); + const handleChangePage = (event, newPage) => { + setPage(newPage); + // Fetch orders whenever page changes + fetchOrdersDebounced( + newPage + 1, + rowsPerPage, + searchOrderIdRef.current, + searchStatusRef.current + ); + }; + const handleChangeRowsPerPage = (event) => { + setRowsPerPage(parseInt(event.target.value)); + setPage(0); + // Fetch orders with the new rows per page setting + fetchOrdersDebounced( + 1, + parseInt(event.target.value), + searchOrderIdRef.current, + searchStatusRef.current + ); + }; return (
- {/* SinglePrincipalDistributorAllDetails - - - */}
-
+
Principal Distributor All Details
-
-

-
-
- • Principal Distributor Profile{" "} + • Principal Distributor Profile
Principal Distributor ID: {user?.uniqueId} - - SBU: - - {user?.SBU} - - - - Name: - - {user?.name} - - - - Email: - - {user?.email} - - - - Mobile Number: - - {user?.phone} - - - - Date Registered: - - {new Date(user?.createdAt).toLocaleString("en-IN", { - weekday: "short", - month: "short", - day: "numeric", - year: "numeric", - hour: "numeric", - minute: "numeric", - hour12: true, - })} - - - - Last Purchase: - - {userOrder?.length > 0 - ? new Date(userOrder[0]?.createdAt).toLocaleString("en-IN", { + {/* Repeating fields with similar styling and structure */} +
+
+ {[ + { label: "SBU", value: user?.SBU }, + { label: "Name", value: user?.name }, + { label: "Email", value: user?.email }, + { label: "Mobile Number", value: user?.phone }, + ].map((item, index) => ( + + {item.label}: + + {item.value} + + + ))} +
+
+ {[ + { + label: "Date Registered", + value: new Date(user?.createdAt).toLocaleString("en-IN", { weekday: "short", month: "short", day: "numeric", @@ -246,18 +296,46 @@ const SinglePrincipalDistributorAllDetails = () => { hour: "numeric", minute: "numeric", hour12: true, - }) - : userOrder - ? "No Purchase" - : "Loading"} - - + }), + }, + { + label: "Last Purchase", + value: + orders.length > 0 + ? new Date(orders[0]?.createdAt).toLocaleString("en-IN", { + weekday: "short", + month: "short", + day: "numeric", + year: "numeric", + hour: "numeric", + minute: "numeric", + hour12: true, + }) + : "No Purchase", + }, + { label: "Total Orders", value: userOrder?.totalOrders }, + { label: "Total Spent", value: `₹ ${userOrder?.totalValue}` }, + ].map((item, index) => ( + + {item.label}: + + {item.value} + + + ))} +
+
-
• Addresses{" "} -
+ {" "}
• Total Addresses : {userAllAddress?.length}{" "}
@@ -309,94 +387,203 @@ const SinglePrincipalDistributorAllDetails = () => { )}
-
- • Orders{" "} -
-
- • Total Orders : {userOrder?.length}{" "} -
-
- • Total Spent : ₹ {totalSpent}{" "} -
- {userOrder?.length > 0 && ( -
- - • Orders + + + + Search By + - - - - - - {/* */} - - - - {userAllAddress?.length === 0 && ( - - - + Order ID + Status + + + + + +
SL No.Order Date Order Id Items Order Amount Profile Image
-
No Data Available
-
+ + + 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} + + + + + )) )} - {userOrder?.map((order, i) => { - return ( - - - - -
{i + 1} - {" "} - {new Date(order?.createdAt).toLocaleString("en-IN", { - weekday: "short", - month: "short", - day: "numeric", - year: "numeric", - hour: "numeric", - minute: "numeric", - hour12: true, - })} - {order?.orderID} - {order?.orderItems?.map((item, i) => ( -
-

{item?.name}

-
- {item?.image?.map((img, i) => ( + +
+ + {/* Pagination */} + + + Order Details + Order Id : {singleorder?.uniqueId} + + {singleorder?.invoices?.length > 0 && ( + <> + + Invoices + + + + )} + + Order Summary + + + + + + + + + Product + Price (₹) + 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.productId.name} - ))} - - - ))} - - - - ); - })} - -
₹ {order?.total_amount}
-
- )} + + {item.productId.name} + + + + ₹{item.price} + + + {item.quantity} + + ₹{subtotal} + {item.GST}% + + ₹{gstAmount} + + + ₹{totalWithGST} + + + ); + })} + + + + + + {singleorder?.invoices?.length > 0 && ( + <> + + Order Items {singleorder?.status=="pending"?"to be Processed":"Cancelled"} + + + + )} + + + + + +
); }; - +// Helper function to format time as AM/PM +const formatAMPM = (date) => { + var hours = new Date(date).getHours(); + var minutes = new Date(date).getMinutes(); + var ampm = hours >= 12 ? "PM" : "AM"; + hours = hours % 12; + hours = hours ? hours : 12; + minutes = minutes < 10 ? "0" + minutes : minutes; + var strTime = hours + ":" + minutes + " " + ampm; + return strTime; +}; export default SinglePrincipalDistributorAllDetails; diff --git a/src/views/orders/ViewOrders.js b/src/views/orders/ViewOrders.js index 4afb673..a54e3f7 100644 --- a/src/views/orders/ViewOrders.js +++ b/src/views/orders/ViewOrders.js @@ -370,7 +370,7 @@ const ViewOrders = () => { <> {" "} - Order Itmes to processed + Order Items {order?.status=="pending"?"to be Processed":"Cancelled"}