import {
Autocomplete,
Button,
Chip,
Divider,
Grid,
Stack,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Tooltip,
Typography,
Backdrop,
IconButton
} from '@mui/material';
import React, { Fragment, useEffect, useMemo, useState } from 'react';
import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';
import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard';
import { useLocation, useNavigate } from 'react-router-dom';
import dayjs from 'dayjs';
import MainCard from 'components/MainCard';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { fetchPaymentType, fetchRidersList, finalCreatedeliveries, notifyRider } from '../api/api';
import { OpenToast } from 'components/nearle_components/OpenToast';
import { useMutation, useQuery } from '@tanstack/react-query';
import Loader from 'components/Loader';
import CircularLoader from 'components/nearle_components/CircularLoader';
import { Empty } from 'antd';
import HoverSocialCard from 'components/cards/statistics/HoverSocialCard';
import { DashboardFilled } from '@ant-design/icons';
import { MdDirectionsBike } from 'react-icons/md';
import { FaMapLocationDot } from 'react-icons/fa6';
import { HiOutlineArrowLeft } from 'react-icons/hi';
var utc = require('dayjs/plugin/utc');
dayjs.extend(utc);
// Mobile-only rendering of the optimised-orders preview. Mirrors the exact same
// fields, chips and tooltips as the desktop table rows — no behaviour added,
// purely a card layout for phones. Renders for both aiMode 1 and normal mode;
// the Zone / Rider fields are gated on aiMode just like the table columns.
const MobileOrdersList = ({ list, aiMode }) => {
if (!list || list.length === 0) {
return (
);
}
return (
{list.map((val, index) => {
const typeColor =
val.ordertype == 'Economy' ? 'success' : val.ordertype == 'Risky' ? 'error' : 'primary';
return (
#{index + 1}
{aiMode == 1 && }
}
>
{val.tenantname}
{val.tenantsuburb}
{val.applocation}
{`${val.locationname}-(${val.locationsuburb})`}
{val.orderid}
{dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
{dayjs(val.orderdate).utc().format('hh:mm A')}
-
{dayjs(val.deliverydate).utc().format('DD/MM/YYYY')}
{dayjs(val.deliverydate).utc().format('hh:mm A')}
{val.pickupcustomer}
{val.pickupcontactno}
{val.pickupsuburb || val.pickupaddress.slice(0, 20)}
{val.deliverycustomer}
{val.deliverycontactno}
{val.deliverysuburb || val.deliveryaddress.slice(0, 20)}
{val.ordernotes ? : null}
{aiMode == 1 && (
{val.username}
ID : {val.userid}
)}
);
})}
);
};
const OrdersPreview = () => {
const theme = useTheme();
const isMobile = useMediaQuery(theme.breakpoints.down('md'));
const navigate = useNavigate();
const location = useLocation();
console.log('location.state', location.state);
const [rider, setRider] = useState(null);
const [payment, setPayment] = useState(null);
const [finaldeliveryList, setFinalDeliveryList] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const deliverylist = location.state?.deliverylist;
const zoneData = location.state?.zoneData;
const metaData = location.state?.metaData;
const riderToken = location.state?.riderToken;
const appId = location.state?.appId;
const aiMode = location.state?.aiMode;
const reassignOrders = location.state?.reassignOrders;
useEffect(() => {
console.log('aiMode', aiMode);
console.log('riderToken', riderToken);
console.log('zoneData', zoneData);
console.log('metaData', metaData);
console.log('reassignOrders', reassignOrders);
}, []);
useEffect(() => {
if (!deliverylist?.length) return;
const updateDeliveryAmtList = deliverylist.map((list) => {
const cumulativeKms = Number(list.cumulativekms || 0);
const minKm = Number(list.minkm || 0);
const basePrice = Number(list.baseprice || 0);
const pricePerKm = Number(list.priceperkm || 0);
if (cumulativeKms <= minKm) {
return {
...list,
deliveryamt: basePrice
};
}
return {
...list,
deliveryamt: (cumulativeKms - minKm) * pricePerKm + basePrice
};
});
setFinalDeliveryList(updateDeliveryAmtList);
console.log('finaldeliveryList', updateDeliveryAmtList);
}, [deliverylist]);
// ==============================|| fetchPaymentType ||============================== //
const {
data: paymentModes = [],
isLoading: paymentModesLoading
} = useQuery({
queryKey: ['paymentmodes'],
queryFn: fetchPaymentType
});
// ==============================|| fetchRidersList ||============================== //
const {
data: ridersList = [],
isLoading: ridersListLoading
} = useQuery({
queryKey: ['ridersList', appId], // Unique key for caching & re-fetching
queryFn: fetchRidersList,
enabled: appId !== 0 // Ensures query runs only when appId is valid
});
const getRiderName = async (userid) => {
await ridersList.map((rider) => {
if (rider.userid == userid) {
return rider.firstname;
}
});
};
// ======================================================= || notifyRiderMutation || =======================================================
const notifyRiderMutation = useMutation({
mutationFn: notifyRider, // Using the separate function
onSuccess: () => {
OpenToast('Notification sent Successfully', 'success', 2000);
},
onError: (error) => {
OpenToast(error.message, 'error', 2000);
}
});
const createNormalDeliveryMutation = useMutation({
mutationFn: finalCreatedeliveries, // for optimised delivery create
onSuccess: (data, variables) => {
console.log('data', data);
console.log('varialbles', variables);
notifyRiderMutation.mutate(rider?.userfcmtoken || riderToken); // Call notifyRider after success
if (data.status == 'accepted') {
OpenToast('Delivery Created Successfully', 'success', 2000);
}
setTimeout(() => {
setIsLoading(false);
navigate('/nearle/orders');
}, 2000);
},
onError: (error) => {
OpenToast(error.message, 'error', 4000);
}
});
const handleManualCreateDelivery = async () => {
setIsLoading(true);
createNormalDeliveryMutation.mutate({
deliveries: finaldeliveryList
});
};
return (
navigate('/nearle/orders')}
sx={{
backgroundColor: 'action.hover',
color: 'text.primary',
'&:hover': {
backgroundColor: 'action.selected'
}
}}
>
{' '}
Assign Orders
}
secondary={
}>
Re-Assign
}
>
{(paymentModesLoading || ridersListLoading || isLoading) && (
<>
>
)}
{
theme.zIndex.drawer + 1
}}
open={paymentModesLoading || ridersListLoading || isLoading} // when loader = true, backdrop covers the page
>
}
{aiMode == 1 && (
}
color={theme.palette.success.main}
sx={{ cursor: 'pointer' }}
/>
}
color={theme.palette.warning.main}
/>
}
color={theme.palette.info.main}
/>
}
color={theme.palette.error.main}
/>
)}
{isMobile ? (
) : (
#
{aiMode == 1 && (
Zone
)}
Tenant
order Location
Pickup
Delivery
Notes
{aiMode == 1 && (
Rider
)}
Type
Profit
Charges
KMS
{finaldeliveryList?.length == 0 && (
)}
{finaldeliveryList && aiMode == 1 // ai mode , ai automation
? finaldeliveryList?.map((val, index) => {
return (
{index + 1}
{aiMode == 1 && (
)}
{val.tenantname}
{val.tenantsuburb}
{val.applocation}
{`${val.locationname}-(${val.locationsuburb})`}
{val.orderid}
{dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
{dayjs(val.orderdate).utc().format('hh:mm A')}
-
{dayjs(val.deliverydate).utc().format('DD/MM/YYYY')}
{dayjs(val.deliverydate).utc().format('hh:mm A')}
{val.pickupcustomer}
{val.pickupcontactno}
{val.pickupsuburb || val.pickupaddress.slice(0, 20)}
{val.deliverycustomer}
{val.deliverycontactno}
{val.deliverysuburb || val.deliveryaddress.slice(0, 20)}
{val.ordernotes}
{aiMode == 1 && (
{val.username}
ID : {val.userid}
)}
);
})
: // normal optimisation
finaldeliveryList?.map((val, index) => {
return (
{index + 1}
{val.tenantname}
{val.tenantsuburb}
{val.applocation}
{`${val.locationname}-(${val.locationsuburb})`}
{val.orderid}
{dayjs(val.orderdate).utc().format('DD/MM/YYYY')}
{dayjs(val.orderdate).utc().format('hh:mm A')}
-
{dayjs(val.deliverydate).utc().format('DD/MM/YYYY')}
{dayjs(val.deliverydate).utc().format('hh:mm A')}
{val.pickupcustomer}
{val.pickupcontactno}
{val.pickupsuburb || val.pickupaddress.slice(0, 20)}
{val.deliverycustomer}
{val.deliverycontactno}
{val.deliverysuburb || val.deliveryaddress.slice(0, 20)}
{val.ordernotes}
);
})}
)}
{aiMode == 0 && (
}
onChange={(event, newValue, reason) => {
if (reason === 'clear') {
setPayment(null);
return;
}
if (newValue) {
console.log('Selected:', newValue);
setPayment(newValue);
const newList = finaldeliveryList?.map((list) => ({
...list,
paymenttype: newValue.apptypeid // merge selected rider into each list item
}));
setFinalDeliveryList(newList);
}
}}
/>
}
onChange={(event, newValue, reason) => {
if (reason === 'clear') {
setRider(null);
return;
}
if (newValue) {
setRider(newValue);
console.log('Selected:', newValue);
const newList = finaldeliveryList?.map((list) => ({
...list,
userid: newValue.userid,
userfcmtoken: newValue.userfcmtoken
}));
setFinalDeliveryList(newList);
}
}}
/>
)}
}
onClick={() => {
navigate('/nearle/orders');
}}
>
Back
);
};
export default OrdersPreview;