import * as React from 'react'; import { useState, useEffect, useRef, Fragment } from 'react'; import { useNavigate } from 'react-router-dom'; import axios from 'axios'; import { Avatar, Paper, Stack, Typography, Table, TableCell, TableBody, TableHead, IconButton, TableRow, Tooltip, TableContainer, Backdrop, Collapse, Grid, Box, Skeleton, useMediaQuery, ToggleButtonGroup, ToggleButton, Dialog, DialogTitle, DialogContent, DialogActions, Button, Autocomplete, TextField } from '@mui/material'; import { useTheme } from '@mui/material/styles'; var utc = require('dayjs/plugin/utc'); import dayjs from 'dayjs'; dayjs.extend(utc); import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; import { MdMyLocation, MdCheckCircle, MdCancel, MdGroups, MdOutlineGroups, MdOutlineCheckCircle, MdOutlineCancel, MdEdit, MdKeyboardArrowDown, MdKeyboardArrowUp, MdLocationOn, MdBatteryStd, MdPowerSettingsNew, MdSpeed, MdGpsFixed, MdAccessTime, MdInventory2, MdTwoWheeler, MdArrowForward, MdDelete } from 'react-icons/md'; import LocationAutocomplete from 'components/nearle_components/LocationAutocomplete'; import PageHeader from 'components/nearle_components/PageHeader'; import StatCard from 'components/nearle_components/StatCard'; import { MobileCard, MobileCardList, MobileField, MobileFieldGrid } from 'components/nearle_components/MobileCard'; import DebounceSearchBar from 'components/nearle_components/DebounceSearchBar'; import CircularLoader from 'components/CircularLoader'; import { fetchAllRiders, getallridersummary, getriderstatus } from 'pages/api/api'; import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'; import LoaderWithImage from 'components/nearle_components/LoaderWithImage'; import { OrdersTableSkeleton } from '../orders/OrdersTableSkeleton'; import { OpenToast } from 'components/third-party/OpenToast'; import RiderSubstitution from './RiderSubstitution'; // ============================================================================ // Design tokens — shared with the deliveries / tenants / customers pages so // every surface (header, KPI tiles, table, badges, dialog) speaks the same // visual language. Brand purple `#662582` is the canonical primary; status // colours are semantic and distinct from the brand. // ============================================================================ const DT = { radiusPill: 999, radiusCard: 14, shadowSoft: '0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 24px rgba(15, 23, 42, 0.05)', shadowMd: '0 1px 3px rgba(15, 23, 42, 0.06)', shadowPop: '0 12px 32px rgba(15, 23, 42, 0.12)', textPrimary: '#0f172a', textSecondary: '#64748b', textMuted: '#94a3b8', borderSubtle: '#e2e8f0', divider: '#f1f5f9', surface: '#ffffff', surfaceAlt: '#f8fafc' }; const a = (c, suffix) => `${c}${suffix}`; const tint = (c) => a(c, '08'); const soft = (c) => a(c, '18'); const ring = (c) => a(c, '26'); const edge = (c) => a(c, '55'); const BRAND = '#662582'; const SoftPaper = (props) => ( ); const AccentAvatar = ({ color, selected, size = 24, children }) => ( {children} ); // Status palette — semantic only (do NOT swap for brand purple). Used by the // per-row status badges and the lifecycle tabs (ALL, Active). const STATUS_META = { active: { label: 'Active', color: '#10b981', icon: MdCheckCircle }, inactive: { label: 'Inactive', color: '#ef4444', icon: MdCancel }, online: { label: 'Online', color: '#10b981', icon: MdCheckCircle }, offline: { label: 'Offline', color: '#ef4444', icon: MdCancel }, idle: { label: 'Idle', color: '#f59e0b', icon: MdAccessTime }, unknown: { label: 'Unknown', color: '#94a3b8', icon: MdInventory2 } }; // Pill-tab definitions for the rider listing tabs. Keeps brand purple for the // "ALL" view and emerald for "Active" so the colour matches the count's meaning. const TAB_META = [ { key: 0, label: 'All Riders', color: BRAND, icon: MdGroups, countKey: 'total' }, { key: 1, label: 'Active', color: '#10b981', icon: MdCheckCircle, countKey: 'active' }, { key: 2, label: 'Substitutes', color: '#8b5cf6', icon: MdTwoWheeler, countKey: 'substitute' }, { key: 3, label: 'Substitution History', color: '#f59e0b', icon: MdAccessTime, countKey: 'history' } ]; const KPI_META = (summary) => [ { key: 'total', label: 'Total Riders', color: BRAND, icon: MdOutlineGroups, value: summary?.total ?? 0 }, { key: 'active', label: 'Active Riders', color: '#10b981', icon: MdOutlineCheckCircle, value: summary?.active ?? 0 }, { key: 'inactive', label: 'Inactive Riders', color: '#ef4444', icon: MdOutlineCancel, value: summary?.inactive ?? 0 } ]; const Riders = () => { const queryClient = useQueryClient(); const navigate = useNavigate(); const theme = useTheme(); const isMobile = useMediaQuery(theme.breakpoints.down('md')); const loadMoreRef = useRef(); const containerRef = useRef(); const [searchword, setSearchword] = useState(''); const [debouncedSearch, setDebouncedSearch] = useState(''); const [locaName, setLocoName] = useState('All'); const [appId, setAppId] = useState(0); const [tabvalue, setTabvalue] = useState(0); const roleid = localStorage.getItem('roleid'); const totalCols = roleid == 1 ? 11 : 10; const [logsRow, setLogsRow] = useState(null); const [riderLogsdata, setRiderLogsdata] = useState(null); const [historyDate, setHistoryDate] = useState(dayjs()); const [historyStatus, setHistoryStatus] = useState('all'); const [selectedDate, setSelectedDate] = useState(dayjs()); const [editingSub, setEditingSub] = useState(null); const [newSubRider, setNewSubRider] = useState(null); const getResolvedPartnerId = () => { let partnerId = ''; try { const rawLocs = localStorage.getItem('applocations'); if (rawLocs) { const locs = JSON.parse(rawLocs); const currentLoc = locs.find((l) => l.applocationid === appId); if (currentLoc && currentLoc.partnerid) { partnerId = currentLoc.partnerid; } else { const firstValidLoc = locs.find((l) => l.partnerid); if (firstValidLoc && firstValidLoc.partnerid) { partnerId = firstValidLoc.partnerid; } } } } catch (e) { console.error('Error parsing applocations', e); } if (!partnerId) { const savedPartnerId = localStorage.getItem('partnerid'); if (savedPartnerId && savedPartnerId !== 'undefined' && savedPartnerId !== 'null') { partnerId = savedPartnerId; } } if (!partnerId || partnerId === '0' || partnerId === 0) { partnerId = 44; } return partnerId; }; const getHistoryStatusColor = (status) => { const s = (status || '').toLowerCase(); if (s === 'cancelled' || s === 'deleted' || s === 'inactive') return '#ef4444'; // Red if (s === 'scheduled') return '#0ea5e9'; // Blue if (s === 'active' || s === 'completed') return '#10b981'; // Green return '#64748b'; // Gray }; const handleDeleteSubstitution = async (row) => { if (window.confirm(`Are you sure you want to delete the substitution for ${row.absent_rider_name}?`)) { try { const resolvedTenantId = row.tenant_id || row.tenantid || getResolvedPartnerId(); const url = `${process.env.REACT_APP_URL}/substitutions/${row.id}?tenant_id=${resolvedTenantId}`; const res = await axios.delete(url); if (res.data && res.data.status) { OpenToast('Substitution deleted successfully!', 'success', 2000); } else { OpenToast(res.data?.message || 'Failed to delete substitution.', 'error', 2000); } } catch (err) { console.error(err); OpenToast(err.response?.data?.message || err.message || 'Failed to delete substitution.', 'error', 2000); } finally { queryClient.invalidateQueries({ queryKey: ['substitutionsHistory'] }); queryClient.invalidateQueries({ queryKey: ['activeSubstitutionsToday'] }); } } }; const handleUpdateSubstitutionSubmit = async () => { if (!newSubRider) { OpenToast('Please select a substitute rider', 'error', 2000); return; } try { const resolvedTenantId = editingSub.tenant_id || editingSub.tenantid || getResolvedPartnerId(); const url = `${process.env.REACT_APP_URL}/substitutions/${editingSub.id}`; const payload = { tenant_id: parseInt(resolvedTenantId, 10), sub_rider_id: parseInt(newSubRider.userid, 10), sub_rider_name: newSubRider.username || newSubRider.fullname || `Rider #${newSubRider.userid}` }; const res = await axios.put(url, payload); if (res.data && res.data.status) { OpenToast('Substitution updated successfully!', 'success', 2000); } else { OpenToast(res.data?.message || 'Failed to update substitution.', 'error', 2000); } } catch (err) { console.error(err); OpenToast(err.response?.data?.message || err.message || 'Failed to update substitution.', 'error', 2000); } finally { setEditingSub(null); setNewSubRider(null); queryClient.invalidateQueries({ queryKey: ['substitutionsHistory'] }); queryClient.invalidateQueries({ queryKey: ['activeSubstitutionsToday'] }); } }; const [substituteAssignments, setSubstituteAssignments] = useState(() => { try { const saved = localStorage.getItem('rider_substitutions'); return saved ? JSON.parse(saved) : {}; } catch { return {}; } }); const handleAssignSubstitute = (activeRiderId, substituteRider) => { const updated = { ...substituteAssignments, [activeRiderId]: substituteRider }; setSubstituteAssignments(updated); localStorage.setItem('rider_substitutions', JSON.stringify(updated)); if (substituteRider) { OpenToast(`Assigned ${substituteRider.username || substituteRider.fullname || 'Rider'} as substitute`, 'success', 2000); } else { OpenToast(`Removed substitute assignment`, 'info', 2000); } }; const handleFinalizeSuccess = () => { setSubstituteAssignments({}); localStorage.removeItem('rider_substitutions'); queryClient.invalidateQueries({ queryKey: ['substitutionsHistory'] }); queryClient.invalidateQueries({ queryKey: ['subRidersLogs'] }); queryClient.invalidateQueries({ queryKey: ['activeSubstitutionsToday'] }); }; const { data: substituteRidersList } = useQuery({ queryKey: ['allRidersForSub', appId], queryFn: async () => { try { // Resolve partner ID dynamically let partnerId = ''; try { const rawLocs = localStorage.getItem('applocations'); if (rawLocs) { const locs = JSON.parse(rawLocs); const currentLoc = locs.find((l) => l.applocationid === appId); if (currentLoc && currentLoc.partnerid) { partnerId = currentLoc.partnerid; } else { const firstValidLoc = locs.find((l) => l.partnerid); if (firstValidLoc && firstValidLoc.partnerid) { partnerId = firstValidLoc.partnerid; } } } } catch (e) { console.error('Error parsing applocations', e); } if (!partnerId) { const savedPartnerId = localStorage.getItem('partnerid'); if (savedPartnerId && savedPartnerId !== 'undefined' && savedPartnerId !== 'null') { partnerId = savedPartnerId; } } if (!partnerId || partnerId === '0' || partnerId === 0) { partnerId = 44; // final fallback } const url = `${process.env.REACT_APP_URL}/partners/getallriders/?applocationid=0&partnerid=${partnerId}&pagesize=1000&pageno=1&status=`; const res = await axios.get(url); const allRiders = res.data.details || []; console.log('Substitute query - all riders returned from API:', allRiders.map(r => ({ userid: r.userid, username: r.username, partnerid: r.partnerid }))); const allowedIds = [1121, 772, 1116]; const filtered = allRiders.filter((rider) => allowedIds.includes(parseInt(rider.userid))); console.log('Substitute query - filtered allowed riders:', filtered); return filtered; } catch (err) { console.error(err); return []; } } }); const { data: subRidersLogsData, isLoading: subRidersLogsLoading } = useQuery({ queryKey: ['subRidersLogs', appId, debouncedSearch, selectedDate.format('YYYY-MM-DD')], queryFn: async () => { try { const dateStr = selectedDate.format('YYYY-MM-DD'); // Resolve partner ID dynamically let partnerId = ''; try { const rawLocs = localStorage.getItem('applocations'); if (rawLocs) { const locs = JSON.parse(rawLocs); const currentLoc = locs.find((l) => l.applocationid === appId); if (currentLoc && currentLoc.partnerid) { partnerId = currentLoc.partnerid; } else { const firstValidLoc = locs.find((l) => l.partnerid); if (firstValidLoc && firstValidLoc.partnerid) { partnerId = firstValidLoc.partnerid; } } } } catch (e) { console.error('Error parsing applocations', e); } if (!partnerId) { const savedPartnerId = localStorage.getItem('partnerid'); if (savedPartnerId && savedPartnerId !== 'undefined' && savedPartnerId !== 'null') { partnerId = savedPartnerId; } } if (!partnerId || partnerId === '0' || partnerId === 0) { partnerId = 44; } const url = `${process.env.REACT_APP_URL2}/partners/getriderlogs/?applocationid=${appId}&partnerid=${partnerId}&fromdate=${dateStr}&todate=${dateStr}&keyword=${debouncedSearch}`; const res = await axios.get(url); return res.data.details || []; } catch (err) { console.error(err); return []; } } }); const { data: activeSubsToday, isLoading: activeSubsTodayLoading } = useQuery({ queryKey: ['activeSubstitutionsToday', appId, selectedDate.format('YYYY-MM-DD')], queryFn: async () => { try { let partnerId = ''; try { const rawLocs = localStorage.getItem('applocations'); if (rawLocs) { const locs = JSON.parse(rawLocs); const currentLoc = locs.find((l) => l.applocationid === appId); if (currentLoc && currentLoc.partnerid) { partnerId = currentLoc.partnerid; } else { const firstValidLoc = locs.find((l) => l.partnerid); if (firstValidLoc && firstValidLoc.partnerid) { partnerId = firstValidLoc.partnerid; } } } } catch (e) { console.error('Error parsing applocations', e); } if (!partnerId) { const savedPartnerId = localStorage.getItem('partnerid'); if (savedPartnerId && savedPartnerId !== 'undefined' && savedPartnerId !== 'null') { partnerId = savedPartnerId; } } if (!partnerId || partnerId === '0' || partnerId === 0) { partnerId = 44; } const dateStr = selectedDate.format('YYYY-MM-DD'); const url = `${process.env.REACT_APP_URL}/substitutions?tenant_id=${partnerId}&from_date=${dateStr}&to_date=${dateStr}`; const res = await axios.get(url); return res.data.details || []; } catch (err) { console.error(err); return []; } } }); const { data: subHistoryData, isLoading: subHistoryLoading } = useQuery({ queryKey: ['substitutionsHistory', appId, historyDate, historyStatus], queryFn: async () => { try { let partnerId = ''; try { const rawLocs = localStorage.getItem('applocations'); if (rawLocs) { const locs = JSON.parse(rawLocs); const currentLoc = locs.find((l) => l.applocationid === appId); if (currentLoc && currentLoc.partnerid) { partnerId = currentLoc.partnerid; } else { const firstValidLoc = locs.find((l) => l.partnerid); if (firstValidLoc && firstValidLoc.partnerid) { partnerId = firstValidLoc.partnerid; } } } } catch (e) { console.error('Error parsing applocations', e); } if (!partnerId) { const savedPartnerId = localStorage.getItem('partnerid'); if (savedPartnerId && savedPartnerId !== 'undefined' && savedPartnerId !== 'null') { partnerId = savedPartnerId; } } if (!partnerId || partnerId === '0' || partnerId === 0) { partnerId = 44; } const dateStr = historyDate.format('YYYY-MM-DD'); let url = `${process.env.REACT_APP_URL}/substitutions?tenant_id=${partnerId}&from_date=${dateStr}&to_date=${dateStr}`; if (historyStatus !== 'all') { url += `&status=${historyStatus}`; } const res = await axios.get(url); return res.data.details || []; } catch (err) { console.error(err); return []; } } }); const handleChangetab = (i) => { setTabvalue(i); setLogsRow(null); }; // ==============================|| getallridersummary||============================== // const { data: allRidersSummary, isLoading: riderSummarysLoading } = useQuery({ queryKey: ['allriders', appId, tabvalue], queryFn: getallridersummary }); // ==============================|| getRiderLogs (riders)||============================== // const getRiderLogs = async (userid) => { try { const res = await axios.get(`${process.env.REACT_APP_URL}/utils/getriderperiodiclogs?userid=${userid}`); if (res.data.data.length == 0) { setLogsRow(null); OpenToast(res.data.message, 'error', 2000); } else { setRiderLogsdata(res.data.data); } } catch (err) { OpenToast(err.message, 'error', 2000); } }; // ==============================|| getriderstatus||============================== // const { data: ridersStatus, isLoading: riderStatusLoading, isError: riderstatusIsError, error: riderStatusError } = useQuery({ queryKey: ['ridersStatus'], queryFn: getriderstatus }); // ==============================|| fetchAllRiders||============================== // const { data: allRidersData, isLoading: allRidersLoading, isFetchingNextPage, fetchNextPage, hasNextPage } = useInfiniteQuery({ queryKey: ['allriders', appId, debouncedSearch, tabvalue], queryFn: fetchAllRiders, getNextPageParam: (lastPage, pages) => (lastPage.details?.length ? pages.length + 1 : undefined) }); const rows = (allRidersData?.pages.flatMap((page) => page.details || []) || []).filter(Boolean); useEffect(() => { if (!hasNextPage) return; const observer = new IntersectionObserver( (entries) => { if (entries[0].isIntersecting) { fetchNextPage(); } }, { root: document.querySelector('.MuiTableContainer-root'), rootMargin: '0px', threshold: 1.0 } ); if (loadMoreRef.current) observer.observe(loadMoreRef.current); return () => { if (loadMoreRef.current) observer.unobserve(loadMoreRef.current); }; }, [hasNextPage, fetchNextPage]); const handleScroll = (event) => { const { scrollTop, scrollHeight, clientHeight } = event.currentTarget; if (scrollTop + clientHeight >= scrollHeight - 50) { if (hasNextPage && !isFetchingNextPage) { fetchNextPage(); } } }; const errMessage = riderstatusIsError ? riderStatusError : null; useEffect(() => { if (errMessage) { OpenToast(errMessage, 'error', 2000); } }, [errMessage]); // Per-row status meta — falls back to "unknown" if the rider's state key // isn't in the palette (e.g. brand-new status string from the backend). const getRowStatusMeta = (row) => { if (tabvalue == 0) { const key = (row?.status || '').toLowerCase() === 'active' ? 'active' : 'inactive'; return STATUS_META[key] || STATUS_META.unknown; } const state = ridersStatus?.find((s) => s.userid === row?.userid); const key = (state?.status || 'unknown').toLowerCase(); return STATUS_META[key] || STATUS_META.unknown; }; return ( <> theme.zIndex.drawer + 1 }} open={allRidersLoading || riderSummarysLoading || riderStatusLoading || (tabvalue === 2 && subRidersLogsLoading) || (tabvalue === 3 && subHistoryLoading)} > {/* ============================================= || Header | ============================================= */} } placeholder="Select Zone" paperComponent={SoftPaper} sx={{ width: { xs: '100%', sm: 280 }, zIndex: 100 }} /> } /> {/* ============================================= || KPI Cards | ============================================= */} {KPI_META(allRidersSummary).map((item) => { const Icon = item.icon; return ( } color={item.color} loading={riderSummarysLoading} /> ); })} {/* ============================================= || Status Tabs + Search || ============================================= */} {TAB_META.map((t) => { const Icon = t.icon; const active = tabvalue === t.key; const count = t.key === 2 ? (subRidersLogsData?.length || 0) : t.key === 3 ? (subHistoryData?.length || 0) : (allRidersSummary?.[t.countKey] ?? 0); const countLoading = t.key === 2 ? subRidersLogsLoading : t.key === 3 ? subHistoryLoading : riderSummarysLoading; return ( handleChangetab(t.key)} sx={{ display: 'inline-flex', alignItems: 'center', gap: { xs: 0.625, md: 0.875 }, pl: 0.5, pr: { xs: 1, md: 1.25 }, py: 0.5, flexShrink: 0, cursor: 'pointer', borderRadius: '10px', border: `1px solid ${active ? t.color : DT.borderSubtle}`, bgcolor: active ? t.color : DT.surface, color: active ? '#fff' : DT.textSecondary, fontWeight: 600, boxShadow: 'none', transition: 'background-color 0.15s, border-color 0.15s, color 0.15s', '&:hover': { borderColor: active ? t.color : '#cbd5e1', bgcolor: active ? t.color : '#f8fafc' } }} > {t.label} {countLoading ? : count} ); })} {tabvalue === 3 && ( Status: val && setHistoryStatus(val)} aria-label="status selection" size="small" sx={{ '& .MuiToggleButton-root': { borderRadius: '8px', mx: 0.5, border: `1px solid ${DT.borderSubtle}`, color: DT.textSecondary, fontWeight: 600, textTransform: 'capitalize', px: 2, py: 0.5, '&.Mui-selected': { bgcolor: BRAND, color: '#fff', '&:hover': { bgcolor: '#4D1C61' } } } }} > All Scheduled newValue && setHistoryDate(newValue)} slotProps={{ textField: { size: 'small', sx: { width: 180, '& .MuiOutlinedInput-root': { borderRadius: '20px', '& fieldset': { borderColor: DT.borderSubtle }, '&:hover fieldset': { borderColor: BRAND }, '&.Mui-focused fieldset': { borderColor: BRAND } } } } }} /> )} {tabvalue === 3 ? ( {subHistoryData?.length === 0 ? ( No substitution history to show Historical substitution logs will be listed here. ) : isMobile ? ( {subHistoryData?.map((row, index) => ( {dayjs(row.sub_date).format('DD MMM YYYY')} {row.status || 'scheduled'} Absent Rider {row.absent_rider_name} #{row.absent_rider_id} Substitute {row.sub_rider_name} #{row.sub_rider_id} {row.reason && ( Reason: {row.reason} )} } /> ))} ) : ( Date Absent Rider Substitute Rider Reason Status Action {subHistoryData?.map((row, index) => ( {dayjs(row.sub_date).format('DD MMM YYYY')} {(row.absent_rider_name || '?').charAt(0).toUpperCase()} {row.absent_rider_name} #{row.absent_rider_id} {(row.sub_rider_name || '?').charAt(0).toUpperCase()} {row.sub_rider_name} #{row.sub_rider_id} {row.reason || '—'} {row.status || 'scheduled'} {(row.status || '').toLowerCase() !== 'cancelled' && ( { setEditingSub(row); setNewSubRider(null); }} > { handleDeleteSubstitution(row); }} > )} ))}
)}
) : tabvalue === 2 ? ( ) : ( {isMobile ? ( /* ===================== MOBILE: card list ===================== */ {allRidersLoading && ( Loading riders… )} {rows?.length === 0 && !allRidersLoading && ( No riders to show {searchword ? 'Try a different keyword.' : `No ${tabvalue === 0 ? '' : 'active '}riders for this zone.`} )} {rows?.length !== 0 && rows?.map((row, index) => { const statusMeta = getRowStatusMeta(row); const StatusIcon = statusMeta.icon; const expanded = logsRow === row.userid; return ( {String(index + 1).padStart(2, '0')} #{row?.userid} {statusMeta.label} {roleid == 1 && ( { navigate('/nearle/riders/edit', { state: { riderdata: row } }); }} > {tabvalue != 0 && ( { if (row.userid == logsRow) { setLogsRow(null); } else { setLogsRow(row.userid); getRiderLogs(row.userid); } }} > {expanded ? : } )} )} {(row.fullname || row.username || '?').charAt(0).toUpperCase()} {row.username || '—'} {row.contactno || '—'} } > {row.suburb || (row.address ? row.address.slice(0, 20) + '…' : '—')} {row.city || ''} {row.vehicleno || '—'} {row.starttime ? dayjs(`${dayjs().format('MM-DD-YYYY')} ${row.starttime}`).format('hh:mm A') : '—'} {row.endtime ? dayjs(`${dayjs().format('MM-DD-YYYY')} ${row.endtime}`).format('hh:mm A') : '—'} {expanded && tabvalue !== 0 && ( Live telemetry — {row.username || `Rider #${row.userid}`} )} ); })} {rows?.length !== 0 && (
{isFetchingNextPage || hasNextPage ? ( ) : ( No more riders )}
)}
) : ( # ID Rider Address Vehicle Shift Time Fare Fuel Status {roleid == 1 && Action} {allRidersLoading && } {rows?.length === 0 && !allRidersLoading && ( No riders to show {searchword ? 'Try a different keyword.' : `No ${tabvalue === 0 ? '' : 'active '}riders for this zone.`} )} {rows?.length !== 0 && rows?.map((row, index) => { const statusMeta = getRowStatusMeta(row); const StatusIcon = statusMeta.icon; const expanded = logsRow === row.userid; return ( {String(index + 1).padStart(2, '0')} #{row?.userid} {(row.fullname || row.username || '?').charAt(0).toUpperCase()} {row.username || '—'} {row.contactno || '—'} {row.suburb || (row.address ? row.address.slice(0, 20) + '…' : '—')} {row.city || ''} {row.vehicleno || '—'} #{row.shiftid ?? '—'} {row.starttime ? dayjs(`${dayjs().format('MM-DD-YYYY')} ${row.starttime}`).format('hh:mm A') : '—'} {row.endtime ? dayjs(`${dayjs().format('MM-DD-YYYY')} ${row.endtime}`).format('hh:mm A') : '—'} {row.basefare ?? '—'} {row.fuelcharge ?? '—'} {statusMeta.label} {roleid == 1 && ( { navigate('/nearle/riders/edit', { state: { riderdata: row } }); }} > {tabvalue != 0 && ( { if (row.userid == logsRow) { setLogsRow(null); } else { setLogsRow(row.userid); getRiderLogs(row.userid); } }} > {expanded ? : } )} )} {/* ============ Collapsible row — live rider logs ============ */} {expanded && tabvalue !== 0 && ( Live telemetry — {row.username || `Rider #${row.userid}`} )} ); })} {rows?.length !== 0 && (
{isFetchingNextPage || hasNextPage ? ( ) : ( No more riders )}
)}
)}
)} setEditingSub(null)} maxWidth="xs" fullWidth PaperProps={{ sx: { borderRadius: `${DT.radiusCard / 8}px`, p: 1 } }} > Update Substitution Choose a new substitute rider for {editingSub?.absent_rider_name}. option?.userid === value?.userid} getOptionLabel={(option) => `${option.username || option.fullname || ''} (#${option.userid})`} value={newSubRider} onChange={(event, newValue) => setNewSubRider(newValue)} renderInput={(params) => ( )} /> ); }; // Inline stat chip used in the rider-logs collapse row. Mirrors the StatChip // pattern from the pricing page so the telemetry block reads at a glance. const LogChip = ({ color, icon: Icon, label, value }) => ( {label} {value} ); export default Riders;