updated the fix on the slots and some ui fixes
This commit is contained in:
@@ -3,7 +3,7 @@ import { MapContainer, TileLayer, Marker, Popup, Polyline, useMap, ZoomControl }
|
||||
import L from 'leaflet';
|
||||
import 'leaflet/dist/leaflet.css';
|
||||
import dayjs from 'dayjs';
|
||||
import { useInfiniteQuery } from '@tanstack/react-query';
|
||||
import { useInfiniteQuery, useQuery } from '@tanstack/react-query';
|
||||
import {
|
||||
MdMap,
|
||||
MdDirectionsBike,
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
MdNotes,
|
||||
MdSwapHoriz
|
||||
} from 'react-icons/md';
|
||||
import { fetchDeliveries } from '../../api/api';
|
||||
import { fetchDeliveries, fetchAppLocations } from '../../api/api';
|
||||
import './Dispatch.css';
|
||||
import { RAW_DISPATCH_DATA } from './DispatchData';
|
||||
|
||||
@@ -50,7 +50,11 @@ const toNum = (v) => {
|
||||
};
|
||||
|
||||
const hasValidDrop = (o) => Number.isFinite(toNum(o.droplat || o.deliverylat)) && Number.isFinite(toNum(o.droplon || o.deliverylong));
|
||||
const hasValidPickup = (o) => Number.isFinite(toNum(o.pickuplat)) && Number.isFinite(toNum(o.pickuplong));
|
||||
// Try multiple field-name variants — the live delivery API may return pickuplatitude/picklongitude
|
||||
// or pickuplongitude instead of the shorter pickuplat/pickuplong used in the static data.
|
||||
const pickupLat = (o) => o.pickuplat || o.pickuplatitude || o.pickup_lat;
|
||||
const pickupLon = (o) => o.pickuplong || o.pickuplongitude || o.picklongitude || o.pickup_lon;
|
||||
const hasValidPickup = (o) => Number.isFinite(toNum(pickupLat(o))) && Number.isFinite(toNum(pickupLon(o)));
|
||||
|
||||
// Batch buckets by expected delivery time-of-day (operator's mental model — morning rush,
|
||||
// lunch wave, dinner wave). Anything outside a window OR with no parsable time falls under "all".
|
||||
@@ -73,13 +77,27 @@ const BATCHES = Array.from({ length: BATCH_END_HOUR - BATCH_START_HOUR }, (_, i)
|
||||
});
|
||||
|
||||
const getRowBatch = (r) => {
|
||||
const t = r.expecteddeliverytime || r.deliverydate || r.pickupslot;
|
||||
if (!t) return null;
|
||||
const d = dayjs(t);
|
||||
if (!d.isValid()) return null;
|
||||
const h = d.hour();
|
||||
if (h < BATCH_START_HOUR || h >= BATCH_END_HOUR) return null;
|
||||
return `slot-${h}`;
|
||||
// Try fields in priority order. Bare date strings like "YYYY-MM-DD" have no time
|
||||
// component and parse to midnight (hour 0) which is below BATCH_START_HOUR — skip
|
||||
// them early so we fall through to a field that actually has a time of day.
|
||||
const candidates = [
|
||||
r.expecteddeliverytime,
|
||||
r.assigntime,
|
||||
r.deliverydate,
|
||||
r.pickupslot
|
||||
];
|
||||
for (const t of candidates) {
|
||||
if (!t) continue;
|
||||
const str = String(t).trim();
|
||||
// Skip bare date strings — no time component, would always parse to midnight
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(str)) continue;
|
||||
const d = dayjs(t);
|
||||
if (!d.isValid()) continue;
|
||||
const h = d.hour();
|
||||
if (h < BATCH_START_HOUR || h >= BATCH_END_HOUR) continue;
|
||||
return `slot-${h}`;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const FINAL_STATUSES = new Set(['delivered']);
|
||||
@@ -114,8 +132,8 @@ const computeRiderPosition = (r) => {
|
||||
prevLat = toNum(prev.droplat || prev.deliverylat);
|
||||
prevLon = toNum(prev.droplon || prev.deliverylong);
|
||||
} else if (hasValidPickup(next)) {
|
||||
prevLat = toNum(next.pickuplat);
|
||||
prevLon = toNum(next.pickuplong);
|
||||
prevLat = toNum(pickupLat(next));
|
||||
prevLon = toNum(pickupLon(next));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -179,7 +197,7 @@ const buildTripPoints = (sorted) => {
|
||||
if (!valid.length) return [];
|
||||
const pickupSrc = sorted.find(hasValidPickup);
|
||||
const pts = [];
|
||||
if (pickupSrc) pts.push([toNum(pickupSrc.pickuplat), toNum(pickupSrc.pickuplong)]);
|
||||
if (pickupSrc) pts.push([toNum(pickupLat(pickupSrc)), toNum(pickupLon(pickupSrc))]);
|
||||
valid.forEach((o) => pts.push([toNum(o.droplat || o.deliverylat), toNum(o.droplon || o.deliverylong)]));
|
||||
return pts;
|
||||
};
|
||||
@@ -194,7 +212,7 @@ L.Icon.Default.mergeOptions({
|
||||
|
||||
const RIDER_COLORS = ['#0055FF', '#00D82C', '#FF6B00', '#9D00FF', '#FF00A8', '#00C2B2', '#FF9900', '#FF0000'];
|
||||
|
||||
const MapController = ({ focusedItem, viewMode, orders }) => {
|
||||
const MapController = ({ focusedItem, viewMode, orders, kitchens }) => {
|
||||
const map = useMap();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -202,10 +220,19 @@ const MapController = ({ focusedItem, viewMode, orders }) => {
|
||||
if (focusedItem) {
|
||||
if (focusedItem.orders) {
|
||||
pts = focusedItem.orders.map(o => [parseFloat(o.droplat || o.deliverylat), parseFloat(o.droplon || o.deliverylong)]);
|
||||
focusedItem.orders.forEach(o => pts.push([parseFloat(o.pickuplat), parseFloat(o.pickuplong)]));
|
||||
focusedItem.orders.forEach(o => pts.push([toNum(pickupLat(o)), toNum(pickupLon(o))]));
|
||||
} else {
|
||||
pts = [[focusedItem.lat, focusedItem.lon]];
|
||||
}
|
||||
} else if (viewMode === 'kitchens') {
|
||||
// Fit to all kitchen pickup positions so the user sees them when switching to By Location
|
||||
pts = (kitchens || [])
|
||||
.filter(k => Number.isFinite(k.lat) && Number.isFinite(k.lon))
|
||||
.map(k => [k.lat, k.lon]);
|
||||
// Fall back to delivery drops if no valid kitchen coords are available
|
||||
if (pts.length === 0) {
|
||||
pts = orders.map(o => [parseFloat(o.droplat || o.deliverylat), parseFloat(o.droplon || o.deliverylong)]);
|
||||
}
|
||||
} else if (viewMode === 'all') {
|
||||
pts = orders.map(o => [parseFloat(o.droplat || o.deliverylat), parseFloat(o.droplon || o.deliverylong)]);
|
||||
}
|
||||
@@ -221,7 +248,7 @@ const MapController = ({ focusedItem, viewMode, orders }) => {
|
||||
} else {
|
||||
map.setView([11.022, 76.982], 12, { animate: true });
|
||||
}
|
||||
}, [focusedItem, viewMode, orders, map]);
|
||||
}, [focusedItem, viewMode, orders, kitchens, map]);
|
||||
|
||||
return null;
|
||||
};
|
||||
@@ -263,7 +290,26 @@ const Dispatch = ({
|
||||
const orderMarkerRefs = useRef({});
|
||||
const isControlled = selectedRiderId !== undefined;
|
||||
const [clock, setClock] = useState('');
|
||||
|
||||
// Fetch the logged-in user's hub/location name from the API.
|
||||
// applocationid in localStorage is the hub the user selected at login.
|
||||
const liveAppLocationId = typeof window !== 'undefined' ? localStorage.getItem('applocationid') : null;
|
||||
const { data: appLocations } = useQuery({
|
||||
queryKey: ['appLocations'],
|
||||
queryFn: fetchAppLocations,
|
||||
staleTime: 5 * 60 * 1000
|
||||
});
|
||||
const locationName = useMemo(() => {
|
||||
if (!appLocations || !liveAppLocationId) return null;
|
||||
const match = appLocations.find((l) => String(l.applocationid) === String(liveAppLocationId));
|
||||
return match?.locationname || null;
|
||||
}, [appLocations, liveAppLocationId]);
|
||||
|
||||
const [osrmRoutes, setOsrmRoutes] = useState({});
|
||||
// Mirror of osrmRoutes held in a ref so fetchRoute can check the cache without
|
||||
// being listed in useCallback deps (which caused a render-loop: fetch → state
|
||||
// update → new fetchRoute → effect re-runs → repeat).
|
||||
const osrmRoutesRef = useRef({});
|
||||
const [isAnimating, setIsAnimating] = useState(false);
|
||||
const [animatedSegments, setAnimatedSegments] = useState([]);
|
||||
const [selectedDate, setSelectedDate] = useState(dayjs().format('YYYY-MM-DD'));
|
||||
@@ -458,15 +504,15 @@ const Dispatch = ({
|
||||
kitchenMap[key] = {
|
||||
id: key,
|
||||
kitchenName: name,
|
||||
lat: toNum(o.pickuplat),
|
||||
lon: toNum(o.pickuplong),
|
||||
lat: toNum(pickupLat(o)),
|
||||
lon: toNum(pickupLon(o)),
|
||||
orders: [],
|
||||
riders: new Set()
|
||||
};
|
||||
} else if (!Number.isFinite(kitchenMap[key].lat) && hasValidPickup(o)) {
|
||||
// Upgrade to first valid pickup coords we see for this kitchen
|
||||
kitchenMap[key].lat = toNum(o.pickuplat);
|
||||
kitchenMap[key].lon = toNum(o.pickuplong);
|
||||
kitchenMap[key].lat = toNum(pickupLat(o));
|
||||
kitchenMap[key].lon = toNum(pickupLon(o));
|
||||
}
|
||||
kitchenMap[key].orders.push(o);
|
||||
if (o.rider_id) kitchenMap[key].riders.add(o.rider_id);
|
||||
@@ -550,11 +596,15 @@ const Dispatch = ({
|
||||
|
||||
const fetchRoute = useCallback(async (riderId, tripKey, points) => {
|
||||
const cacheKey = `${riderId}-${tripKey}`;
|
||||
// Already cached (array) or known-failed (false). `null` means in-flight.
|
||||
if (osrmRoutes[cacheKey] !== undefined) return;
|
||||
// Use the ref (not state) for the in-flight / already-cached check so this
|
||||
// callback doesn't need osrmRoutes in its deps — that old pattern caused a
|
||||
// render loop: each resolved route updated state → recreated fetchRoute →
|
||||
// re-ran all route-fetching effects for every rider.
|
||||
if (osrmRoutesRef.current[cacheKey] !== undefined) return;
|
||||
if (points.length < 2) return;
|
||||
|
||||
// Mark as in-flight so simultaneous renders don't fire duplicate requests.
|
||||
// Mark in-flight in both ref (immediate) and state (triggers re-render).
|
||||
osrmRoutesRef.current[cacheKey] = null;
|
||||
setOsrmRoutes(prev => ({ ...prev, [cacheKey]: null }));
|
||||
|
||||
const coords = points.map(p => `${p[1]},${p[0]}`).join(';');
|
||||
@@ -562,20 +612,32 @@ const Dispatch = ({
|
||||
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const data = await res.json();
|
||||
if (data.routes && data.routes[0]) {
|
||||
const poly = data.routes[0].geometry.coordinates.map(c => [c[1], c[0]]);
|
||||
const json = await res.json();
|
||||
if (json.routes && json.routes[0]) {
|
||||
const poly = json.routes[0].geometry.coordinates.map(c => [c[1], c[0]]);
|
||||
osrmRoutesRef.current[cacheKey] = poly;
|
||||
setOsrmRoutes(prev => ({ ...prev, [cacheKey]: poly }));
|
||||
} else {
|
||||
// OSRM responded but couldn't route — record as failed so renderRoutes
|
||||
// shows the aerial fallback instead of an empty gap.
|
||||
osrmRoutesRef.current[cacheKey] = false;
|
||||
setOsrmRoutes(prev => ({ ...prev, [cacheKey]: false }));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('OSRM Fetch error:', e);
|
||||
osrmRoutesRef.current[cacheKey] = false;
|
||||
setOsrmRoutes(prev => ({ ...prev, [cacheKey]: false }));
|
||||
}
|
||||
}, [osrmRoutes]);
|
||||
}, []); // stable — cache reads go through osrmRoutesRef, not state
|
||||
|
||||
// Clear the OSRM route cache whenever the date or batch changes. Without this,
|
||||
// routes fetched for the previous day/slot linger and are shown against the new
|
||||
// data — especially visible when the same rider ID appears across different batches
|
||||
// and the cached polyline from the earlier slot is drawn over the new orders.
|
||||
useEffect(() => {
|
||||
osrmRoutesRef.current = {};
|
||||
setOsrmRoutes({});
|
||||
}, [selectedDate, selectedBatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (embedded) return undefined;
|
||||
@@ -761,7 +823,7 @@ const Dispatch = ({
|
||||
<div className="rcard-emo" style={{ background: `${r.color}18`, borderColor: `${r.color}50`, color: r.color }}><MdTwoWheeler /></div>
|
||||
<div className="rcard-info">
|
||||
<div className="rcard-name">{r.riderName}</div>
|
||||
<div className="rcard-zone">{r.orders[0]?.zone_name || 'Coimbatore'} · {new Set(r.orders.map(o => o.trip_number || 1)).size} trips</div>
|
||||
<div className="rcard-zone">{r.orders[0]?.zone_name || locationName || 'Local'} · {new Set(r.orders.map(o => o.trip_number || 1)).size} trips</div>
|
||||
</div>
|
||||
<div className="rcard-badge" style={{ background: `${r.color}18`, color: r.color }}>{r.orders.length}</div>
|
||||
</div>
|
||||
@@ -924,7 +986,7 @@ const Dispatch = ({
|
||||
<div className="logo">
|
||||
<div className="logo-badge">D</div>
|
||||
<div className="logo-name">Dispatch</div>
|
||||
<div className="logo-city"><MdPlace /> Coimbatore</div>
|
||||
{locationName && <div className="logo-city"><MdPlace /> {locationName}</div>}
|
||||
</div>
|
||||
|
||||
{/* Header right-cluster: profit/loss chip, total-orders pill, date picker.
|
||||
@@ -1505,7 +1567,27 @@ const Dispatch = ({
|
||||
'Rider dispatch'
|
||||
}</div>
|
||||
<div id="rider-cards">
|
||||
{viewMode === 'zones' ? (
|
||||
{allOrders.length === 0 && !liveIsFetching ? (
|
||||
(() => {
|
||||
const slotLabel = BATCHES.find(b => b.id === selectedBatch)?.label;
|
||||
const hasDayData = shouldFetchLive && liveRows.length > 0;
|
||||
return (
|
||||
<div className="empty-slot">
|
||||
<div className="empty-slot-icon">
|
||||
<MdInventory2 />
|
||||
</div>
|
||||
<div className="empty-slot-title">
|
||||
{slotLabel ? `No orders in ${slotLabel}` : 'No orders'}
|
||||
</div>
|
||||
<div className="empty-slot-sub">
|
||||
{hasDayData
|
||||
? `${liveRows.length} order${liveRows.length === 1 ? '' : 's'} exist in other slots today`
|
||||
: 'No deliveries found for this date'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()
|
||||
) : viewMode === 'zones' ? (
|
||||
zoneCards.map((z, i) => {
|
||||
const delivered = z.statusCounts.delivered || 0;
|
||||
const profitNeg = z.totalProfit < 0;
|
||||
@@ -1613,16 +1695,13 @@ const Dispatch = ({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div id="desc">
|
||||
{(focusedRider || focusedKitchen) ? 'Detailed breakdown' : focusedZone ? `${focusedZone.activeRidersCount} riders in ${focusedZone.name} — click one to drill in` : '💡 Click a card to view detailed route breakdown'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="map-wrap" className={viewMode === 'kitchens' ? 'view-mode-kitchens' : ''}>
|
||||
<MapContainer center={[11.022, 76.982]} zoom={12} scrollWheelZoom style={{ height: '100%', width: '100%' }} zoomControl={false}>
|
||||
<TileLayer url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" attribution='© OpenStreetMap contributors' />
|
||||
<ZoomControl position="bottomright" />
|
||||
<MapController focusedItem={((focusedRider || focusedKitchen) && focusedStop) || focusedRider || focusedKitchen || focusedZone} viewMode={viewMode} orders={allOrders} />
|
||||
<MapController focusedItem={((focusedRider || focusedKitchen) && focusedStop) || focusedRider || focusedKitchen || focusedZone} viewMode={viewMode} orders={allOrders} kitchens={kitchens} />
|
||||
{kitchens
|
||||
.filter(k => Number.isFinite(k.lat) && Number.isFinite(k.lon))
|
||||
.filter(k => !focusedRider || k.riders.has(focusedRider.id))
|
||||
|
||||
Reference in New Issue
Block a user