orderdetails , orders

This commit is contained in:
joshikannan
2025-10-17 10:55:05 +05:30
parent 36eaf3d845
commit e6c8df5583
13 changed files with 592 additions and 1240 deletions

View File

@@ -766,7 +766,7 @@ const Createorder1 = () => {
enqueueSnackbar(message, {
variant: variant,
anchorOrigin: { vertical: 'top', horizontal: 'right' },
autoHideDuration: time ? time : 1500
autoHideDuration: time ? time : 2000
});
console.log(alertmessage);
};
@@ -829,7 +829,6 @@ const Createorder1 = () => {
pickuplocation: pickCust.suburb || '',
pickuplocationid: pickCust.deliverylocationid || 0,
pickuplong: pickCust.longitude.toString(),
pickupaddress: pickCust.address || '',
processing: '',
ready: '',
remarks: '',
@@ -943,10 +942,10 @@ const Createorder1 = () => {
navigate('/orders');
} else {
opentoast(res.data.message, 'warning');
opentoast('Something went wrong, Cannot create order', 'warning');
}
setLoading(false);
console.log(res);
console.log(createRes);
} catch (error) {
console.log('createResErr', error);
}
@@ -1318,7 +1317,7 @@ const Createorder1 = () => {
disablePortal
id="combo-box-demo"
options={tenantLocations || []}
getOptionLabel={(option) => `${option.locationname} (${option.locationsuburb})` || ''}
getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
sx={{ width: 300 }}
renderInput={(params) => <TextField {...params} label="Select Business Locations" />}
onChange={(event, value, reason) => {

View File

@@ -23,13 +23,9 @@ import {
Grid,
Typography,
Stack,
Box,
Button,
TextField,
Autocomplete,
CardActions,
Chip,
Avatar,
Divider,
Dialog,
DialogTitle,
@@ -37,16 +33,7 @@ import {
Checkbox,
DialogActions,
CircularProgress,
ButtonGroup,
FormLabel,
IconButton,
Drawer,
InputLabel,
Select,
MenuItem,
Switch,
CardHeader,
Card,
OutlinedInput,
FormGroup,
FormControlLabel,
@@ -58,75 +45,42 @@ import {
Paper,
TableHead
} from '@mui/material';
import { log } from 'util';
import CircularLoader from 'components/nearle_components/CircularLoader';
const MultipleOrders = () => {
const navigate = useNavigate();
const theme = useTheme();
const [locaName, setLocoName] = useState('Select Location');
const [locations, setLocations] = useState([]);
const [tenantlist, setTenantlist] = useState([]);
const [loading, setLoading] = useState(false);
const [btnLoading, setBtnLoading] = useState(false);
const [appId, setAppId] = useState(0);
const [isAppLocation, setIsAppLocation] = useState(false);
const [isBusiness, setIsBusiness] = useState(false);
const [isClient, setisclient] = useState(false);
const [tenantLocations, setTenantlocations] = useState([]);
const userid = localStorage.getItem('userid');
const tenId = localStorage.getItem('tenantid');
const [tenantid, setTenantid] = useState();
const [tid, setTid] = useState(0);
const [tenanatLocoId, setTenanatLocoId] = useState(localStorage.getItem('locationid'));
const [tenantlocation, setTenantlocation] = useState('');
const [isLocation, setIsLocation] = useState(false);
const [basePrice, setBasePrice] = useState(0);
const [pricePerKm, setPricePerKm] = useState(0);
const [minKm, setMinKm] = useState(0);
const [tenantinfo, setTenantinfo] = useState({});
const [pickCust, setPickCust] = useState({});
const [dropCust, setDropCust] = useState([]);
const [isCustomerOpen, setIsCustomerOpen] = useState(false);
const [searchCustList, setSearchCustList] = useState('');
const [customerlist, setCustomerlist] = useState([]);
const [clientdetail, setClientdetail] = useState([]);
const [appLocaLat, setAppLocaLat] = useState();
const [appLocaLng, setAppLocaLng] = useState();
const [appLocaRadius, setAppLocaRadius] = useState();
const [startdate, setStartdate] = useState(dayjs().format('MM-DD-YYYY'));
const [timeslotarr, setTimeslotarr] = useState([]);
const [showDistance, setShowDistance] = useState(false);
const [subCat, setSubCat] = useState([]);
const [subCatName, setSubCatName] = useState('Select ');
const [subCatId, setSubCatId] = useState(0);
const [weight, setWeight] = useState('');
const [selectedCatChip, setSelectedCatChip] = useState(null);
const [isSms, setIsSms] = useState(0);
const [starttime, setStatrttime] = useState();
const [endtime, setEndtime] = useState();
const [selectedtime, setSelectedtime] = useState('');
const [distance, setDistance] = useState(0);
const [alertmessage, setAlertmessage] = useState('');
const [otherinstructions, setOtherinstructions] = useState('');
const [totalCharge, setTotalCharge] = useState(0);
const [admintoken, setAdmintoken] = useState();
const [tenant, setTenant] = useState(0);
const [totaldist, settotaldist] = useState(0);
const [totalAmt, settotalAmt] = useState(0);
const [isLoading, setIsLoading] = useState(false);
// =============================================== || chipStyle ( time slot) || ===============================================
const chipStyle = (chipLabel) => ({
cursor: 'pointer',
backgroundColor: selectedCatChip === chipLabel ? theme.palette.primary.main : 'default',
color: selectedCatChip === chipLabel ? '#fff' : '',
'&:hover': {
backgroundColor: selectedCatChip === chipLabel ? theme.palette.primary.main : theme.palette.primary.light,
color: '#fff'
}
});
const handleChipClick = (chipLabel) => {
setSelectedCatChip(chipLabel);
};
useEffect(() => {
console.log('dropCust', dropCust);
}, [dropCust]);
// =============================================== || opentoast || ===============================================
const opentoast = (message, variant, time) => {
@@ -141,13 +95,7 @@ const MultipleOrders = () => {
const fetchAppLocations = async () => {
try {
const locationRes = await axios.get(`${process.env.REACT_APP_URL}/partners/getlocations/?userid=${userid}`);
// const updatedLocations = [
// ...locationRes.data.details,
// { partnername: 'All', applocationid: -1 }
// ];
// console.log('fetchAppLocations', updatedLocations);
console.log('fetchAppLocations', locationRes.data.details);
setLocations(locationRes.data.details);
} catch (err) {
console.log('locationRes', err);
}
@@ -156,32 +104,6 @@ const MultipleOrders = () => {
fetchAppLocations();
}, []);
// ===================================================== || fetchtenantinfolist || =====================================================
const fetchtenantinfolist = async (id) => {
setLoading(true);
await axios
.get(`${process.env.REACT_APP_URL}/tenants/gettenants/?applocationid=${id}&status=active`)
.then((res) => {
console.log(res);
if (res.data.status) {
let arr = [];
res.data.details.map((val) => {
arr.push({
...val,
label: `${val.tenantname}`
});
});
setTenantlist(arr);
}
setLoading(false);
})
.catch((err) => {
console.log(err);
setLoading(false);
});
};
// ============================================= || fetchTenantPricing || =============================================
const fetchTenantPricing = async (id) => {
@@ -207,12 +129,8 @@ const MultipleOrders = () => {
setIsLocation(true);
setTenantlocations(res.data.details);
setPickCust(res.data.details[0]);
setTenanatLocoId(res.data.details[0].locationid);
setTenantlocation(res.data.details[0].locationaddress); //client address
setIsBusiness(true);
} else {
setTenantlocations(res.data.details);
setIsBusiness(false); // became true after select from tenanatLocations
}
} catch (err) {
console.log('gettenantlocations', err);
@@ -234,7 +152,6 @@ const MultipleOrders = () => {
if (res.data.status) {
console.log('clientdetails', res.data.details);
setClientdetail(res.data.details);
setCustomerlist(res.data.details);
let arr = [];
res.data.details.map((val) => {
@@ -276,11 +193,15 @@ const MultipleOrders = () => {
// ========================================================= || handleCheckboxChange || =========================================================
const handleCheckboxChange = async (event, customer) => {
setIsLoading(true);
console.log('event', event.target.checked);
console.log('customer', customer);
if (event.target.checked) {
// If the checkbox is checked, calculate the distance and add the customer
try {
const obj = await calculateDistance(customer);
console.log('return of calculateDistance', obj);
const { roundedDistance, totalcharge } = obj;
// Create a new customer object with the distance property
const updatedCustomer = {
@@ -297,32 +218,42 @@ const MultipleOrders = () => {
} catch (error) {
console.error('Failed to calculate distance:', error);
}
setIsLoading(false);
} else {
// If the checkbox is unchecked, remove the customer from dropCust
setDropCust((prevDropCust) => {
return prevDropCust.filter((cust) => cust.customerid !== customer.customerid);
});
setIsLoading(false);
}
};
// ========================================================= || calculateDistance || =========================================================
const calculateDistance = async (customer) => {
console.log('Distance calculation starts');
const service = new google.maps.DistanceMatrixService();
// Helper function to get the distance matrix
const getDistanceMatrix = (origins, destinations) => {
const getDistanceMatrix = async (origins, destinations) => {
console.log('origins', origins);
console.log('destinations', destinations);
return new Promise((resolve, reject) => {
console.log('calculation starts');
service.getDistanceMatrix(
{
origins: [new google.maps.LatLng(origins.locationlatitude, origins.locationlong)],
origins: [new google.maps.LatLng(origins.latitude, origins.longitude)],
destinations: [new google.maps.LatLng(destinations.latitude, destinations.longitude)],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC // Distances in metric units (km)
},
(response, status) => {
console.log('cal response', response);
console.log('cal status', status);
if (status === 'OK') {
console.log('calcualtion resolved');
resolve(response);
} else {
console.log('calcualtion rejected');
reject(new Error(`Error calculating distance: ${status}`));
}
}
@@ -348,14 +279,12 @@ const MultipleOrders = () => {
console.log('pricePerKm', pricePerKm);
console.log('basePrice', basePrice);
totalcharge = basePrice;
setTotalCharge(basePrice);
} else {
console.log('minKm', minKm);
console.log('pricePerKm', pricePerKm);
console.log('basePrice', basePrice);
totalcharge = (roundedDistance - minKm) * pricePerKm + basePrice;
console.log('totalcharge', totalcharge);
setTotalCharge(totalcharge);
}
// Return the rounded distance
@@ -375,9 +304,6 @@ const MultipleOrders = () => {
console.log('fetchTiming', res);
const { opentime, closetime, latitude, longitude, radius } = res.data.details[0];
if (res.data.status) {
setAppLocaLat(latitude);
setAppLocaLng(longitude);
setAppLocaRadius(radius);
setStatrttime(`${dayjs().format('MM-DD-YYYY')} ${opentime}`);
setEndtime(`${dayjs().format('MM-DD-YYYY')} ${closetime}`);
console.log('starttime', `${dayjs().format('MM-DD-YYYY')} ${opentime}`);
@@ -405,23 +331,7 @@ const MultipleOrders = () => {
fetchTiming();
}
}, [starttime, endtime, appId]);
// ==================================================== || getsubcategories || ====================================================
const getsubcategories = async () => {
await axios
.get(`${process.env.REACT_APP_URL}/utils/getsubcategories/?moduleid=6`)
.then((res) => {
console.log('subcateRes', res.data.details);
if (res.data.status) {
setSubCat(res.data.details);
}
})
.catch((err) => {
console.log(err);
});
};
useEffect(() => {
getsubcategories();
}, []);
const fetchAppAdminTokens = async () => {
setLoading(true);
await axios
@@ -463,11 +373,7 @@ const MultipleOrders = () => {
.then((res) => {
console.log('fetchtenantinfo', res);
if (res.data.status) {
setTenant(res.data.details);
setTenantid(res.data.details.tenantid);
fetchAppAdminTokens();
setSubCatName(res.data.details.subcategoryname);
setSubCatId(res.data.details.subcategoryid);
}
setLoading(false);
})
@@ -525,7 +431,7 @@ const MultipleOrders = () => {
cancellled: '',
// categoryid: +tenant.categoryid,
configid: 9,
customerid: 0,
customerid: customer.customerid,
deliveryaddress: customer.address || '',
deliverycharge: +customer.totalcharge || 0,
deliverycity: customer.city || '',
@@ -533,10 +439,10 @@ const MultipleOrders = () => {
deliverycustomer: customer.firstname || '',
deliveryid: +customer.customerid,
deliverylandmark: customer.landmark || '',
deliverylat: customer.latitude.toString(),
deliverylat: customer.latitude,
deliverylocation: customer.suburb || '',
deliverylocationid: customer.deliverylocationid || 0,
deliverylong: customer.longitude.toString(),
deliverylong: customer.longitude,
// deliverytime: `${dayjs(startdate).format('YYYY-MM-DD HH:mm:ss')} `,
deliverytime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
deliverytype: 'B',
@@ -558,20 +464,18 @@ const MultipleOrders = () => {
paymentstatus: 1,
paymenttype: 42,
pending: '',
pickupaddress: pickCust.locationaddress || '',
pickupaddress: pickCust.address || '',
pickupcity: pickCust.locationcity || '',
pickupcontactno: pickCust.locationcontact || '',
pickupcontactno: pickCust.contactno || '',
pickupcustomer: pickCust.locationname || '',
pickuplandmark: pickCust.landmark || '',
pickuplat: pickCust.locationlatitude.toString(),
pickuplocation: pickCust.locationsuburb || '',
pickuplat: pickCust.latitude,
pickuplocation: pickCust.suburb || '',
pickuplocationid: pickCust.locationid || 0,
pickuplong: pickCust.locationlong.toString(),
pickuplong: pickCust.longitude,
processing: '',
ready: '',
remarks: '',
// smsdelivery: isSms,
// subcategoryid: +subCatId,
taxamount: 0.0,
tenantid: pickCust.tenantid,
tenantuserid: 0
@@ -656,23 +560,19 @@ const MultipleOrders = () => {
// disabled={!isAppLocation || !isClient}
id="combo-box-demo"
options={tenantLocations || []}
getOptionLabel={(option) => `${option.locationname} (${option.locationsuburb})` || ''}
renderInput={(params) => <TextField {...params} label="Select Business Locations" focused color="primary" />}
getOptionLabel={(option) => `${option.locationname} (${option.suburb})` || ''}
renderInput={(params) => <TextField {...params} label="Select Business Locations" color="primary" />}
sx={{ width: '350px' }}
onChange={(event, value, reason) => {
if (value) {
console.log('Business Locations', value);
console.log('locationid', value.locationid);
setTenanatLocoId(value.locationid);
setTid(value.tenantid);
setTenantlocation(value.locationaddress);
setIsLocation(true);
setIsBusiness(true);
setPickCust(value);
}
if (reason == 'clear') {
setIsLocation(false);
setIsBusiness(false);
}
}}
/>
@@ -693,7 +593,7 @@ const MultipleOrders = () => {
let dateres11 = dayjs().diff(dayjs(`${dayjs(e).format('YYYY-MM-DD')}`), 'd');
console.log('dateres11');
console.log(dateres11);
setSelectedtime('');
if (dateres11 <= 0) {
console.log('startdate', e);
setStartdate(e);
@@ -744,7 +644,7 @@ const MultipleOrders = () => {
<TableBody>
<TableRow>
<TableCell>{pickCust.locationname}</TableCell>
<TableCell>{pickCust.locationaddress}</TableCell>
<TableCell>{pickCust.address}</TableCell>
</TableRow>
</TableBody>
</Table>
@@ -830,175 +730,7 @@ const MultipleOrders = () => {
</TableContainer>
</MainCard>
</Grid>
{/* ================================================= || Time || ================================================= */}
{/* <Grid item xs={12} sx={{ width: '100%', mt: -2 }}>
<MainCard sx={{ mt: 2, height: '390px' }}>
<Grid container spacing={4}>
<Grid item xs={12} md={6}>
<Typography variant="h5">Date</Typography>
<LocalizationProvider dateAdapter={AdapterDayjs} sx={{}}>
<DatePicker
format="DD-MM-YYYY"
onChange={(e) => {
let dateres11 = dayjs().diff(dayjs(`${dayjs(e).format('YYYY-MM-DD')}`), 'd');
console.log('dateres11');
console.log(dateres11);
setSelectedtime('');
if (dateres11 <= 0) {
console.log('startdate', e);
setStartdate(e);
let arr = [];
timeslotarr.map((val) => {
if (dayjs().diff(dayjs(`${dayjs(e).format('MM-DD-YYYY')} ${dayjs(val).format('HH:mm:ss')}`), 'm') <= 0) {
arr.push(val);
}
});
if (arr[0]) {
setOrderarr([
{
sno: 1,
address: '',
customerid: '',
deliverytime: dayjs(arr[0]) || '',
deliverylocationid: '',
clientname: '',
contactno: '',
latitude: '',
longitude: ''
}
]);
} else {
setOrderarr([]);
}
} else {
setAlertmessage('choose Upcoming Date');
opentoast('choose Upcoming Date', 'warning');
setStartdate(NaN);
}
}}
value={dayjs(startdate)}
sx={{ width: '100%', mt: 2 }}
disablePast
/>
</LocalizationProvider>
<Typography variant="h5" sx={{ my: 2 }}>
Time
</Typography>
<MainCard
sx={{
height: '210px',
mt: 1,
overflowY: 'scroll',
'&::-webkit-scrollbar': {
width: '3px', // Width of vertical scrollbar
height: '10px' // Height of horizontal scrollbar
},
'&::-webkit-scrollbar-thumb': {
backgroundColor: '#65387A' // Color of the scrollbar thumb
}
}}
>
<Grid container spacing={2}>
{timeslotarr.map((val, index) => {
if (dayjs().diff(dayjs(`${dayjs(startdate).format('MM-DD-YYYY')} ${dayjs(val).format('HH:mm:ss')}`), 'm') <= 0) {
return (
<Fragment key={index}>
<Grid item>
<Chip
key={index}
sx={{ cursor: 'pointer' }}
color={dayjs(selectedtime).format('HH:mm') == dayjs(val).format('HH:mm') ? 'primary' : 'default'}
label={dayjs(val).format('hh:mm A')}
onClick={() => {
setSelectedtime(val);
}}
/>
</Grid>
</Fragment>
);
}
})}
</Grid>
</MainCard>
</Grid>
<Grid item xs={12} sm={6} sx={{}}>
{showDistance && (
<Stack sx={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', mb: 3 }}>
<Stack spacing={1.5}>
<Chip label={`Distance: ${distance} km`} size="medium" variant="contained" color="primary" />
</Stack>
<Stack spacing={1.5}>
<Chip label={`Charge: ₹${totalCharge.toFixed(2)}`} size="medium" variant="contained" color="primary" />
</Stack>
</Stack>
)}
<Stack direction={'column'} justifyContent={'space-between'} sx={{ mb: 2 }}>
<Typography variant="h5">Category</Typography>
<Autocomplete
// disablePortal
id="combo-box-demo"
options={subCat}
getOptionLabel={(option) => `${option.subcategoryname}` || ''}
sx={{ my: 2, zIndex: '99' }}
fullWidth
renderInput={(params) => <TextField {...params} label={subCatName == '' ? tenant.subcategoryname : subCatName} />}
onChange={(event, value, reason) => {
if (value) {
console.log(value);
setSubCatName(value.subcategoryname);
setSubCatId(value.subcategoryid);
}
}}
/>
</Stack>
<Typography variant="h5">Weight</Typography>
<Stack direction={'row'} justifyContent={'space-evenly'} sx={{ border: '1px solid #eee', my: 2, py: 2 }}>
<Chip
variant="contained"
color="default"
label="1-10kgs"
sx={chipStyle('1-10kgs')}
onClick={() => {
handleChipClick('1-10kgs');
setWeight('1-10kgs');
}}
/>
<Chip
variant="contained"
color="default"
label="11-20kgs"
sx={chipStyle('11-20kgs')}
onClick={() => {
handleChipClick('11-20kgs');
setWeight('11-20kgs');
}}
/>
<Chip
variant="contained"
color="default"
label="21-30kgs"
sx={chipStyle('21-30kgs')}
onClick={() => {
handleChipClick('21-30kgs');
setWeight('21-30kgs');
}}
/>
</Stack>
<Stack direction={'row'} justifyContent={'space-between'} sx={{ mt: 4 }}>
<Typography variant="h5">SMS Delivery</Typography>
<Switch
checked={isSms === 1}
onChange={(e) => {
setIsSms(e.target.checked ? 1 : 0);
}}
/>
</Stack>
</Grid>
</Grid>
</MainCard>
</Grid> */}
<Grid item xs={12} sx={{ width: '100%', mt: -2 }}>
{/* ================================================= || Notes || ================================================= */}
<MainCard sx={{ mt: 2 }} title={'Notes'}>
@@ -1052,6 +784,7 @@ const MultipleOrders = () => {
fullWidth
sx={{ minWidth: 'lg' }}
>
{isLoading && <CircularLoader />}
<DialogTitle sx={{ bgcolor: theme.palette.primary.main, color: 'white' }}>
<Stack>
<Typography variant="h4"> {`Select Drop Customers (${dropCust.length || 0})`}</Typography>

View File

@@ -1,15 +1,12 @@
import * as React from 'react';
import { enqueueSnackbar } from 'notistack';
import { DeleteFilled, NotificationOutlined } from '@ant-design/icons';
import { DeleteFilled } from '@ant-design/icons';
import { useState, useEffect, Fragment, useRef } from 'react';
import { Empty } from 'antd';
import { DatePicker } from '@mui/x-date-pickers/DatePicker';
import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';
import dayjs from 'dayjs';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
import axios from 'axios';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { useTheme } from '@mui/material/styles';
import {
@@ -27,7 +24,6 @@ import {
TableCell,
TableBody,
TableHead,
Collapse,
Dialog,
TableRow,
DialogContent,
@@ -37,16 +33,13 @@ import {
OutlinedInput,
InputAdornment,
Skeleton,
CircularProgress,
DialogActions
TextField,
Autocomplete
} from '@mui/material';
import MainCard from 'components/MainCard';
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 { useNavigate } from 'react-router';
import PropTypes from 'prop-types';
import TableContainer from '@mui/material/TableContainer';
import TablePagination from '@mui/material/TablePagination';
import TableSortLabel from '@mui/material/TableSortLabel';
@@ -55,31 +48,6 @@ import Loader from 'components/Loader';
import { FilterList } from '@mui/icons-material';
const Orders = () => {
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]);
}
const tid = localStorage.getItem('tenantid');
const [page, setPage] = React.useState(0);
const [rowsPerPage, setRowsPerPage] = React.useState(10);
@@ -92,22 +60,16 @@ const Orders = () => {
const [percentage3, setPercentage3] = useState('0');
const [percentage4, setPercentage4] = useState('0');
let [orderarr, setArr] = useState([]);
let [orderarrcovered, setArrcovered] = useState([]);
const [allorders, setAllorders] = useState('');
const [activeorders, setActiveorders] = useState('');
const [coveredorders, setCoveredorders] = useState('');
const [uncoveredorders, setUncoveredorders] = useState('');
const [cancelled, setCancelled] = useState('');
const [closed, setClosed] = 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);
let navigate = useNavigate();
const [open, setOpen] = useState(false);
const [dateselect, setDateselect] = useState('select');
const [tabstatus1, setTabstatus1] = useState('Today');
const [datestatus, setDatestatus] = useState('Today');
const [searchword, setSearchword] = useState('');
@@ -175,52 +137,15 @@ const Orders = () => {
if (tabstatus1 === 'Tomorrow') {
setEnddate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
setStartdate(new Date(startDate.getTime() + day).toISOString().substring(0, 10));
setDateselect('select');
} else if (tabstatus1 === 'Today') {
setEnddate(new Date().toISOString().substring(0, 10));
setStartdate(new Date().toISOString().substring(0, 10));
setDateselect('select');
} else if (tabstatus1 === 'Week') {
setStartdate(new Date(startDate.getTime() - day * 7).toISOString().substring(0, 10));
setEnddate(new Date().toISOString().substring(0, 10));
setDateselect('select');
}
// else if (tabstatus1 === 'All') {
// setEnddate('');
// setStartdate('');
// setDateselect('all');
// }
}, [tabstatus1]);
const choosedate = (date) => {
setStartdate(date.$d.toISOString().substring(0, 10));
setEnddate(date.$d.toISOString().substring(0, 10));
setTabstatus1('');
};
useEffect(() => {
if (searchword) {
let arr = orderarr.filter((val) => {
return (
val.tenantname.toLowerCase().includes(searchword.toLowerCase()) ||
val.orderid.toLowerCase().includes(searchword.toLowerCase()) ||
val.pickupcustomer.toString().toLowerCase().includes(searchword.toLowerCase()) ||
val.pickupcontactno.toString().toLowerCase().includes(searchword.toLowerCase()) ||
val.pickupsuburb.toString().toLowerCase().includes(searchword.toLowerCase()) ||
val.deliverycustomer.toLowerCase().includes(searchword.toLowerCase()) ||
val.deliverycontactno.toLowerCase().includes(searchword.toLowerCase()) ||
val.deliverysuburb.toLowerCase().includes(searchword.toLowerCase()) ||
val.ordernotes.toString().toLowerCase().includes(searchword.toLowerCase())
);
});
console.log(arr);
setRows([...arr]);
} else {
setRows([...orderarr]);
}
}, [searchword]);
const fetchtablecovered = async () => {
try {
await axios
@@ -229,7 +154,7 @@ const Orders = () => {
process.env.REACT_APP_URL
}/orders/tenant/getorders/?tenantid=${tid}&status=${currentStatus}&fromdate=${startdate}&todate=${enddate}&pageno=${
page + 1
}&pagesize=${rowsPerPage}`
}&pagesize=${rowsPerPage}&keyword=${searchword}`
)
.then((res) => {
setArr(res.data.details);
@@ -244,7 +169,7 @@ const Orders = () => {
};
useEffect(() => {
fetchtablecovered();
}, [tabstatus, startdate, enddate, page, rowsPerPage]);
}, [tabstatus, startdate, enddate, page, rowsPerPage, searchword]);
const fetchpercentage = async () => {
setLoading(true);
@@ -253,12 +178,10 @@ const Orders = () => {
.get(`${process.env.REACT_APP_URL}/orders/getordersummary/?tenantid=${tid}`)
.then((res) => {
console.log(res);
setAllorders(res.data.details.total.toString());
setCoveredorders(res.data.details.delivered.toString());
setCancelled(res.data.details.cancelled.toString());
setUncoveredorders(res.data.details.pending.toString());
setCreated(res.data.details.created.toString());
setClosed(res.data.details.delivered.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());
@@ -331,11 +254,7 @@ const Orders = () => {
disablePadding: false,
label: 'Delivery'
},
// {
// id: 'ordervalue',
// disablePadding: false,
// label: 'VALUE $',
// },
{
id: 'itemcount',
disablePadding: false,
@@ -389,15 +308,6 @@ const Orders = () => {
}
function EnhancedTable() {
const [order, setOrder] = React.useState('asc');
const [orderBy, setOrderBy] = React.useState('calories');
const [selected, setSelected] = React.useState([]);
const [expandopen, setExpandopen] = React.useState('');
const [dialogopen, setDialogopen] = useState(false);
const [stafflist, setStafflist] = useState([]);
const [loading1, setLoading1] = useState(false);
const [open, setOpen] = useState(false);
const [orderheaderid, setOrderheaderid] = useState('');
@@ -411,11 +321,6 @@ const Orders = () => {
.then((res) => {
console.log(res);
if (res.data.status) {
// if (orderheaderid && tenantid) {
// fetchorderdetails();
// fetchorderaddons();
// fetchorderattires();
// }
enqueueSnackbar('Order Cancelled Successfully', {
variant: 'success',
anchorOrigin: { vertical: 'top', horizontal: 'right' },
@@ -431,21 +336,6 @@ const Orders = () => {
});
};
const handleRequestSort = (event, property) => {
const isAsc = orderBy === property && order === 'asc';
setOrder(isAsc ? 'desc' : 'asc');
setOrderBy(property);
};
const handleSelectAllClick = (event) => {
if (event.target.checked) {
const newSelected = rows.map((n) => n.name);
setSelected(newSelected);
return;
}
setSelected([]);
};
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
@@ -455,16 +345,6 @@ const Orders = () => {
setPage(0);
};
const isSelected = (name) => selected.indexOf(name) !== -1;
// Avoid a layout jump when reaching the last page with empty rows.
const emptyRows = page > 0 ? Math.max(0, (1 + page) * rowsPerPage - rows.length) : 0;
const visibleRows = React.useMemo(
() => stableSort(rows, getComparator(order, orderBy)).slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage),
[order, orderBy, page, rowsPerPage]
);
const handleClose = () => {
setOpen(false);
setOrderheaderid('');
@@ -478,15 +358,7 @@ const Orders = () => {
// const [deletepassword, setDeletepassword] = useState('');
return (
<Dialog
open={open}
onClose={() => handleClose(false)}
// keepMounted
// TransitionComponent={PopupTransition}
maxWidth="xs"
// aria-labelledby="column-delete-title"
// aria-describedby="column-delete-description"
>
<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' }}>
@@ -580,7 +452,7 @@ const Orders = () => {
</>
)}
<TableBody>
{rows.length == 0 && (
{rows?.length == 0 && (
<>
<TableCell colSpan={7}>
<Stack width={'100%'} direction={'row'} justifyContent={'center'}>
@@ -590,14 +462,13 @@ const Orders = () => {
</>
)}
{rows.map((row, index) => {
{rows?.map((row, index) => {
return (
<>
<TableRow
key={index}
sx={{
cursor: 'pointer',
backgroundColor: expandopen === row.sno ? '#f5f5f5' : ''
cursor: 'pointer'
}}
>
<TableCell padding="none">
@@ -633,26 +504,13 @@ const Orders = () => {
</Typography>
<Tooltip title={row.pickupaddress}>
<Typography variant="caption" color="textSecondary">
{/* {row.pickupaddress.slice(0, 20)} */}
{row.pickupsuburb || row.pickupaddress.slice(0, 20)}
</Typography>
</Tooltip>
</Stack>
</Stack>
{/* <Stack direction='column'>
</Stack> */}
</TableCell>
<TableCell align="left">
{/* <Stack direction='column'>
<Tooltip title={row.deliveryaddress}>
<Typography variant="caption" color="textSecondary"
>
{row.customersuburb || row.deliveryaddress.slice(0, 20)}
</Typography>
</Tooltip>
</Stack> */}
<Stack direction={'row'} spacing={1}>
<Avatar
alt=""
@@ -727,8 +585,8 @@ const Orders = () => {
<TablePagination
rowsPerPageOptions={[5, 10, 25, 50, 100]}
component="div"
count={pageCount}
rowsPerPage={rowsPerPage}
count={pageCount || 0}
rowsPerPage={rowsPerPage || 0}
page={page}
onPageChange={handleChangePage}
onRowsPerPageChange={handleChangeRowsPerPage}
@@ -740,16 +598,13 @@ const Orders = () => {
return (
<>
{loading && <Loader />}
<Grid container rowSpacing={4.5} columnSpacing={2.75}>
<Grid item xs={12} sx={{ mb: -2.25 }}>
<Stack direction={{ xs: 'column', md: 'row' }} justifyContent="space-between" alignItems="center" spacing={2}>
<Stack direction="column" alignItems="flex-start" spacing={1}>
<Typography variant="h3">Orders</Typography>
</Stack>
</Stack>
</Grid>
<Grid item xs={12} lg={3} sm={6}>
<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}
@@ -757,7 +612,7 @@ const Orders = () => {
color={theme.palette.primary.main}
/>
</Grid>
<Grid item xs={12} lg={3} sm={6}>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Pending orders"
secondary={uncoveredorders == '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : uncoveredorders}
@@ -766,7 +621,7 @@ const Orders = () => {
/>
</Grid>
<Grid item xs={12} lg={3} sm={6}>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Delivered orders"
secondary={coveredorders === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : coveredorders}
@@ -775,7 +630,7 @@ const Orders = () => {
/>
</Grid>
<Grid item xs={12} lg={3} sm={6}>
<Grid item xs={12} sm={6} md={3}>
<HoverSocialCard
primary="Cancelled Orders"
secondary={cancelled === '' ? <Skeleton sx={{ width: '30px' }} animation="wave" /> : cancelled}
@@ -783,80 +638,65 @@ const Orders = () => {
color={theme.palette.secondary[600]}
/>
</Grid>
</Grid>
<Grid item xs={12} sx={{ mb: -3 }}>
<Stack direction={'row'} justifyContent={'space-between'}>
{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>
)}
{(!startdate || !enddate) && (
<>
<Stack direction="row" spacing={2}>
<Chip label="Orders-All" color="primary" variant="light" size="small" />
</Stack>
</>
)}
<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" />
<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>
<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>
</Grid>
)}
<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>
<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}
@@ -894,97 +734,95 @@ const Orders = () => {
/>
</FormControl>
</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') {
setDateselect('all');
setStartdate('');
setEnddate('');
setOpen(false);
} else {
setDateselect('select');
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>
<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>
</>
);
};