pd mapped with order

This commit is contained in:
Sibunnayak 2024-09-25 18:09:16 +05:30
parent a20729d390
commit 82645c201a
4 changed files with 500 additions and 300 deletions

View File

@ -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);

View File

@ -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}`,
},
@ -257,7 +256,21 @@ const principalDistributor = () => {
}
)}
</td>
{loading1 && (
<td className="text-start">
{user.lastOrderDate
? new Date(user.lastOrderDate).toLocaleString(
"en-IN",
{
month: "short",
day: "numeric",
year: "numeric",
}
)
: "No purchase"}
</td>
<td className="text-start">{user.totalOrders}</td>
{/* {loading1 && (
<>
<td className="text-start">loading...</td>
<td className="text-start">loading...</td>
@ -267,7 +280,7 @@ const principalDistributor = () => {
<OrderDetails
_id={user?._id}
setLoading1={setLoading1}
/>
/> */}
<td className="text-start">
<Link
to={`/view/mappedretaildistributor/${user?._id}`}

View File

@ -1,123 +1,234 @@
import { Typography } from "@material-ui/core";
import { Button } from "@mui/material";
import { debounce } from "lodash";
import {
Dialog,
DialogTitle,
DialogContent,
DialogActions,
Grid,
Typography,
Box,
FormControl,
InputLabel,
Select,
MenuItem,
TextField,
TableContainer,
Paper,
Table,
TableHead,
TableRow,
TableCell,
TableBody,
Button,
TablePagination,
Skeleton,
} from "@mui/material";
import axios from "axios";
import React, { useCallback, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import React, { useCallback, useEffect, useState, useRef } from "react";
import { Link, useParams, useNavigate } from "react-router-dom";
import swal from "sweetalert";
import { isAutheticated } from "src/auth";
import InvoiceTable from "../orders/invoiceTable";
import PendingOrderTable from "../orders/pendingOrderTable";
const SinglePrincipalDistributorAllDetails = () => {
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 orders:", error);
swal({
title: "Warning",
text: error.message,
icon: "error",
button: "Close",
dangerMode: true,
});
// setLoading1(false);
console.error('Error fetching order details:', error);
}
};
const getUserDetails = useCallback(async () => {
let resp = await axios.get(`/api/v1/admin/user/${_id}`, {
// 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) {
swal({
title: "Warning",
text: error.message,
icon: "error",
button: "Close",
dangerMode: true,
});
}
}, [_id, token]);
// 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}`,
},
});
setUser(resp.data.user);
}, [token]);
setUserOrder(response.data);
} catch (error) {
swal({
title: "Warning",
text: error.message,
icon: "error",
button: "Close",
dangerMode: true,
});
}
}, [_id, token]);
// useEffect(() => {
// getUserDetails();
// }, [getUserDetails]);
// 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 (
<div>
{/* SinglePrincipalDistributorAllDetails
<Link to={`/principal-distributor`}>
<button
type="button"
className="mt-1 btn btn-info btn-sm waves-effect waves-light btn-table ml-2"
>
back
</button>
</Link> */}
<div className="row">
<div className="col-12">
<div
className="
page-title-box
d-flex
align-items-center
justify-content-between
"
>
<div className="page-title-box d-flex align-items-center justify-content-between">
<div style={{ fontSize: "22px" }} className="fw-bold">
Principal Distributor All Details
</div>
<div style={{ display: "flex", gap: "1rem" }}>
<h4 className="mb-0"></h4>
</div>
<div className="page-title-right">
<Link to="/principal-distributor">
<Button
@ -138,85 +249,46 @@ const SinglePrincipalDistributorAllDetails = () => {
</div>
<div className="card" style={{ padding: "1rem" }}>
<h5 style={{ fontWeight: "bold" }}>
&bull; Principal Distributor Profile{" "}
&bull; Principal Distributor Profile
</h5>
<div style={{ marginLeft: "1rem", marginTop: "1rem" }}>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Principal Distributor ID:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
style={{ fontWeight: "normal", marginLeft: "0.5rem" }}
>
{user?.uniqueId}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
SBU:
{/* Repeating fields with similar styling and structure */}
<div style={{ display: "flex", justifyContent: "space-between" }}>
<div style={{ flex: 1, paddingRight: "1rem" }}>
{[
{ label: "SBU", value: user?.SBU },
{ label: "Name", value: user?.name },
{ label: "Email", value: user?.email },
{ label: "Mobile Number", value: user?.phone },
].map((item, index) => (
<Typography
key={index}
style={{ fontWeight: "bold", fontSize: "1.2rem" }}
>
{item.label}:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
style={{ fontWeight: "normal", marginLeft: "0.5rem" }}
>
{user?.SBU}
{item.value}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Name:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
>
{user?.name}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Email:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
>
{user?.email}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Mobile Number:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
>
{user?.phone}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Date Registered:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "0.5rem",
}}
>
{new Date(user?.createdAt).toLocaleString("en-IN", {
))}
</div>
<div style={{ flex: 1, paddingLeft: "1rem" }}>
{[
{
label: "Date Registered",
value: new Date(user?.createdAt).toLocaleString("en-IN", {
weekday: "short",
month: "short",
day: "numeric",
@ -224,21 +296,13 @@ const SinglePrincipalDistributorAllDetails = () => {
hour: "numeric",
minute: "numeric",
hour12: true,
})}
</Typography>
</Typography>
<Typography style={{ fontWeight: "bold", fontSize: "1.2rem" }}>
Last Purchase:
<Typography
component="span"
style={{
fontWeight: "normal",
fontSize: "1.2rem",
marginLeft: "1.5rem",
}}
>
{userOrder?.length > 0
? new Date(userOrder[0]?.createdAt).toLocaleString("en-IN", {
}),
},
{
label: "Last Purchase",
value:
orders.length > 0
? new Date(orders[0]?.createdAt).toLocaleString("en-IN", {
weekday: "short",
month: "short",
day: "numeric",
@ -247,17 +311,31 @@ const SinglePrincipalDistributorAllDetails = () => {
minute: "numeric",
hour12: true,
})
: userOrder
? "No Purchase"
: "Loading"}
: "No Purchase",
},
{ label: "Total Orders", value: userOrder?.totalOrders },
{ label: "Total Spent", value: `${userOrder?.totalValue}` },
].map((item, index) => (
<Typography
key={index}
style={{ fontWeight: "bold", fontSize: "1.2rem" }}
>
{item.label}:
<Typography
component="span"
style={{ fontWeight: "normal", marginLeft: "0.5rem" }}
>
{item.value}
</Typography>
</Typography>
))}
</div>
</div>
</div>
<div style={{ marginTop: "2rem" }}>
<h5 style={{ fontWeight: "bold", marginBottom: "1rem" }}>
&bull; Addresses{" "}
</h5>
</h5>{" "}
<h5 style={{ fontWeight: "bold", marginLeft: "1rem" }}>
&bull; Total Addresses : {userAllAddress?.length}{" "}
</h5>
@ -309,94 +387,203 @@ const SinglePrincipalDistributorAllDetails = () => {
)}
</div>
<div style={{ marginTop: "2rem" }}>
<h5 style={{ fontWeight: "bold", marginBottom: "1rem" }}>
&bull; Orders{" "}
</h5>
<h5 style={{ fontWeight: "bold", marginLeft: "1rem" }}>
&bull; Total Orders : {userOrder?.length}{" "}
</h5>
<h5 style={{ fontWeight: "bold", marginLeft: "1rem" }}>
&bull; Total Spent : {totalSpent}{" "}
</h5>
{userOrder?.length > 0 && (
<div className="table-responsive table-shoot mt-3">
<table
className="table table-centered table-nowrap"
style={{ border: "1px solid" }}
<h5 style={{ fontWeight: "bold" }}>&bull; Orders</h5>
<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"
>
<thead
className="thead-info"
style={{ background: "rgb(140, 213, 213)" }}
>
<tr>
<th>SL No.</th>
<th>Order Date </th>
<th>Order Id </th>
<th>Items </th>
<th>Order Amount </th>
{/* <th>Profile Image</th> */}
</tr>
</thead>
<tbody>
{userAllAddress?.length === 0 && (
<tr className="text-center">
<td colSpan="6">
<h5>No Data Available</h5>
</td>
</tr>
)}
{userOrder?.map((order, i) => {
return (
<tr key={i}>
<td className="text-start">{i + 1}</td>
<td>
{" "}
{new Date(order?.createdAt).toLocaleString("en-IN", {
weekday: "short",
month: "short",
day: "numeric",
year: "numeric",
hour: "numeric",
minute: "numeric",
hour12: true,
})}
</td>
<td>{order?.orderID}</td>
<td>
{order?.orderItems?.map((item, i) => (
<div
style={{ display: "flex", marginTop: "1rem" }}
key={i}
>
<p>{item?.name}</p>
<div>
{item?.image?.map((img, i) => (
<img
style={{
width: "50px",
height: "50px",
marginLeft: "1rem",
}}
src={img?.url}
alt="img not available"
<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
/>
))}
</div>
</div>
))}
</td>
<td> {order?.total_amount}</td>
</tr>
</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={[10, 25, 50]}
component="div"
count={totalOrders}
rowsPerPage={rowsPerPage}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
<Dialog
open={openTMModal}
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>
<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>
);
})}
</tbody>
</table>
</div>
</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>
</div>
</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

@ -370,7 +370,7 @@ const ViewOrders = () => {
<>
{" "}
<Typography variant="h4" my={3} gutterBottom>
Order Itmes to processed
Order Items {order?.status=="pending"?"to be Processed":"Cancelled"}
</Typography>
<PendingOrderTable order={order} />
</>