import { React, useState, useEffect, useRef } from 'react';
import TitleCard from 'pages/nearle/titleCard';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import { Empty } from 'antd';
import ClearIcon from '@mui/icons-material/Clear';
import { useTheme } from '@mui/material/styles';
import { SlLocationPin } from 'react-icons/sl';
import MapWithRoute from './mapWithRoute';
import { enqueueSnackbar } from 'notistack';
// material-ui
import {
Divider,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Grid,
Dialog,
DialogTitle,
Typography,
DialogContent,
Stack,
Button,
IconButton,
Tooltip,
Chip,
Paper,
FormControl,
OutlinedInput,
InputAdornment,
Badge,
Autocomplete,
TextField
} from '@mui/material';
import { SearchOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import { DateRangePicker } from 'mui-daterange-picker';
import {
addDays,
addMonths,
addWeeks,
// addYears,
endOfMonth,
endOfWeek,
// endOfYear,
startOfMonth,
startOfWeek
// startOfYear,
} from 'date-fns';
import { FilterList } from '@mui/icons-material';
// project imports
import { fetchorderdetails, fetchCount, fetchAppLocations } from '../api/api';
import MainCard from 'components/MainCard';
import { CSVExport } from 'components/third-party/ReactTable';
import Loader from 'components/Loader';
function descendingComparator(a, b, orderBy) {
if (b[orderBy] < a[orderBy]) {
return -1;
}
if (b[orderBy] > a[orderBy]) {
return 1;
}
return 0;
}
function getComparator(order, orderBy) {
return order === 'desc' ? (a, b) => descendingComparator(a, b, orderBy) : (a, b) => -descendingComparator(a, b, orderBy);
}
function stableSort(array, comparator) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = comparator(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
function formatNumberToRupees(value) {
return new Intl.NumberFormat('en-IN', {
style: 'currency',
currency: 'INR',
minimumFractionDigits: 2
}).format(value);
}
const headCells = [
{
id: 'sno',
disablePadding: false,
label: '#'
},
{
id: 'tenantname',
disablePadding: false,
label: 'Client'
},
{
id: 'Pickup loco',
disablePadding: false,
label: 'Pickup'
},
{
id: 'Delivery loco',
disablePadding: false,
label: 'Drop'
},
{
id: 'order status',
disablePadding: false,
label: 'status'
},
{
id: 'assigned',
disablePadding: false,
label: 'assigned'
},
{
id: 'Accepted',
disablePadding: false,
label: 'Accepted'
},
{
id: 'arrived',
disablePadding: false,
label: 'arrived'
},
{
id: 'picked',
disablePadding: false,
label: 'picked'
},
{
id: 'Delivered',
disablePadding: false,
label: 'Delivered'
},
{
id: 'cancelled',
disablePadding: false,
label: 'cancelled'
},
{
id: ' notes',
disablePadding: false,
label: 'NOTES'
},
{
id: 'kms',
disablePadding: false,
label: 'KMS'
},
{
id: 'charges',
disablePadding: false,
label: 'Charges',
numeric: true
}
];
// ==============================|| MUI TABLE - ENHANCED ||============================== //
export default function OrdersDetails() {
const textFieldRef = useRef(null);
const [order, setOrder] = useState('asc');
const [orderBy, setOrderBy] = useState('calories');
const [selected, setSelected] = useState([]);
const [page, setPage] = useState(0);
const [dense] = useState(false);
const [rowsPerPage, setRowsPerPage] = useState(20);
const [selectedValue, setSelectedValue] = useState([]);
const [locaName, setLocoName] = useState('All');
const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
const [open, setOpen] = useState(false);
const [open1, setOpen1] = useState(false);
const [dateselect, setDateselect] = useState('select');
const [tabstatus1, setTabstatus1] = useState('Today');
const [datestatus, setDatestatus] = useState('Today');
const [totalCharge, settotalCharge] = useState(0);
const [totalAmount, settotalAmount] = useState(0);
const [appId, setAppId] = useState(-1);
const [value, setValue] = useState(0);
const [tabvalue, setTabvalue] = useState(0);
const [deliCount, setDeliCount] = useState(0);
const [pendCount, setPendCount] = useState(0);
const [cancelCount, setCancelCount] = useState(0);
const [searchword, setSearchword] = useState('');
const [count, setCount] = useState(0);
const theme = useTheme();
const [riderCoordinates, setRiderCoordinates] = useState([]);
const [riderStart, setRiderStart] = useState();
const [riderEnd, setRiderEnd] = useState();
const [mapOpen, setMapOpen] = useState(false);
const [mapTenant, setMapTenant] = useState({});
let [total, settotal] = useState(0);
let [coveredLenght, setCoveredLenght] = useState(0);
let [uncoveredLenght, setUncoveredLenght] = useState(0);
let [cancelLenght, setCancelLenght] = useState(0);
let [assignLenght, setAssignLenght] = useState(0);
let [pickedLenght, setPickedLenght] = useState(0);
let [activeLenght, setActiveLenght] = useState(0);
let [arrivesLenght, setArrivedLenght] = useState(0);
const [statusCount, setStatusCount] = useState();
const [currentStatus, setCurrentStatus] = useState('All');
const status = [
{ id: 0, status: 'All', statusLow: 'All', count: total },
{ id: 1, status: 'Pending', statusLow: 'pending', count: assignLenght },
{ id: 2, status: 'Accepted', statusLow: 'accepted', count: uncoveredLenght },
{ id: 3, status: 'Arrived', statusLow: 'arrived', count: arrivesLenght },
{ id: 4, status: 'Picked', statusLow: 'picked', count: pickedLenght },
{ id: 5, status: 'Active', statusLow: 'active', count: activeLenght },
{ id: 6, status: 'Delivered', statusLow: 'delivered', count: coveredLenght },
{ id: 7, status: 'Cancelled', statusLow: 'cancelled', count: cancelLenght }
];
const getdeliverylogs = async (id) => {
console.log('deliveryid', id);
try {
const res = await axios.get(`${process.env.REACT_APP_URL}/deliveries/getdeliverylogs/?deliveryid=${id}`);
console.log('getdeliverylogs', res.data.details);
const datas = res.data.details;
if (datas.length != 0) {
setRiderStart(datas[0].logdate);
setRiderEnd(datas[datas.length - 1].logdate);
const coData = datas.map((data) => ({ lat: data.latitude, lng: data.longitude }));
console.log('coData', coData);
setRiderCoordinates(coData);
setOpen1(true);
} else {
opentoast('No Logs Found ', 'error', 2000);
}
} catch (error) {
console.log('getdeliverylogs', error);
}
};
const opentoast = (message, variant, time) => {
enqueueSnackbar(message, {
variant: variant,
anchorOrigin: { vertical: 'top', horizontal: 'right' },
autoHideDuration: time ? time : 1500
});
};
// ==============================|| textFieldRef (cmd+k)||============================== //
useEffect(() => {
const handleKeyPress = (event) => {
if (event.key === 'k' && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
textFieldRef.current.focus();
}
if (event.key === 'Escape' && document.activeElement === textFieldRef.current) {
// Remove focus from the TextField
textFieldRef.current.blur();
}
};
document.addEventListener('keydown', handleKeyPress);
return () => {
document.removeEventListener('keydown', handleKeyPress);
};
}, []);
// ==============================|| fetchorderdetails (orders)||============================== //
const {
isLoading: isLoadingOrderDetails,
isError: isErrorOrderDetails, //true or false
data: rows,
error: orderDetailsError
} = useQuery({
queryKey: [startdate, enddate, currentStatus],
queryFn: fetchorderdetails
});
// ==============================|| calculate||============================== //
const calculate = () => {
let calculatedTotalCharge = 0;
let calculatedTotalAmount = 0;
rows &&
rows.forEach((row) => {
calculatedTotalCharge += row.deliverycharges;
});
settotalCharge(calculatedTotalCharge);
rows &&
rows.forEach((row) => {
calculatedTotalAmount += row.deliveryamt;
});
console.log('calculatedTotalAmount', calculatedTotalAmount);
settotalAmount(calculatedTotalAmount);
};
useEffect(() => {
calculate();
rows && setRowsPerPage(rows.length + 1);
rows && setCount(rows.length);
}, [rows]);
// ==============================|| fetchOrdersCount (orders)||============================== //
const {
isLoading: isLoadingOrderCount,
isError: isErrorOrderCount, //true or false
data: countData,
error: orderCountError
} = useQuery({
queryKey: [startdate, enddate],
queryFn: fetchCount
});
useEffect(() => {
if (countData) {
setDeliCount(countData.deliveredCount);
setPendCount(countData.pendingCount);
setCancelCount(countData.cancelledCount);
}
}, [fetchCount, startdate, enddate]);
// ==============================|| fetchAppLocations ||============================== //
if (isLoadingOrderDetails || isLoadingOrderCount) return ;
if (isErrorOrderDetails) return 'An error has occurred:(isErrorOrderDetails) ' + orderDetailsError.message;
if (isErrorOrderCount) return 'An error has occurred:(isErrorOrderCount) ' + orderCountError.message;
const filteredOrders = rows.filter((row) =>
row.orderstatus == ''
? row.orderstatus.toLowerCase().includes(searchword.toLowerCase())
: row.orderstatus.toLowerCase().includes(searchword.toLowerCase()) ||
row.ordernotes.toLowerCase().includes(searchword.toLowerCase()) ||
row.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
row.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
row.pickupcustomer.toLowerCase().includes(searchword.toLowerCase()) ||
row.pickupcontactno.toLowerCase().includes(searchword.toLowerCase()) ||
row.pickuplocation.toLowerCase().includes(searchword.toLowerCase()) ||
row.deliverycustomer.toLowerCase().includes(searchword.toLowerCase()) ||
row.deliverycontactno.toLowerCase().includes(searchword.toLowerCase()) ||
row.deliverylocation.toLowerCase().includes(searchword.toLowerCase()) ||
row.ridername.toLowerCase().includes(searchword.toLowerCase())
);
// to download ex format filtered data
const csvData = filteredOrders.map((order) => ({
tenantname: order.tenantname,
tenantcity: order.tenantcity,
tenantcontactno: order.tenantcontactno,
rider: order.rider,
orderid: order.orderid,
orderdate: order.orderdate,
deliverydate: order.deliverydate,
orderstatus: order.orderstatus,
deliverystatus: order.deliverystatus,
ordernotes: order.ordernotes,
kms: order.kms,
actualkms: order.actualkms,
assigntime: order.assigntime,
starttime: order.starttime,
arrivaltime: order.arrivaltime,
pickuptime: order.pickuptime,
deliverytime: order.deliverytime,
canceltime: order.canceltime,
deliverycharge: order.deliverycharge,
deliveryamt: order.deliveryamt,
pickupcustomer: order.pickupcustomer,
pickupcontactno: order.pickupcontactno,
pickupaddress: order.pickupaddress,
pickupsuburb: order.pickupsuburb,
pickupcity: order.pickupcity,
pickuplat: order.pickuplat,
pickuplong: order.pickuplong,
deliverycustomer: order.deliverycustomer,
deliverycontactno: order.deliverycontactno,
deliveryaddress: order.deliveryaddress,
deliverysuburb: order.deliverysuburb,
deliverylat: order.deliverylat,
deliverylong: order.deliverylong,
locationname: order.locationname,
locationsuburb: order.locationsuburb,
locationcity: order.locationcity,
locationcontactno: order.locationcontactno
}));
const isSelected = (name) => selected.indexOf(name) !== -1;
function formatDate(dateString) {
const date = dayjs(dateString);
const formattedDate = date.format('DD/MM/YYYY ');
return formattedDate;
}
function formatTime(dateString) {
const date = dayjs(dateString);
const formattedDate = date.format(' hh:mm A');
return formattedDate;
}
return (
<>
{startdate && enddate && (
{`Orders-${datestatus}`}
{dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
}
variant="combined"
color="warning"
size="small"
/>
)}
{(!startdate || !enddate) && (
<>
{/* ALL} variant="combined" color='warning' size='small' /> */}
>
)}
`${option.status}`}
onChange={(event, value, reason) => {
if (reason === 'clear') {
setCurrentStatus('All');
setStatusCount(status[0].count);
} else {
console.log('status', value);
setCurrentStatus(value.statusLow);
setStatusCount(value.count);
}
}}
renderInput={(params) => }
/>
setOpen(true)}
>
#
{/* Map */}
Tenant Name
Pickup
Drop
Status
Assignes
Accepted
Arrived
Picked
Delivered
Cancelled
Notes
Kms
Charges
{filteredOrders.length == 0 && (
<>
>
)}
{stableSort(filteredOrders, getComparator(order, orderBy))
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map((row, index) => {
if (typeof row === 'number') return null;
const isItemSelected = isSelected(row.name);
return (
filteredOrders.length !== 0 && (
{index + 1}
{/* {
console.log('row', row);
setMapTenant(row);
setMapOpen(true);
getdeliverylogs(row.deliveryid);
}}
>
{}
*/}
{row.tenantname}
{row.orderid}
{dayjs(row.orderdate).utc().format('DD/MM/YYYY')}
{dayjs(row.orderdate).utc().format('hh:mm A')}
{row.pickupcustomer}
{row.pickupcontactno}
{row.pickupsuburb || row.pickuplocation || row.Pickupaddress.slice(0, 20)}
{row.deliverycustomer}
{row.deliverycontactno}
{/* {row.Pickupaddress.slice(0, 20)} */}
{row.deliverysuburb || row.deliverylocation || row.deliveryaddress.slice(0, 20)}
{row.orderstatus === 'created' && }
{row.orderstatus === 'pending' && }
{row.orderstatus === 'accepted' && (
)}
{row.orderstatus === 'arrived' && (
)}
{row.orderstatus === 'picked' && }
{row.orderstatus === 'active' && }
{row.orderstatus === 'delivered' && (
)}
{row.orderstatus === 'cancelled' && }
{row.ridername}
{/* {dayjs(row.pending).format('DD/MM/YYYY')} */}
{row.assigntime === '' ? '' : formatDate(row.assigntime)}
{row.assigntime === '' ? '' : formatTime(row.assigntime)}
{' '}
{row.starttime === '' ? '' : formatDate(row.starttime)}
{row.starttime === '' ? '' : formatTime(row.starttime)}
{' '}
{row.arrivaltime === '' ? '' : formatDate(row.arrivaltime)}
{row.arrivaltime === '' ? '' : formatTime(row.arrivaltime)}
{' '}
{row.pickuptime === '' ? '' : formatDate(row.pickuptime)}
{row.pickuptime === '' ? '' : formatTime(row.pickuptime)}
{' '}
{row.deliverytime === '' ? '' : formatDate(row.deliverytime)}
{row.deliverytime === '' ? '' : formatTime(row.deliverytime)}
{' '}
{row.canceltime === '' ? '' : formatDate(row.canceltime)}
{row.canceltime === '' ? '' : formatTime(row.canceltime)}
{row.ordernotes}
)
);
})}
{/* ========================================= || bottom row || ========================================= */}
Total Charges :
Total Amount :
{/* ========================================= || Date dialog || ========================================= */}
{/* ========================================= || MapWithRoute || ========================================= */}
>
);
}