import { React, useState, useEffect, useRef } from 'react';
import axios from 'axios';
import { useQuery } from '@tanstack/react-query';
import TaskAltIcon from '@mui/icons-material/TaskAlt';
import HighlightOffIcon from '@mui/icons-material/HighlightOff';
import { Empty } from 'antd';
// material-ui
import {
Box,
Divider,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Dialog,
DialogTitle,
Typography,
DialogContent,
Stack,
Button,
IconButton,
Tooltip,
Chip,
Collapse
} from '@mui/material';
import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown';
import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp';
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';
// project imports
import MainCard from 'components/MainCard';
import Loader from 'components/Loader';
import TitleCard from '../titleCard';
import { fetchRidersSummary } from '../api/api';
import { useTheme } from '@mui/material/styles';
import { getValueColor } from 'components/nearle_components/getValueColor';
// table filter
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);
}
// ==============================|| MUI TABLE - ENHANCED ||============================== //
export default function RidersSummary() {
// const [rows, setRows] = useState([]);
const theme = useTheme();
const tenantid = localStorage.getItem('tenantid');
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(10);
const [selectedValue, setSelectedValue] = useState([]);
const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
const [locaName, setLocoName] = useState('All');
const [open, setOpen] = useState(false);
const [dateselect, setDateselect] = useState('select');
const [tabstatus1, setTabstatus1] = useState('Today');
const [datestatus, setDatestatus] = useState('Today');
const [total, settotal] = useState(0);
const [id, setid] = useState(-1);
const [tenantData, setTenantData] = useState([]);
const [openRow, setOpenRow] = useState(null); // Initially no row is open
const [searchword, setSearchword] = useState('');
const textFieldRef = useRef(null);
const [appId, setAppId] = useState(localStorage.getItem('applocationid'));
const [locations, setLocations] = useState('Select Location');
const userid = localStorage.getItem('userid');
/* ============================================= || handleKeyPress (ctrl+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);
};
}, []);
// ==============================|| fetchRidersSummary (riders summary)||============================== //
const {
isLoading: isLoadingReports,
isError: isErrorReports, //true or false
data: rows,
error: reportsError
} = useQuery({
queryKey: [tenantid, startdate, enddate],
queryFn: fetchRidersSummary
});
useEffect(() => {
rows && console.log('rows', rows);
}, [rows]);
// ==============================|| calculate||============================== //
const calculate = async () => {
let calculatedTotal = 0;
rows &&
rows.forEach((row, index) => {
console.log(index, row.Deliveryamt);
calculatedTotal += row.Deliveryamt;
});
// Update the state after the calculation is done
settotal(calculatedTotal);
console.log('calculatedTotal', calculatedTotal);
};
useEffect(() => {
rows && calculate();
}, [rows]);
if (isLoadingReports) return ;
if (isErrorReports) return 'An error has occurred:(isErrorReports) ' + reportsError.message;
// ==============================|| fetchTenantSummary by rider (rider summary)||============================== //
const fetchTenantSummary = async (riderUserid) => {
try {
const tenantRes = await axios.get(
// `${process.env.REACT_APP_URL}/deliveries/getreportlocationsummary/?&fromdate=${startdate}&todate=${enddate}&userid=${riderUserid}&tenantid=${tenantid}`
`${process.env.REACT_APP_URL}/deliveries/getriderlocationreportsummary/?&fromdate=${startdate}&todate=${enddate}&userid=${riderUserid}&tenantid=${tenantid}`
);
console.log('tenantRes', tenantRes.data.details);
setTenantData(tenantRes.data.details);
} catch (error) {
console.log('tenantRes', error);
}
};
return (
<>
{startdate && enddate && (
{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' /> */}
>
)}
}
>
{/* table */}
#
Rider
Deliveries
Pending
Assigned
Accepted
Arrived
Picked
Active
Skipped
Cancelled
Delivered
kms
COD/PLA
Charges
Action
{/* ============================================ || TableBody || ============================================ */}
{/* {rows?.length === 0 && (
)} */}
{rows?.map((row, index) => (
<>
{/* // ============================================ || tablerow 1 || ============================================ */}
{index + 1}
{row.firstname} {row.lastname}
Id : {row.userid}
{row.totalorders}
{row.pending ? : row.pending}
{row.assigned ? : row.assigned}
{row.accepted ? : row.accepted}
{row.arrived ? : row.arrived}
{row.picked ? : row.picked}
{row.active ? : row.active}
{row.skipped ? : row.skipped}
{row.cancelled ? : row.cancelled}
{row.delivered}
{/*
*/}
{
fetchTenantSummary(row.userid);
setOpenRow(openRow === row.userid ? null : row.userid);
}}
sx={{
bgcolor: openRow === row.userid ? 'primary.main' : null,
color: openRow === row.userid ? 'white' : null,
'&:hover': {
bgcolor: openRow === row.userid ? 'primary.main' : '#e1bee7'
}
}}
>
{openRow === row.userid ? : }
{/* // ============================================ || collapsive row || ============================================ */}
{openRow === row.userid && (
#
Location
All
Pending
Completed
Cancelled
Kms
COD / PLA
Amount
{tenantData?.map((row, index) => (
{index + 1}
{row.locationname}
Id: {row.locationid}
{row.totalorders}
{row.deliveriespending}
{row.deliveriescompleted}
{row.deliveriescancelled}
{/* */}
{' '}
))}
)}
>
))}
{/*
Total :
{formatNumberToRupees(total)}
*/}
{/* ================================================ || Date Filter || ================================================ */}
>
);
}