rd order and pd order fixed

This commit is contained in:
Sibunnayak 2024-10-03 12:04:02 +05:30
parent 9f650d157e
commit d33a4bebbd
10 changed files with 598 additions and 691 deletions

View File

@ -155,6 +155,7 @@ import MapRD from "./views/RetailDistributors/MapRD";
import PendingOrders from "./views/orders/pendingOrders";
import ViewInvoices from "./views/orders/viewInoices";
import Stocks from "./views/PrincipalDistributors/Stock";
import SingleDistributorOrder from "./views/RetailDistributors/DistributorOrders";
const routes = [
//dashboard
@ -370,6 +371,12 @@ const routes = [
element: MapRD,
navName: "RetailDistributor",
},
{
path: "/:distributortype/orders/:id",
name: " Distributor Orders",
element: SingleDistributorOrder,
navName: "Distributor",
},
//----------------------- End Product Management Routes------------------------------------------------
//Departure

View File

@ -268,8 +268,22 @@ const principalDistributor = () => {
)
: "No purchase"}
</td>
<td className="text-start">{user.totalOrders}</td>
<td className="text-center">
<Link
to={`/principaldistributor/orders/${user?._id}`}
>
<button
style={{
color: "black",
marginRight: "1rem",
}}
type="button"
className="btn btn-warning btn-sm waves-effect waves-light btn-table ml-2"
>
{user.totalOrders}
</button>
</Link>
</td>
{/* {loading1 && (
<>
<td className="text-start">loading...</td>

View File

@ -1,113 +1,21 @@
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 { Typography, Button } from "@mui/material";
import axios from "axios";
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(null);
const [userOrder, setUserOrder] = useState({ totalOrders: 0, totalValue: 0 });
const [userOrder, setUserOrder] = useState({
totalOrders: 0,
totalValue: 0,
lastPurchaseOrderDate: null,
});
const [userAllAddress, setUserAllAddress] = 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 { _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) => {
const newSearchField = event.target.value;
setSearchField(newSearchField);
setSearchText("");
if (newSearchField === "Order ID") {
searchStatusRef.current = "";
} else {
searchOrderIdRef.current = "";
}
};
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 [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/get-single-placed-order-pd/${id}`,
{
headers: {
Authorization: `Bearer ${token}`,
},
}
);
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 () => {
@ -172,51 +80,12 @@ const SinglePrincipalDistributorAllDetails = () => {
}
}, [_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-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();
}, [_id, getOrdersCount, getUserAddress, getUserDetails]);
useEffect(() => {
fetchOrders(page + 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current);
}, [page, rowsPerPage]);
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 (
<div>
<div className="row">
@ -296,9 +165,10 @@ const SinglePrincipalDistributorAllDetails = () => {
},
{
label: "Last Purchase",
value:
orders.length > 0
? new Date(orders[0]?.createdAt).toLocaleString("en-IN", {
value: userOrder?.lastPurchaseOrderDate
? new Date(userOrder?.lastPurchaseOrderDate).toLocaleString(
"en-IN",
{
weekday: "short",
month: "short",
day: "numeric",
@ -306,11 +176,20 @@ const SinglePrincipalDistributorAllDetails = () => {
hour: "numeric",
minute: "numeric",
hour12: true,
})
}
)
: "No Purchase",
},
{ label: "Total Orders", value: userOrder?.totalOrders },
{ label: "Total Spent", value: `${userOrder?.totalValue}` },
{
label: "Total Orders",
value: userOrder?.totalOrders ? userOrder?.totalOrders : 0,
},
{
label: "Total Spent",
value: `${
userOrder?.totalValue ? userOrder?.totalValue : 0
}`,
},
].map((item, index) => (
<Typography
key={index}
@ -382,194 +261,6 @@ const SinglePrincipalDistributorAllDetails = () => {
</div>
)}
</div>
<div style={{ marginTop: "2rem" }}>
<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"
>
<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={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>
);
})}
</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>
);

View File

@ -0,0 +1,485 @@
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);
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 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 <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,
}}
>
<Typography variant="h4">{distributortype === "principaldistributor" ? "Principal Distributor Details":"Retail Distributor Details"}</Typography>
<IconButton sx={{ color: "red" }} onClick={handleCancel}>
Cancel <CancelIcon />
</IconButton>
</Box>
<Paper sx={{ p: 2, mb: 3 }}>
<Typography variant="h5" gutterBottom>
Distributor Details
</Typography>
<Grid container spacing={2}>
<Grid item xs={6}>
<Typography>
<strong>Name:</strong> {distributorDetails.name}
</Typography>
<Typography>
<strong>Mobile Number:</strong>{" "}
{distributortype === "principaldistributor"
? distributorDetails.phone
: distributorDetails.mobile_number}
</Typography>
<Typography>
<strong>Email:</strong> {distributorDetails.email}
</Typography>
</Grid>
<Grid item xs={6}>
<Typography>
<strong>Last Purchase:</strong>{" "}
{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"}
</Typography>
<Typography>
<strong>Total Orders:</strong>{" "}
{userOrder?.totalOrders ? userOrder?.totalOrders : 0}
</Typography>
<Typography>
<strong>Total Spent:</strong>{" "}
{userOrder?.totalValue ? userOrder?.totalValue : 0}
</Typography>
</Grid>
</Grid>
</Paper>
<Paper sx={{ p: 2, mb: 3 }}>
<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={handleCloseOrderModal}
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">Order 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="center">
{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={handleCloseOrderModal} color="secondary">
Cancel
</Button>
</DialogActions>
</Dialog>
</Box>
</Paper>
</Box>
);
};
export default SingleDistributorOrder;

View File

@ -14,9 +14,9 @@ const RetailDistributor = () => {
const [allRetailDistributorsData, setAllRetailDistributorsData] = useState(
[]
);
const nameRef = useRef();
const principalDistributorRef = useRef();
const [totalPages, setTotalPages] = useState(1);
const nameRef = useRef();
const principalDistributorRef = useRef();
const [totalPages, setTotalPages] = useState(1);
const [currentPage, setCurrentPage] = useState(1);
const [itemPerPage, setItemPerPage] = useState(10);
const [totalData, setTotalData] = useState(0);
@ -55,12 +55,15 @@ const [totalPages, setTotalPages] = useState(1);
useEffect(() => {
getRetailDistributorsData();
}, [ itemPerPage, currentPage]);
}, [itemPerPage, currentPage]);
const debouncedSearch = useCallback(debounce(() => {
const debouncedSearch = useCallback(
debounce(() => {
setCurrentPage(1);
getRetailDistributorsData();
}, 500), []);
}, 500),
[]
);
const handleSearchChange = () => {
debouncedSearch();
@ -157,8 +160,8 @@ const [totalPages, setTotalPages] = useState(1);
<th className="text-start">Principal Distributor</th>
<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">Mapping</th>
<th className="text-start">Action</th>
</tr>
</thead>
@ -193,14 +196,32 @@ const [totalPages, setTotalPages] = useState(1);
})}
</td>
<td className="text-start">
{retailDistributor?.principalDetails
?.name || "N/A"}
{retailDistributor?.principalDetails?.name ||
"N/A"}
</td>
<td className="text-start">
{retailDistributor?.mappedTMDetails?.name || "N/A"}
{retailDistributor?.mappedTMDetails?.name ||
"N/A"}
</td>
<td className="text-start">
{retailDistributor?.mappedSCDetails?.name || "N/A"}
{retailDistributor?.mappedSCDetails?.name ||
"N/A"}
</td>
<td className="text-center">
<Link
to={`/retailerdistributor/orders/${retailDistributor._id}`}
>
<button
style={{
color: "black",
marginRight: "1rem",
}}
type="button"
className="btn btn-warning btn-sm waves-effect waves-light btn-table ml-2"
>
{retailDistributor?.totalOrders}
</button>
</Link>
</td>
<td className="text-start">
<Link
@ -218,9 +239,7 @@ 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}`}
@ -250,7 +269,8 @@ const [totalPages, setTotalPages] = useState(1);
role="status"
aria-live="polite"
>
Showing {allRetailDistributorsData?.length} of {totalData} entries
Showing {allRetailDistributorsData?.length} of{" "}
{totalData} entries
</div>
</div>

View File

@ -10,103 +10,21 @@ import {
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 [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
@ -123,35 +41,6 @@ const handleSearchChange = (event) => {
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(() => {
fetchOrders(page + 1, rowsPerPage, searchOrderIdRef.current, searchStatusRef.current);
}, [page, rowsPerPage]);
// Fetch retailer details on mount
useEffect(() => {
@ -176,17 +65,6 @@ useEffect(() => {
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
@ -345,194 +223,6 @@ const handleChangeRowsPerPage = (event) => {
</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>
<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}

View File

@ -322,7 +322,7 @@ const ViewOrders = () => {
<TableRow>
<TableCell>Product</TableCell>
<TableCell align="right">Price ()</TableCell>
<TableCell align="right">Quantity</TableCell>
<TableCell align="right">Order Quantity</TableCell>
<TableCell align="right">Subtotal ()</TableCell>
<TableCell align="right">GST (%)</TableCell>
<TableCell align="right">GST Amount ()</TableCell>
@ -353,7 +353,7 @@ const ViewOrders = () => {
</Typography>
</TableCell>
<TableCell align="right">{item.price}</TableCell>
<TableCell align="right">{item.quantity}</TableCell>
<TableCell align="center">{item.quantity}</TableCell>
<TableCell align="right">{subtotal}</TableCell>
<TableCell align="right">{item.GST}%</TableCell>
<TableCell align="right">{gstAmount}</TableCell>

View File

@ -21,7 +21,7 @@ const InvoiceTable = ({ invoices }) => {
<TableRow>
<TableCell>Invoice ID</TableCell>
<TableCell>Items</TableCell>
<TableCell>Invoice Items</TableCell>
<TableCell>Subtotal</TableCell>
<TableCell>GST Total</TableCell>
<TableCell>Invoice Amount</TableCell>

View File

@ -22,12 +22,12 @@ const PendingOrderTable = ({ order }) => {
<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>
<TableCell align="center">Price ()</TableCell>
<TableCell align="center">Pending Quantity</TableCell>
<TableCell align="center">Subtotal ()</TableCell>
<TableCell align="center">GST (%)</TableCell>
<TableCell align="center">GST Amount ()</TableCell>
<TableCell align="center">Total with GST ()</TableCell>
</TableRow>
</TableHead>
<TableBody>
@ -55,14 +55,14 @@ const PendingOrderTable = ({ order }) => {
{item.productId.name}
</Typography>
</TableCell>
<TableCell align="right">{item.price}</TableCell>
<TableCell align="right">
<TableCell align="center">{item.price}</TableCell>
<TableCell align="center">
{item.remainingQuantity}
</TableCell>
<TableCell align="right">{subtotal}</TableCell>
<TableCell align="right">{item.GST}%</TableCell>
<TableCell align="right">{gstAmount}</TableCell>
<TableCell align="right">{totalWithGST}</TableCell>
<TableCell align="center">{subtotal}</TableCell>
<TableCell align="center">{item.GST}%</TableCell>
<TableCell align="center">{gstAmount}</TableCell>
<TableCell align="center">{totalWithGST}</TableCell>
</TableRow>
);
}

View File

@ -180,7 +180,7 @@ const ViewInvoices = () => {
<TableRow>
<TableCell>Invoice ID</TableCell>
<TableCell>Items</TableCell>
<TableCell>Invoice Items</TableCell>
<TableCell>Subtotal</TableCell>
<TableCell>GST Total</TableCell>
<TableCell>Invoice Amount</TableCell>