Files
dailygrubs_console/src/pages/nearle/orders/orders.js
2025-10-17 10:55:05 +05:30

831 lines
29 KiB
JavaScript

import * as React from 'react';
import { enqueueSnackbar } from 'notistack';
import { DeleteFilled } from '@ant-design/icons';
import { useState, useEffect, Fragment, useRef } from 'react';
import { Empty } from 'antd';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import axios from 'axios';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import {
Avatar,
Box,
Button,
Grid,
Tabs,
Tab,
IconButton,
Stack,
Chip,
Typography,
Table,
TableCell,
TableBody,
TableHead,
Dialog,
TableRow,
DialogContent,
DialogTitle,
Tooltip,
FormControl,
OutlinedInput,
InputAdornment,
Skeleton,
TextField,
Autocomplete
} from '@mui/material';
import { SearchOutlined, CloseOutlined } from '@ant-design/icons';
import ClearIcon from '@mui/icons-material/Clear';
import { addDays, addMonths, addWeeks, endOfMonth, endOfWeek, startOfMonth, startOfWeek } from 'date-fns';
import { DateRangePicker } from 'mui-daterange-picker';
import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import TableSortLabel from '@mui/material/TableSortLabel';
import { visuallyHidden } from '@mui/utils';
import Loader from 'components/Loader';
import { FilterList } from '@mui/icons-material';
const Orders = () => {
const tid = localStorage.getItem('tenantid');
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(10);
const [pageCountObj, setPageCountObj] = React.useState({});
const [pageCount, setPageCount] = React.useState();
const [startdate, setStartdate] = useState(dayjs().format('YYYY-MM-DD'));
const [enddate, setEnddate] = useState(dayjs().format('YYYY-MM-DD'));
const [percentage1, setPercentage1] = useState('0');
const [percentage2, setPercentage2] = useState('0');
const [percentage3, setPercentage3] = useState('0');
const [percentage4, setPercentage4] = useState('0');
let [orderarr, setArr] = useState([]);
const [coveredorders, setCoveredorders] = useState('');
const [uncoveredorders, setUncoveredorders] = useState('');
const [cancelled, setCancelled] = useState('');
const [created, setCreated] = useState('');
const [tabstatus, setTabstatus] = useState('Created');
const [loading, setLoading] = useState(true);
const theme = useTheme();
let [rows, setRows] = useState([]);
const [tabvalue, setTabvalue] = useState(0);
const [open, setOpen] = useState(false);
const [tabstatus1, setTabstatus1] = useState('Today');
const [datestatus, setDatestatus] = useState('Today');
const [searchword, setSearchword] = useState('');
const [currentStatus, setCurrentStatus] = useState('created');
const [createdLenght, setCreatedLenght] = useState();
const [pendingLenght, setPendingLenght] = useState();
const [deliveredlenght, setDeliveredlenght] = useState();
const [cancelledLenght, setCancelledLenght] = useState();
const handleChangetab = (e, i) => {
setTabvalue(i);
if (i === 0) {
setTabstatus('Created');
setCurrentStatus('created');
setPageCount(pageCountObj.created);
}
if (i === 1) {
setTabstatus('Pending');
setCurrentStatus('pending');
setPageCount(pageCountObj.pending);
}
if (i === 2) {
setTabstatus('Delivered');
setCurrentStatus('delivered');
setPageCount(pageCountObj.delivered);
}
if (i === 3) {
setTabstatus('Cancelled');
setCurrentStatus('cancelled');
setPageCount(pageCountObj.cancelled);
}
console.log(i);
};
const okclicked = () => {
setOpen(false);
};
const textFieldRef = useRef(null);
/* ============================================= || 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);
};
}, []);
useEffect(() => {
var day = 60 * 60 * 24 * 1000;
var startDate = new Date();
if (tabstatus1 === 'Tomorrow') {
setEnddate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
setStartdate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
} else if (tabstatus1 === 'Today') {
setEnddate(new Date().toISOString().substring(0, 10));
setStartdate(new Date().toISOString().substring(0, 10));
} else if (tabstatus1 === 'Week') {
setStartdate(new Date(startDate.getTime() - day * 7).toISOString().substring(0, 10));
setEnddate(new Date().toISOString().substring(0, 10));
}
}, [tabstatus1]);
const fetchtablecovered = async () => {
try {
await axios
.get(
`${
process.env.REACT_APP_URL
}/orders/tenant/getorders/?tenantid=${tid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
page + 1
}&pagesize=${rowsPerPage}&keyword=${searchword}`
)
.then((res) => {
setArr(res.data.details);
setRows(res.data.details);
})
.catch((err) => {
console.log(err);
});
} catch (err) {
console.log(err);
}
};
useEffect(() => {
fetchtablecovered();
}, [tabstatus, startdate, enddate, page, rowsPerPage, searchword]);
const fetchpercentage = async () => {
setLoading(true);
try {
await axios
.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}`)
.then((res) => {
console.log(res);
setCoveredorders(res.data.details.delivered.toString());
setCancelled(res.data.details.cancelled.toString());
setUncoveredorders(res.data.details.pending.toString());
setCreated(res.data.details.created.toString());
setPercentage1((Math.round((res.data.details.created / res.data.details.total) * 100) || 0).toString());
setPercentage3((Math.round((res.data.details.delivered / res.data.details.total) * 100) || 0).toString());
setPercentage4((Math.round((res.data.details.cancelled / res.data.details.total) * 100) || 0).toString());
setPercentage2((Math.round((res.data.details.pending / res.data.details.total) * 100) || 0).toString());
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
} catch (err) {
console.log(err);
setLoading(false);
}
};
useEffect(() => {
fetchpercentage();
}, []);
const fetchorderscount = async () => {
setLoading(true);
try {
await axios
.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}&fromdate=${startdate}&todate=${enddate}`)
.then((res) => {
console.log('fetchorderscount', res.data.details);
setCreatedLenght(res.data.details.created);
setPendingLenght(res.data.details.pending);
setDeliveredlenght(res.data.details.delivered);
setCancelledLenght(res.data.details.cancelled);
tabvalue === 0 && setPageCount(res.data.details.created);
tabvalue === 1 && setPageCount(res.data.details.pending);
tabvalue === 2 && setPageCount(res.data.details.delivered);
tabvalue === 3 && setPageCount(res.data.details.cancelled);
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
} catch (err) {
console.log(err);
setLoading(false);
}
};
useEffect(() => {
fetchorderscount();
}, [tabvalue]);
const headCells = [
{
id: 'sno',
disablePadding: true,
label: 'S NO'
},
{
id: 'orderid',
numeric: false,
disablePadding: false,
label: 'ORDER ID'
},
{
id: 'eventname',
disablePadding: false,
label: 'Pickup'
},
{
id: 'eventname4',
disablePadding: false,
label: 'Delivery'
},
{
id: 'itemcount',
disablePadding: false,
label: 'NOTES'
},
{
id: 'orderstatus',
disablePadding: false,
label: 'STATUS'
},
{
id: 'action',
disablePadding: false,
label: 'ACTION'
}
];
function EnhancedTableHead(props) {
const { order, orderBy, onRequestSort } = props;
const createSortHandler = (property) => (event) => {
onRequestSort(event, property);
};
return (
<TableHead>
<TableRow>
{headCells.map((headCell) => (
<TableCell
key={headCell.id}
align={headCell.numeric ? 'right' : 'left'}
padding={headCell.disablePadding ? 'none' : 'normal'}
sortDirection={orderBy === headCell.id ? order : false}
>
<TableSortLabel
active={orderBy === headCell.id}
direction={orderBy === headCell.id ? order : 'asc'}
onClick={createSortHandler(headCell.id)}
>
{headCell.label}
{orderBy === headCell.id ? (
<Box component="span" sx={visuallyHidden}>
{order === 'desc' ? 'sorted descending' : 'sorted ascending'}
</Box>
) : null}
</TableSortLabel>
</TableCell>
))}
</TableRow>
</TableHead>
);
}
function EnhancedTable() {
const [open, setOpen] = useState(false);
const [orderheaderid, setOrderheaderid] = useState('');
const cancelorder = async () => {
await axios
.put(`${process.env.REACT_APP_URL}/orders/updateorder`, {
orderheaderid: orderheaderid,
orderstatus: 'cancelled',
cancelled: dayjs().format('YYYY-MM-DD HH:mm:ss')
})
.then((res) => {
console.log(res);
if (res.data.status) {
enqueueSnackbar('Order Cancelled Successfully', {
variant: 'success',
anchorOrigin: { vertical: 'top', horizontal: 'right' },
autoHideDuration: 2000
});
handleClose(true);
fetchtablecovered();
fetchorderscount();
}
})
.catch((err) => {
console.log(err);
});
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const handleChangeRowsPerPage = (event) => {
setRowsPerPage(parseInt(event.target.value, 10));
setPage(0);
};
const handleClose = () => {
setOpen(false);
setOrderheaderid('');
};
function AlertCustomerDelete({
// title,
open,
handleClose
}) {
// const [deletepassword, setDeletepassword] = useState('');
return (
<Dialog open={open} onClose={() => handleClose(false)} maxWidth="xs">
<DialogContent sx={{ mt: 2, my: 1 }}>
<Stack alignItems="center" spacing={3.5}>
<Avatar color="error" sx={{ width: 72, height: 72, fontSize: '1.75rem' }}>
<DeleteFilled />
</Avatar>
{/* <Grid >
<Chip label={orderid.slice(4)} variant="combined" color='warning' size='small' />
</Grid> */}
<Stack spacing={2}>
<Typography variant="h4" align="center">
Are you sure you want to cancel this order?
</Typography>
{/* <Typography variant="h4" align="center">
Please type in the order number to confirm.
</Typography> */}
</Stack>
<Stack direction="row" spacing={2} sx={{ width: 1 }}>
<Button
fullWidth
color="error"
variant="contained"
onClick={() => {
// if (deletepassword === orderid.slice(4)) {
cancelorder();
// }
}}
autoFocus
>
Yes, Cancel
</Button>
<Button
fullWidth
onClick={() => {
handleClose(false);
}}
color="secondary"
variant="outlined"
>
No
</Button>
</Stack>
</Stack>
</DialogContent>
</Dialog>
);
}
return (
<Box sx={{ width: '100%' }}>
<AlertCustomerDelete open={open} handleClose={handleClose} />
<TableContainer sx={{ width: '100%', borderBottom: 1, borderColor: 'divider' }}>
<Table sx={{ minWidth: 750 }} aria-label="collapsible table" size={'medium'}>
<EnhancedTableHead />
{loading && (
<>
<TableBody>
{[0, 1, 2, 3, 4, 5, 6, 7, 8, 9].map((item, index) => (
<TableRow key={index}>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
<TableCell>
<Skeleton animation="wave" />
</TableCell>
</TableRow>
))}
</TableBody>
</>
)}
<TableBody>
{rows?.length == 0 && (
<>
<TableCell colSpan={7}>
<Stack width={'100%'} direction={'row'} justifyContent={'center'}>
<Empty />
</Stack>
</TableCell>
</>
)}
{rows?.map((row, index) => {
return (
<>
<TableRow
key={index}
sx={{
cursor: 'pointer'
}}
>
<TableCell padding="none">
<Typography> {page * rowsPerPage + index + 1}</Typography>
</TableCell>
<TableCell align="left">
<Typography variant="body2" noWrap>
{row.orderid}
</Typography>
<Typography noWrap sx={{ fontSize: '11px' }}>
{dayjs(row.deliverydate).utc().format('DD/MM/YYYY')}
</Typography>
<Typography noWrap sx={{ fontSize: '11px' }} variant="h5">
{dayjs(row.deliverydate).utc().format('hh:mm A')}
</Typography>
</TableCell>
<TableCell align="left">
<Stack direction={'row'} spacing={1}>
<Avatar
alt=""
size="sm"
sx={{
width: '25px',
height: '25px'
}}
></Avatar>
<Stack direction="column">
<Typography variant="caption">{row.pickupcustomer}</Typography>
<Typography variant="caption" color="textSecondary">
{row.pickupcontactno}
</Typography>
<Tooltip title={row.pickupaddress}>
<Typography variant="caption" color="textSecondary">
{row.pickupsuburb || row.pickupaddress.slice(0, 20)}
</Typography>
</Tooltip>
</Stack>
</Stack>
</TableCell>
<TableCell align="left">
<Stack direction={'row'} spacing={1}>
<Avatar
alt=""
size="sm"
sx={{
width: '25px',
height: '25px'
}}
></Avatar>
<Stack direction="column">
<Typography variant="caption">{row.deliverycustomer}</Typography>
<Typography variant="caption" color="textSecondary">
{row.deliverycontactno}
</Typography>
<Tooltip title={row.deliveryaddress}>
<Typography variant="caption" color="textSecondary">
{/* {row.pickupaddress.slice(0, 20)} */}
{row.deliverysuburb || row.deliveryaddress.slice(0, 20)}
</Typography>
</Tooltip>
</Stack>
</Stack>
</TableCell>
<TableCell align="left">{row.ordernotes}</TableCell>
{/* <TableCell align="left"><Chip label={row.itemcount} color="primary" variant="light" size="small" /></TableCell> */}
<TableCell align="left">
<Stack direction="row">
{row.orderstatus === 'pending' && <Chip label="Pending" color="warning" size="small" />}
{row.orderstatus === 'modified' && <Chip label="Confirmed" color="success" size="small" />}
{row.orderstatus === 'cancelled' && <Chip label="Cancelled" color="error" size="small" />}
{row.orderstatus === 'delivered' && <Chip label="Completed" color="primary" size="small" />}
{row.orderstatus === 'processing' && <Chip label="Processing" color="primary" size="small" />}
{row.orderstatus === 'ready' && <Chip label="Accepted" color="info" size="small" />}
{row.orderstatus === 'confirmed' && <Chip label="Confirmed" color="success" size="small" />}
{row.orderstatus === 'active' && <Chip label="Picked" color="info" size="small" />}
{row.orderstatus === 'closed' && <Chip label="Closed" color="info" size="small" />}
{row.orderstatus === 'created' && <Chip label="Created" color="secondary" size="small" />}
</Stack>
</TableCell>
<TableCell>
{row.orderstatus == 'created' && (
<>
<Tooltip title="Cancel">
<IconButton
// disabled={(row.orderstatus != 'created')}
onClick={(e) => {
e.stopPropagation();
setOrderheaderid(row.orderheaderid);
setOpen(true);
}}
>
<CloseOutlined
style={{
color: theme.palette.error.main
}}
// twoToneColor={theme.palette.primary.main}
/>
</IconButton>
</Tooltip>
</>
)}
</TableCell>
</TableRow>
</>
);
})}
</TableBody>
</Table>
</TableContainer>
<TablePagination
rowsPerPageOptions={[5, 10, 25, 50, 100]}
component="div"
count={pageCount || 0}
rowsPerPage={rowsPerPage || 0}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
/>
</Box>
);
}
return (
<>
{loading && <Loader />}
<Stack direction={{ xs: 'column', md: 'row' }} justifyContent="space-between" alignItems="center" spacing={2}>
<Typography variant="h3">Orders</Typography>
</Stack>
<Grid container spacing={3} sx={{ mt: 0.1 }}>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Created Orders"
secondary={created === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : created}
percentage={percentage1.toString()}
color={theme.palette.primary.main}
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Pending orders"
secondary={uncoveredorders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : uncoveredorders}
percentage={percentage2.toString()}
color={theme.palette.warning.main}
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Delivered orders"
secondary={coveredorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : coveredorders}
percentage={percentage3.toString()}
color={theme.palette.success.main}
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Cancelled Orders"
secondary={cancelled === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : cancelled}
percentage={percentage4.toString()}
color={theme.palette.secondary[600]}
/>
</Grid>
</Grid>
<Stack direction={'row'} justifyContent={'space-between'} alignItems={'center'} sx={{ my: 2 }}>
{startdate && enddate && (
<Stack direction="row" spacing={2}>
<Chip label={`Orders-${datestatus ? datestatus : ''}`} color="primary" variant="light" size="small" />
<Chip
label={
<Typography noWrap color="secondary">
{dayjs(startdate).format('DD/MM/YYYY')} - {dayjs(enddate).format('DD/MM/YYYY')}
</Typography>
}
variant="combined"
color="warning"
size="small"
/>
</Stack>
)}
<Tooltip title="Order Filter">
<IconButton
color="secondary"
variant="light"
sx={{ color: 'text.primary', bgcolor: 'grey.200', display: { xs: 'none', md: 'flex' } }}
aria-haspopup="true"
onClick={() => setOpen(true)}
>
<FilterList />
</IconButton>
</Tooltip>
</Stack>
<Grid item xs={12}>
<Box sx={{ overflow: 'auto', border: 1, borderColor: 'grey.200', borderRadius: 2, backgroundColor: '#fff', minHeight: 350 }}>
<Stack
alignItems="center"
justifyContent="space-between"
direction="row"
sx={{
p: 2,
width: '100%'
}}
>
<Tabs value={tabvalue} onChange={handleChangetab} variant="scrollable" scrollButtons="auto">
<Tab label="Created" icon={<Chip label={createdLenght} color="primary" variant="light" size="small" />} iconPosition="end" />
<Tab label="Pending" icon={<Chip label={pendingLenght} color="primary" variant="light" size="small" />} iconPosition="end" />
<Tab
label="Delivered"
icon={<Chip label={deliveredlenght} color="primary" variant="light" size="small" />}
iconPosition="end"
/>
<Tab
label="Cancelled"
icon={<Chip label={cancelledLenght} color="primary" variant="light" size="small" />}
iconPosition="end"
/>
</Tabs>
<Stack>
<FormControl sx={{ width: 250, display: { xs: 'none', md: 'flex' } }}>
<OutlinedInput
inputRef={textFieldRef}
size="small"
id="header-search"
aria-describedby="header-search-text"
inputProps={{
'aria-label': 'weight'
}}
placeholder="Search (ctrl+k)"
value={searchword}
onChange={(e) => {
setSearchword(e.target.value);
}}
autoComplete="off"
startAdornment={
<InputAdornment position="start" sx={{ mr: -0.5 }}>
<SearchOutlined style={{ color: theme.palette.primary.main }} />
</InputAdornment>
}
endAdornment={
<Tooltip title="clear">
<IconButton
sx={{ visibility: searchword ? 'visible' : 'hidden' }}
onClick={() => {
setSearchword('');
fetchtablecovered();
fetchorderscount();
}}
>
<ClearIcon fontSize="small" sx={{ color: theme.palette.primary.main }} />
</IconButton>
</Tooltip>
}
/>
</FormControl>
</Stack>
</Stack>
<Box sx={{ width: '100%', display: 'table', tableLayout: 'fixed' }}>
<EnhancedTable />
</Box>
</Box>
</Grid>
<Dialog open={open}>
<DialogTitle align="left">
<Typography variant="h4">Select Filter Options</Typography>
</DialogTitle>
<DialogContent sx={{ width: '100%' }} className="datedialog">
<DateRangePicker
open={open}
toggle={() => setOpen(!open)}
id="daterange1"
onChange={(range) => {
if (range.label === 'All') {
setStartdate('');
setEnddate('');
setOpen(false);
} else {
setStartdate(dayjs(range.startDate).format('YYYY-MM-DD'));
setEnddate(dayjs(range.endDate).format('YYYY-MM-DD'));
if (range.label) {
setDatestatus(range.label);
} else {
setDatestatus('');
}
}
console.log(range);
}}
definedRanges={[
{
label: 'Today',
startDate: new Date(),
endDate: new Date()
},
{
label: 'Yesterday',
startDate: addDays(new Date(), -1),
endDate: addDays(new Date(), -1)
},
{
label: 'Tomorrow',
startDate: addDays(new Date(), +1),
endDate: addDays(new Date(), +1)
},
{
label: 'This Week',
startDate: startOfWeek(new Date()),
endDate: endOfWeek(new Date())
},
{
label: 'Last Week',
startDate: startOfWeek(addWeeks(new Date(), -1)),
endDate: endOfWeek(addWeeks(new Date(), -1))
},
{
label: 'Last 7 Days',
startDate: addWeeks(new Date(), -1),
endDate: new Date()
},
{
label: 'This Month',
startDate: startOfMonth(new Date()),
endDate: endOfMonth(new Date())
},
{
label: 'Last Month',
startDate: startOfMonth(addMonths(new Date(), -1)),
endDate: endOfMonth(addMonths(new Date(), -1))
}
// {
// label: 'All',
// startDate: new Date(),
// endDate: addDays(new Date(), -1),
// },
]}
/>
</DialogContent>
<Stack direction="row" justifyContent="flex-end" sx={{ width: '100%', p: 2 }}>
<Button variant="contained" size="small" onClick={okclicked}>
ok
</Button>
</Stack>
</Dialog>
</>
);
};
export default Orders;