admin/src/views/RetailDistributors/DistributorOrders.js
2025-02-08 17:52:25 +05:30

505 lines
16 KiB
JavaScript

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 <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"
: "Retailers Details"}
</Typography>
<Button
variant="contained"
color="secondary"
style={{
fontWeight: "bold",
textTransform: "capitalize",
}}
onClick={handleCancel}
>
Back
</Button>
</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>
{item.image.length > 0 && (
<img
src={item?.image[0]?.url}
alt={item.name}
style={{
width: 50,
height: 50,
marginRight: 10,
}}
/>
)}
<Typography variant="subtitle1">
{item.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;