import { View, Text, ScrollView, RefreshControl, ActivityIndicator, TouchableOpacity, Linking, Alert } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useQueries } from '@tanstack/react-query'; import { router } from 'expo-router'; import { api } from '../../services/api'; import { useAuthStore } from '../../stores/authStore'; const PRIORITY_COLOR: Record = { HIGH: '#DC2626', NORMAL: '#0891B2' }; const PRIORITY_BG: Record = { HIGH: '#FEE2E2', NORMAL: '#ECFEFF' }; const TYPE_COLOR: Record = { INSTALLATION: '#0891B2', SUPPORT: '#7C3AED', BILLING: '#D97706' }; function KpiCard({ label, value, color, bg }: { label: string; value: string | number; color: string; bg: string }) { return ( {label} {value} ); } function TicketRow({ task, onPress }: { task: any; onPress: () => void }) { const typeColor = TYPE_COLOR[task.type] ?? '#6B7280'; return ( {task.type} {task.priority === 'HIGH' && ( HIGH )} {task.status?.replace('_', ' ')} {task.subject} {task.client?.firstName} {task.client?.lastName} {task.assignedTo ? ` ยท ${task.assignedTo.firstName}` : ' ยท Unassigned'} ); } function InvoiceRow({ inv }: { inv: any }) { const dueDate = inv.dueDate ? new Date(inv.dueDate) : null; const today = new Date(); const isOverdue = dueDate && dueDate < today; const daysLeft = dueDate ? Math.ceil((dueDate.getTime() - today.getTime()) / 86400000) : null; const navigate = () => { const lat = inv.client?.lat; const lng = inv.client?.lng; if (!lat || !lng) { Alert.alert('No Location', 'This client does not have a recorded location yet.'); return; } Alert.alert('Navigate', `Open navigation to ${inv.client?.firstName} ${inv.client?.lastName}?`, [ { text: 'Google Maps', onPress: () => Linking.openURL(`https://www.google.com/maps/dir/?api=1&destination=${lat},${lng}`) }, { text: 'Waze', onPress: () => Linking.openURL(`waze://?ll=${lat},${lng}&navigate=yes`) }, { text: 'Cancel', style: 'cancel' }, ]); }; return ( {inv.client?.firstName} {inv.client?.lastName} {inv.invoiceNumber} {isOverdue ? `Overdue by ${Math.abs(daysLeft ?? 0)} day${Math.abs(daysLeft ?? 0) !== 1 ? 's' : ''}` : daysLeft !== null ? `Due in ${daysLeft} day${daysLeft !== 1 ? 's' : ''}` : 'No due date'} โ‚ฑ{Number(inv.balance).toLocaleString()} ๐Ÿ“ Navigate ); } export default function DashboardScreen() { const { user } = useAuthStore(); const role = user?.roles?.[0] ?? user?.role ?? ''; const isAdminOrStaff = role === 'ADMIN' || role === 'STAFF'; const hour = new Date().getHours(); const greeting = hour < 12 ? 'Good morning' : hour < 18 ? 'Good afternoon' : 'Good evening'; const [summaryQ, ticketsQ, invoicesQ] = useQueries({ queries: [ { queryKey: ['dashboard'], queryFn: () => api.get('/api/v1/dashboard/summary').then(r => r.data), }, { queryKey: ['dashboard-tickets'], queryFn: async () => { const res = await api.get('/api/v1/tickets?limit=50'); const all: any[] = res.data?.data ?? res.data ?? []; return all.filter((t: any) => t.status === 'OPEN' || t.status === 'IN_PROGRESS'); }, }, { queryKey: ['dashboard-invoices'], queryFn: async () => { const res = await api.get('/api/v1/invoices?limit=50'); const all: any[] = res.data?.data ?? res.data ?? []; const unpaid = all.filter((inv: any) => ['SENT', 'PARTIAL', 'OVERDUE'].includes(inv.status) && Number(inv.balance) > 0); unpaid.sort((a: any, b: any) => { const da = a.dueDate ? new Date(a.dueDate).getTime() : Infinity; const db = b.dueDate ? new Date(b.dueDate).getTime() : Infinity; return da - db; }); return unpaid.slice(0, 10); }, }, ], }); const isLoading = summaryQ.isLoading || ticketsQ.isLoading || invoicesQ.isLoading; const isRefetching = summaryQ.isRefetching || ticketsQ.isRefetching || invoicesQ.isRefetching; const summary = summaryQ.data ?? {}; const allActiveTickets: any[] = ticketsQ.data ?? []; const unpaidInvoices: any[] = invoicesQ.data ?? []; const unassigned = allActiveTickets.filter((t: any) => !t.assignedToId).slice(0, 10); const assignedToMe = allActiveTickets.filter((t: any) => t.assignedToId === user?.id).slice(0, 10); const byPrio = (a: any, b: any) => (a.priority === 'HIGH' ? -1 : 1) - (b.priority === 'HIGH' ? -1 : 1); const refetchAll = () => { summaryQ.refetch(); ticketsQ.refetch(); invoicesQ.refetch(); }; return ( } > {/* Header */} {greeting}, {user?.firstName ?? 'Field Staff'} {isLoading ? ( ) : ( {/* KPI Row 1 */} {/* KPI Row 2 */} {/* Revenue โ€” ADMIN/STAFF only */} {isAdminOrStaff && summary?.revenue?.thisMonth != null && ( This Month's Revenue โ‚ฑ{Number(summary.revenue.thisMonth).toLocaleString()} {summary.revenue.growth !== undefined && ( +{summary.revenue.growth}% )} )} {/* โ”€โ”€ Unassigned Tickets โ”€โ”€ */} Unassigned Tickets {unassigned.length > 0 && ( {unassigned.length} )} router.push('/(app)/tasks')} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}> View all {unassigned.length === 0 ? ( No unassigned tickets ๐ŸŽ‰ ) : ( {[...unassigned].sort(byPrio).map((t: any) => ( router.push(`/(app)/tasks/${t.id}`)} /> ))} )} {/* โ”€โ”€ Assigned to Me โ”€โ”€ */} {assignedToMe.length > 0 && ( <> Assigned to Me {[...assignedToMe].sort(byPrio).map((t: any) => ( router.push(`/(app)/tasks/${t.id}`)} /> ))} )} {/* โ”€โ”€ Unpaid Invoices โ”€โ”€ */} Unpaid Invoices router.push('/(app)/payments')} hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}> View all {unpaidInvoices.length === 0 ? ( No unpaid invoices ๐ŸŽ‰ ) : ( {unpaidInvoices.map((inv: any) => ( ))} )} )} ); }