rd totalorder and order view ui created

This commit is contained in:
Sibunnayak 2024-09-30 16:42:25 +05:30
parent 6197aea186
commit 9f650d157e
3 changed files with 468 additions and 131 deletions

View File

@ -38,7 +38,7 @@ const SinglePrincipalDistributorAllDetails = () => {
const [orders, setOrders] = useState([]);
const [totalOrders, setTotalOrders] = useState(0);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const [rowsPerPage, setRowsPerPage] = useState(5);
const [loading, setLoading] = useState(true);
const [searchField, setSearchField] = useState("Order ID");
const [searchText, setSearchText] = useState("");
@ -56,8 +56,15 @@ const SinglePrincipalDistributorAllDetails = () => {
).current;
const handleSearchFieldChange = (event) => {
setSearchField(event.target.value);
const newSearchField = event.target.value;
setSearchField(newSearchField);
setSearchText("");
if (newSearchField === "Order ID") {
searchStatusRef.current = "";
} else {
searchOrderIdRef.current = "";
}
};
const handleSearchChange = (event) => {
@ -67,9 +74,10 @@ const SinglePrincipalDistributorAllDetails = () => {
} else {
searchStatusRef.current = event.target.value;
}
// Call the debounced function to fetch orders
// Reset page to 0 and fetch orders with the new search term
setPage(0);
fetchOrdersDebounced(
page + 1,
1,
rowsPerPage,
searchOrderIdRef.current,
searchStatusRef.current
@ -86,19 +94,21 @@ const SinglePrincipalDistributorAllDetails = () => {
// Function to fetch order details
const fetchOrderDetails = async (id) => {
try {
const response = await axios.get(`/api/get-single-placed-order-pd/${id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
const response = await axios.get(
`/api/get-single-placed-order-pd/${id}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
setSingleOrder(response.data?.singleOrder);
setOpenTMModal(true);
setOpenTMModal(true);
} catch (error) {
console.error('Error fetching order details:', error);
console.error("Error fetching order details:", error);
}
};
// Fetch Shipping address of the individual user
const getUserAddress = useCallback(async () => {
try {
@ -163,63 +173,49 @@ const SinglePrincipalDistributorAllDetails = () => {
}, [_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]);
const fetchOrders = useCallback(
async (page = 1, limit = rowsPerPage, orderId = "", status = "") => {
setLoading(true);
try {
const response = await axios.get(`/api/single-pd-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]
);
useEffect(() => {
getOrdersCount();
getUserAddress();
getUserDetails();
fetchOrders();
}, [_id, getOrdersCount, getUserAddress, getUserDetails, fetchOrders]);
}, [_id, getOrdersCount, getUserAddress, getUserDetails]);
useEffect(() => {
fetchOrders(page + 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current);
}, [page, rowsPerPage]);
const handleChangePage = (event, newPage) => {
setPage(newPage);
// Fetch orders whenever page changes
fetchOrdersDebounced(
newPage + 1,
rowsPerPage,
searchOrderIdRef.current,
searchStatusRef.current
);
};
// Handle rows per page change
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value));
const newRowsPerPage = parseInt(event.target.value, 10);
setRowsPerPage(newRowsPerPage);
setPage(0);
// Fetch orders with the new rows per page setting
fetchOrdersDebounced(
1,
parseInt(event.target.value),
searchOrderIdRef.current,
searchStatusRef.current
);
};
return (
<div>
@ -463,7 +459,7 @@ const SinglePrincipalDistributorAllDetails = () => {
</TableContainer>
{/* Pagination */}
<TablePagination
rowsPerPageOptions={[10, 25, 50]}
rowsPerPageOptions={[5, 10, 25, 50]}
component="div"
count={totalOrders}
rowsPerPage={rowsPerPage}
@ -557,7 +553,10 @@ const SinglePrincipalDistributorAllDetails = () => {
{singleorder?.invoices?.length > 0 && (
<>
<Typography variant="h4" my={3} gutterBottom>
Order Items {singleorder?.status=="pending"?"to be Processed":"Cancelled"}
Order Items{" "}
{singleorder?.status == "pending"
? "to be Processed"
: "Cancelled"}
</Typography>
<PendingOrderTable order={singleorder} />
</>
@ -575,15 +574,4 @@ const SinglePrincipalDistributorAllDetails = () => {
</div>
);
};
// 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;

View File

@ -24,7 +24,7 @@ const [totalPages, setTotalPages] = useState(1);
const getRetailDistributorsData = async () => {
setLoading(true);
try {
const res = await axios.get(`/api/getAllRD`, {
const res = await axios.get(`/api/getAllRDandorder`, {
headers: {
Authorization: `Bearer ${token}`,
},
@ -158,6 +158,7 @@ const [totalPages, setTotalPages] = useState(1);
<th className="text-start">Territory Manager</th>
<th className="text-start">Sales Coordinator</th>
<th className="text-start">Mapping</th>
<th className="text-start">Orders</th>
<th className="text-start">Action</th>
</tr>
</thead>
@ -217,6 +218,9 @@ const [totalPages, setTotalPages] = useState(1);
</button>
</Link>
</td>
<td className="text-center">
{retailDistributor?.totalOrders}
</td>
<td className="text-start">
<Link
to={`/retaildistributor/view/${retailDistributor._id}`}

View File

@ -1,39 +1,162 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Box, Typography, Grid, Paper, Avatar, IconButton, Dialog, DialogContent, DialogTitle } from '@mui/material';
import { useParams, useNavigate } from 'react-router-dom';
import { format } from 'date-fns';
import { isAutheticated } from '../../auth';
import CancelIcon from '@mui/icons-material/Cancel'; // Add this import
import React, { useState, useEffect, useRef, useCallback } from "react";
import axios from "axios";
import {
Box,
Typography,
Grid,
Paper,
Avatar,
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 { format } from "date-fns";
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 SingleRetailDistributor = () => {
const { id } = useParams();
const [retailerDetails, setRetailerDetails] = useState(null);
const [openPopup, setOpenPopup] = useState(false);
const [selectedImage, setSelectedImage] = useState('');
const [selectedImage, setSelectedImage] = useState("");
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 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);
setSearchText("");
if (newSearchField === "Order ID") {
searchStatusRef.current = "";
} else {
searchOrderIdRef.current = "";
}
};
// 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 handleCloseTMModal = () => {
setopenOrderModal(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/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(`/api/getRD/${id}`, {
headers: {
"Access-Control-Allow-Origin": "*",
Authorization: `Bearer ${token}`,
"Content-Type": "multipart/form-data",
},
});
setRetailerDetails(response.data);
// console.log('Retailer Details: ', response.data);
} catch (error) {
console.error("Error fetching data: ", error);
}
}, [id, token]);
// 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(`/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]
);
useEffect(() => {
const fetchData = async () => {
try {
// Commented out the API call and using dummy data
const response = await axios.get(`/api/getRD/${id}`, {
headers: {
'Access-Control-Allow-Origin': '*',
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
},
});
setRetailerDetails(response.data);
// console.log('Retailer Details: ', response.data);
} catch (error) {
console.error('Error fetching data: ', error);
}
};
fetchOrders(page + 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current);
}, [page, rowsPerPage]);
fetchData();
}, [id]);
// Fetch retailer details on mount
useEffect(() => {
getUserDetails();
}, [id, getUserDetails]);
const handleOpenPopup = (imageUrl) => {
setSelectedImage(imageUrl);
@ -42,25 +165,40 @@ const SingleRetailDistributor = () => {
const handleClosePopup = () => {
setOpenPopup(false);
setSelectedImage('');
setSelectedImage("");
};
const handleCancel = () => {
navigate('/retail-distributor');
navigate("/retail-distributor");
};
if (!retailerDetails) {
return <Typography>Loading...</Typography>;
}
// 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 (
<Box sx={{ p: 3 }}>
<Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
<Box
sx={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
mb: 3,
}}
>
<Typography variant="h4">Retailer Details</Typography>
<IconButton
sx={{ color: 'red' }}
onClick={handleCancel}
>
<IconButton sx={{ color: "red" }} onClick={handleCancel}>
Cancel <CancelIcon />
</IconButton>
</Box>
@ -98,7 +236,8 @@ const SingleRetailDistributor = () => {
<strong>Mobile Number:</strong> {retailerDetails.mobile_number}
</Typography>
<Typography>
<strong>Mapped Principal Distributor:</strong> {retailerDetails?.principal_distributer?.name || 'Not Mapped'}
<strong>Mapped Principal Distributor:</strong>{" "}
{retailerDetails?.principal_distributer?.name || "Not Mapped"}
</Typography>
</Grid>
</Grid>
@ -116,17 +255,20 @@ const SingleRetailDistributor = () => {
<Avatar
variant="square"
src={retailerDetails.kyc.pan_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() => handleOpenPopup(retailerDetails.kyc.pan_img.url)}
/>
<Typography>
<strong>Aadhar Number:</strong> {retailerDetails.kyc.aadhar_number}
<strong>Aadhar Number:</strong>{" "}
{retailerDetails.kyc.aadhar_number}
</Typography>
<Avatar
variant="square"
src={retailerDetails.kyc.aadhar_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.kyc.aadhar_img.url)}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() =>
handleOpenPopup(retailerDetails.kyc.aadhar_img.url)
}
/>
<Typography>
<strong>GST Number:</strong> {retailerDetails.kyc.gst_number}
@ -134,7 +276,7 @@ const SingleRetailDistributor = () => {
<Avatar
variant="square"
src={retailerDetails.kyc.gst_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() => handleOpenPopup(retailerDetails.kyc.gst_img.url)}
/>
</Grid>
@ -145,8 +287,10 @@ const SingleRetailDistributor = () => {
<Avatar
variant="square"
src={retailerDetails.kyc.pesticide_license_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.kyc.pesticide_license_img.url)}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() =>
handleOpenPopup(retailerDetails.kyc.pesticide_license_img.url)
}
/>
<Typography>
<strong>Fertilizer License (optional):</strong>
@ -155,8 +299,12 @@ const SingleRetailDistributor = () => {
<Avatar
variant="square"
src={retailerDetails.kyc.fertilizer_license_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.kyc.fertilizer_license_img.url)}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() =>
handleOpenPopup(
retailerDetails.kyc.fertilizer_license_img.url
)
}
/>
) : (
<Typography>Img not available</Typography>
@ -167,8 +315,10 @@ const SingleRetailDistributor = () => {
<Avatar
variant="square"
src={retailerDetails.kyc.selfie_entrance_img.url}
sx={{ width: 100, height: 100, mb: 2, cursor: 'pointer' }}
onClick={() => handleOpenPopup(retailerDetails.kyc.selfie_entrance_img.url)}
sx={{ width: 100, height: 100, mb: 2, cursor: "pointer" }}
onClick={() =>
handleOpenPopup(retailerDetails.kyc.selfie_entrance_img.url)
}
/>
</Grid>
</Grid>
@ -181,22 +331,217 @@ const SingleRetailDistributor = () => {
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Designation:</strong> {retailerDetails?.userType|| 'Not Available'}
<strong>Designation:</strong>{" "}
{retailerDetails?.userType || "Not Available"}
</Typography>
<Typography>
<strong>Name:</strong> {retailerDetails?.addedBy?.name || 'Not Available'}
<strong>Name:</strong>{" "}
{retailerDetails?.addedBy?.name || "Not Available"}
</Typography>
<Typography>
<strong>ID:</strong> {retailerDetails?.addedBy?.uniqueId || 'Not Available'}
<strong>ID:</strong>{" "}
{retailerDetails?.addedBy?.uniqueId || "Not Available"}
</Typography>
</Grid>
</Grid>
</Paper>
<Paper sx={{ p: 2, mb: 3 }}>
{/* <div style={{ marginTop: "2rem" }}> */}
<Typography variant="h5" gutterBottom>
Orders
</Typography>
<Box className="mt-3">
<Box display="flex" mb={2} alignItems="center">
<FormControl variant="outlined" sx={{ minWidth: 150, mr: 2 }}>
<InputLabel id="search-field-label">Search By</InputLabel>
<Select
labelId="search-field-label"
id="search-field"
value={searchField}
onChange={handleSearchFieldChange}
label="Search By"
>
<MenuItem value="Order ID">Order ID</MenuItem>
<MenuItem value="Status">Status</MenuItem>
</Select>
</FormControl>
<TextField
label={`Search by ${searchField}`}
variant="outlined"
value={searchText}
onChange={handleSearchChange}
fullWidth
/>
</Box>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Order ID</TableCell>
<TableCell>Order Date</TableCell>
<TableCell>Items</TableCell>
<TableCell>Order Value</TableCell>
<TableCell>Status</TableCell>
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{loading ? (
<TableRow>
<TableCell colSpan={6} align="center">
Loading...
</TableCell>
</TableRow>
) : orders.length === 0 ? (
<TableRow>
<TableCell colSpan={6} align="center">
No Orders Found
</TableCell>
</TableRow>
) : (
orders.map((order) => (
<TableRow key={order._id}>
<TableCell>{order.uniqueId}</TableCell>
<TableCell>
{new Date(order.createdAt).toLocaleString()}
</TableCell>
<TableCell>{order.orderItem.length}</TableCell>
<TableCell> {order.grandTotal}</TableCell>
<TableCell>{order.status}</TableCell>
<TableCell>
<Button
variant="contained"
color="primary"
onClick={() => fetchOrderDetails(order._id)}
>
View
</Button>
</TableCell>
</TableRow>
))
)}
</TableBody>
</Table>
</TableContainer>
{/* Pagination */}
<TablePagination
rowsPerPageOptions={[5,10, 25, 50]}
component="div"
count={totalOrders}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
<Dialog
open={openOrderModal}
onClose={handleCloseTMModal}
maxWidth="md"
fullWidth
>
<DialogTitle>Order Details</DialogTitle>
<DialogTitle>Order Id : {singleorder?.uniqueId}</DialogTitle>
<DialogContent>
{singleorder?.invoices?.length > 0 && (
<>
<Typography variant="h4" gutterBottom>
Invoices
</Typography>
<InvoiceTable invoices={singleorder.invoices} />
</>
)}
<Typography variant="h4" my={3} gutterBottom>
Order Summary
</Typography>
<Dialog open={openPopup} onClose={handleClosePopup} maxWidth="md" fullWidth>
<Grid container spacing={2}>
<Grid item xs={12}>
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
<TableCell>Product</TableCell>
<TableCell align="right">Price ()</TableCell>
<TableCell align="right">Quantity</TableCell>
<TableCell align="right">Subtotal ()</TableCell>
<TableCell align="right">GST (%)</TableCell>
<TableCell align="right">GST Amount ()</TableCell>
<TableCell align="right">
Total with GST ()
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{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 (
<TableRow key={index}>
<TableCell>
<img
src={item.productId.image}
alt={item.productId.name}
style={{
width: 50,
height: 50,
marginRight: 10,
}}
/>
<Typography variant="subtitle1">
{item.productId.name}
</Typography>
</TableCell>
<TableCell align="right">{item.price}</TableCell>
<TableCell align="right">
{item.quantity}
</TableCell>
<TableCell align="right">{subtotal}</TableCell>
<TableCell align="right">{item.GST}%</TableCell>
<TableCell align="right">{gstAmount}</TableCell>
<TableCell align="right">
{totalWithGST}
</TableCell>
</TableRow>
);
})}
</TableBody>
</Table>
</TableContainer>
</Grid>
</Grid>
{singleorder?.invoices?.length > 0 && (
<>
<Typography variant="h4" my={3} gutterBottom>
Order Items{" "}
{singleorder?.status == "pending"
? "to be Processed"
: "Cancelled"}
</Typography>
<PendingOrderTable order={singleorder} />
</>
)}
</DialogContent>
<DialogActions>
<Button onClick={handleCloseTMModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</Box>
{/* </div> */}
</Paper>
<Dialog
open={openPopup}
onClose={handleClosePopup}
maxWidth="md"
fullWidth
>
<DialogTitle>
<IconButton
sx={{ position: 'absolute', right: 16, top: 16, color: 'red' }}
sx={{ position: "absolute", right: 16, top: 16, color: "red" }}
onClick={handleClosePopup}
>
<CancelIcon />
@ -204,22 +549,22 @@ const SingleRetailDistributor = () => {
</DialogTitle>
<DialogContent
sx={{
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
display: "flex",
justifyContent: "center",
alignItems: "center",
p: 0,
overflow: 'auto',
maxHeight: '80vh',
maxWidth: '80vw',
overflow: "auto",
maxHeight: "80vh",
maxWidth: "80vw",
}}
>
<img
src={selectedImage}
alt="Large Preview"
style={{
maxWidth: '100%',
maxHeight: '100%',
objectFit: 'contain',
maxWidth: "100%",
maxHeight: "100%",
objectFit: "contain",
}}
/>
</DialogContent>