Major Enhancement: NestJS Migration + CASL Authorization + Error Handling
Some checks failed
CI/CD Pipeline / Backend Tests (push) Has been cancelled
CI/CD Pipeline / Frontend Tests (push) Has been cancelled
CI/CD Pipeline / Build Docker Images (push) Has been cancelled
CI/CD Pipeline / Security Scan (push) Has been cancelled
CI/CD Pipeline / Deploy to Staging (push) Has been cancelled
CI/CD Pipeline / Deploy to Production (push) Has been cancelled

Complete rewrite from Express to NestJS with enterprise-grade features:

## Backend Improvements
- Migrated from Express to NestJS 11.0.1 with TypeScript
- Implemented Prisma ORM 7.3.0 for type-safe database access
- Added CASL authorization system replacing role-based guards
- Created global exception filters with structured logging
- Implemented Auth0 JWT authentication with Passport.js
- Added vehicle management with conflict detection
- Enhanced event scheduling with driver/vehicle assignment
- Comprehensive error handling and logging

## Frontend Improvements
- Upgraded to React 19.2.0 with Vite 7.2.4
- Implemented CASL-based permission system
- Added AbilityContext for declarative permissions
- Created ErrorHandler utility for consistent error messages
- Enhanced API client with request/response logging
- Added War Room (Command Center) dashboard
- Created VIP Schedule view with complete itineraries
- Implemented Vehicle Management UI
- Added mock data generators for testing (288 events across 20 VIPs)

## New Features
- Vehicle fleet management (types, capacity, status tracking)
- Complete 3-day Jamboree schedule generation
- Individual VIP schedule pages with PDF export (planned)
- Real-time War Room dashboard with auto-refresh
- Permission-based navigation filtering
- First user auto-approval as administrator

## Documentation
- Created CASL_AUTHORIZATION.md (comprehensive guide)
- Created ERROR_HANDLING.md (error handling patterns)
- Updated CLAUDE.md with new architecture
- Added migration guides and best practices

## Technical Debt Resolved
- Removed custom authentication in favor of Auth0
- Replaced role checks with CASL abilities
- Standardized error responses across API
- Implemented proper TypeScript typing
- Added comprehensive logging

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-31 08:50:25 +01:00
parent 8ace1ab2c1
commit 868f7efc23
351 changed files with 44997 additions and 6276 deletions

View File

@@ -1,833 +0,0 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiCall } from '../config/api';
import { generateTestVips, getTestOrganizations, generateVipSchedule } from '../utils/testVipData';
interface ApiKeys {
aviationStackKey?: string;
googleMapsKey?: string;
twilioKey?: string;
googleClientId?: string;
googleClientSecret?: string;
}
interface SystemSettings {
defaultPickupLocation?: string;
defaultDropoffLocation?: string;
timeZone?: string;
notificationsEnabled?: boolean;
}
const AdminDashboard: React.FC = () => {
const navigate = useNavigate();
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [adminPassword, setAdminPassword] = useState('');
const [apiKeys, setApiKeys] = useState<ApiKeys>({});
const [systemSettings, setSystemSettings] = useState<SystemSettings>({});
const [testResults, setTestResults] = useState<{ [key: string]: string }>({});
const [loading, setLoading] = useState(false);
const [saveStatus, setSaveStatus] = useState<string | null>(null);
const [showKeys, setShowKeys] = useState<{ [key: string]: boolean }>({});
const [savedKeys, setSavedKeys] = useState<{ [key: string]: boolean }>({});
const [testDataLoading, setTestDataLoading] = useState(false);
const [testDataStatus, setTestDataStatus] = useState<string | null>(null);
useEffect(() => {
// Check if already authenticated
const authStatus = sessionStorage.getItem('adminAuthenticated');
if (authStatus === 'true') {
setIsAuthenticated(true);
loadSettings();
}
}, []);
const handleLogin = async (e: React.FormEvent) => {
e.preventDefault();
try {
const response = await fetch('/api/admin/authenticate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password: adminPassword })
});
if (response.ok) {
setIsAuthenticated(true);
sessionStorage.setItem('adminAuthenticated', 'true');
loadSettings();
} else {
alert('Invalid admin password');
}
} catch (error) {
alert('Authentication failed');
}
};
const loadSettings = async () => {
try {
const response = await fetch('/api/admin/settings', {
headers: {
'Admin-Auth': sessionStorage.getItem('adminAuthenticated') || ''
}
});
if (response.ok) {
const data = await response.json();
// Track which keys are already saved (masked keys start with ***)
const saved: { [key: string]: boolean } = {};
if (data.apiKeys) {
Object.entries(data.apiKeys).forEach(([key, value]) => {
if (value && (value as string).startsWith('***')) {
saved[key] = true;
}
});
}
setSavedKeys(saved);
// Don't load masked keys as actual values - keep them empty
const cleanedApiKeys: ApiKeys = {};
if (data.apiKeys) {
Object.entries(data.apiKeys).forEach(([key, value]) => {
// Only set the value if it's not a masked key
if (value && !(value as string).startsWith('***')) {
cleanedApiKeys[key as keyof ApiKeys] = value as string;
}
});
}
setApiKeys(cleanedApiKeys);
setSystemSettings(data.systemSettings || {});
}
} catch (error) {
console.error('Failed to load settings:', error);
}
};
const handleApiKeyChange = (key: keyof ApiKeys, value: string) => {
setApiKeys(prev => ({ ...prev, [key]: value }));
// If user is typing a new key, mark it as not saved anymore
if (value && !value.startsWith('***')) {
setSavedKeys(prev => ({ ...prev, [key]: false }));
}
};
const handleSettingChange = (key: keyof SystemSettings, value: any) => {
setSystemSettings(prev => ({ ...prev, [key]: value }));
};
const testApiConnection = async (apiType: string) => {
setTestResults(prev => ({ ...prev, [apiType]: 'Testing...' }));
try {
const response = await fetch(`/api/admin/test-api/${apiType}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Admin-Auth': sessionStorage.getItem('adminAuthenticated') || ''
},
body: JSON.stringify({
apiKey: apiKeys[apiType as keyof ApiKeys]
})
});
const result = await response.json();
if (response.ok) {
setTestResults(prev => ({
...prev,
[apiType]: `Success: ${result.message}`
}));
} else {
setTestResults(prev => ({
...prev,
[apiType]: `Failed: ${result.error}`
}));
}
} catch (error) {
setTestResults(prev => ({
...prev,
[apiType]: 'Connection error'
}));
}
};
const saveSettings = async () => {
setLoading(true);
setSaveStatus(null);
try {
const response = await fetch('/api/admin/settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Admin-Auth': sessionStorage.getItem('adminAuthenticated') || ''
},
body: JSON.stringify({
apiKeys,
systemSettings
})
});
if (response.ok) {
setSaveStatus('Settings saved successfully!');
// Mark keys as saved if they have values
const newSavedKeys: { [key: string]: boolean } = {};
Object.entries(apiKeys).forEach(([key, value]) => {
if (value && !value.startsWith('***')) {
newSavedKeys[key] = true;
}
});
setSavedKeys(prev => ({ ...prev, ...newSavedKeys }));
// Clear the input fields after successful save
setApiKeys({});
setTimeout(() => setSaveStatus(null), 3000);
} else {
setSaveStatus('Failed to save settings');
}
} catch (error) {
setSaveStatus('Error saving settings');
} finally {
setLoading(false);
}
};
const handleLogout = () => {
sessionStorage.removeItem('adminAuthenticated');
setIsAuthenticated(false);
navigate('/');
};
// Test VIP functions
const createTestVips = async () => {
setTestDataLoading(true);
setTestDataStatus('Creating test VIPs and schedules...');
try {
const token = localStorage.getItem('authToken');
const testVips = generateTestVips();
let vipSuccessCount = 0;
let vipErrorCount = 0;
let scheduleSuccessCount = 0;
let scheduleErrorCount = 0;
const createdVipIds: string[] = [];
// First, create all VIPs
for (const vipData of testVips) {
try {
const response = await apiCall('/api/vips', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(vipData),
});
if (response.ok) {
const createdVip = await response.json();
createdVipIds.push(createdVip.id);
vipSuccessCount++;
} else {
vipErrorCount++;
console.error(`Failed to create VIP: ${vipData.name}`);
}
} catch (error) {
vipErrorCount++;
console.error(`Error creating VIP ${vipData.name}:`, error);
}
}
setTestDataStatus(`Created ${vipSuccessCount} VIPs, now creating schedules...`);
// Then, create schedules for each successfully created VIP
for (let i = 0; i < createdVipIds.length; i++) {
const vipId = createdVipIds[i];
const vipData = testVips[i];
try {
const scheduleEvents = generateVipSchedule(vipData.department, vipData.transportMode);
for (const event of scheduleEvents) {
try {
const eventWithId = {
...event,
id: Date.now().toString() + Math.random().toString(36).substr(2, 9)
};
const scheduleResponse = await apiCall(`/api/vips/${vipId}/schedule`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(eventWithId),
});
if (scheduleResponse.ok) {
scheduleSuccessCount++;
} else {
scheduleErrorCount++;
console.error(`Failed to create schedule event for ${vipData.name}: ${event.title}`);
}
} catch (error) {
scheduleErrorCount++;
console.error(`Error creating schedule event for ${vipData.name}:`, error);
}
}
} catch (error) {
console.error(`Error generating schedule for ${vipData.name}:`, error);
}
}
setTestDataStatus(`✅ Created ${vipSuccessCount} VIPs with ${scheduleSuccessCount} schedule events! ${vipErrorCount > 0 || scheduleErrorCount > 0 ? `(${vipErrorCount + scheduleErrorCount} failed)` : ''}`);
} catch (error) {
setTestDataStatus('❌ Failed to create test VIPs and schedules');
console.error('Error creating test data:', error);
} finally {
setTestDataLoading(false);
setTimeout(() => setTestDataStatus(null), 8000);
}
};
const removeTestVips = async () => {
if (!confirm('Are you sure you want to remove all test VIPs? This will delete VIPs from the test organizations.')) {
return;
}
setTestDataLoading(true);
setTestDataStatus('Removing test VIPs...');
try {
const token = localStorage.getItem('authToken');
// First, get all VIPs
const response = await apiCall('/api/vips', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch VIPs');
}
const allVips = await response.json();
// Filter test VIPs by organization names
const testOrganizations = getTestOrganizations();
const testVips = allVips.filter((vip: any) => testOrganizations.includes(vip.organization));
let successCount = 0;
let errorCount = 0;
for (const vip of testVips) {
try {
const deleteResponse = await apiCall(`/api/vips/${vip.id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (deleteResponse.ok) {
successCount++;
} else {
errorCount++;
console.error(`Failed to delete VIP: ${vip.name}`);
}
} catch (error) {
errorCount++;
console.error(`Error deleting VIP ${vip.name}:`, error);
}
}
setTestDataStatus(`🗑️ Removed ${successCount} test VIPs successfully! ${errorCount > 0 ? `(${errorCount} failed)` : ''}`);
} catch (error) {
setTestDataStatus('❌ Failed to remove test VIPs');
console.error('Error removing test VIPs:', error);
} finally {
setTestDataLoading(false);
setTimeout(() => setTestDataStatus(null), 5000);
}
};
if (!isAuthenticated) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex justify-center items-center">
<div className="bg-white rounded-2xl shadow-xl p-8 w-full max-w-md border border-slate-200/60">
<div className="text-center mb-8">
<div className="w-16 h-16 bg-gradient-to-br from-amber-500 to-orange-600 rounded-full flex items-center justify-center mx-auto mb-4">
<div className="w-8 h-8 bg-white rounded-full flex items-center justify-center">
<div className="w-4 h-4 bg-amber-500 rounded-full"></div>
</div>
</div>
<h2 className="text-2xl font-bold text-slate-800">Admin Login</h2>
<p className="text-slate-600 mt-2">Enter your admin password to continue</p>
</div>
<form onSubmit={handleLogin} className="space-y-6">
<div className="form-group">
<label htmlFor="password" className="form-label">Admin Password</label>
<input
type="password"
id="password"
value={adminPassword}
onChange={(e) => setAdminPassword(e.target.value)}
className="form-input"
placeholder="Enter admin password"
required
/>
</div>
<button type="submit" className="btn btn-primary w-full">
Login
</button>
</form>
</div>
</div>
);
}
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
Admin Dashboard
</h1>
<p className="text-slate-600 mt-2">System configuration and API management</p>
</div>
<div className="flex items-center space-x-4">
<button
className="btn btn-secondary"
onClick={() => navigate('/')}
>
Back to Dashboard
</button>
<button
className="btn btn-danger"
onClick={handleLogout}
>
Logout
</button>
</div>
</div>
</div>
{/* API Keys Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">API Key Management</h2>
<p className="text-slate-600 mt-1">Configure external service integrations</p>
</div>
<div className="p-8 space-y-8">
{/* AviationStack API */}
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">AviationStack API</h3>
{savedKeys.aviationStackKey && (
<span className="bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
Configured
</span>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-4 gap-4 items-end">
<div className="lg:col-span-2">
<label className="form-label">API Key</label>
<div className="relative">
<input
type={showKeys.aviationStackKey ? 'text' : 'password'}
placeholder={savedKeys.aviationStackKey ? 'Key saved (enter new key to update)' : 'Enter AviationStack API key'}
value={apiKeys.aviationStackKey || ''}
onChange={(e) => handleApiKeyChange('aviationStackKey', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.aviationStackKey && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, aviationStackKey: !prev.aviationStackKey }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.aviationStackKey ? 'Hide' : 'Show'}
</button>
)}
</div>
<p className="text-xs text-slate-500 mt-1">
Get your key from: https://aviationstack.com/dashboard
</p>
</div>
<div>
<button
className="btn btn-secondary w-full"
onClick={() => testApiConnection('aviationStackKey')}
>
Test Connection
</button>
</div>
<div>
{testResults.aviationStackKey && (
<div className={`p-3 rounded-lg text-sm ${
testResults.aviationStackKey.includes('Success')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{testResults.aviationStackKey}
</div>
)}
</div>
</div>
</div>
{/* Google OAuth Credentials */}
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Google OAuth Credentials</h3>
{(savedKeys.googleClientId && savedKeys.googleClientSecret) && (
<span className="bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
Configured
</span>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="form-group">
<label className="form-label">Client ID</label>
<div className="relative">
<input
type={showKeys.googleClientId ? 'text' : 'password'}
placeholder={savedKeys.googleClientId ? 'Client ID saved' : 'Enter Google OAuth Client ID'}
value={apiKeys.googleClientId || ''}
onChange={(e) => handleApiKeyChange('googleClientId', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.googleClientId && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, googleClientId: !prev.googleClientId }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.googleClientId ? 'Hide' : 'Show'}
</button>
)}
</div>
</div>
<div className="form-group">
<label className="form-label">Client Secret</label>
<div className="relative">
<input
type={showKeys.googleClientSecret ? 'text' : 'password'}
placeholder={savedKeys.googleClientSecret ? 'Client Secret saved' : 'Enter Google OAuth Client Secret'}
value={apiKeys.googleClientSecret || ''}
onChange={(e) => handleApiKeyChange('googleClientSecret', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.googleClientSecret && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, googleClientSecret: !prev.googleClientSecret }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.googleClientSecret ? 'Hide' : 'Show'}
</button>
)}
</div>
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-4">
<h4 className="font-semibold text-blue-900 mb-2">Setup Instructions</h4>
<ol className="text-sm text-blue-800 space-y-1 list-decimal list-inside">
<li>Go to Google Cloud Console</li>
<li>Create or select a project</li>
<li>Enable the Google+ API</li>
<li>Go to "Credentials" "Create Credentials" "OAuth 2.0 Client IDs"</li>
<li>Set authorized redirect URI: https://your-domain.com/auth/google/callback</li>
<li>Set authorized JavaScript origins: https://your-domain.com</li>
</ol>
</div>
</div>
{/* Future APIs */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-50">
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Google Maps API</h3>
<span className="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-0.5 rounded-full">
Coming Soon
</span>
</div>
<input
type="password"
placeholder="Google Maps API key (not yet implemented)"
disabled
className="form-input"
/>
</div>
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Twilio API</h3>
<span className="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-0.5 rounded-full">
Coming Soon
</span>
</div>
<input
type="password"
placeholder="Twilio API key (not yet implemented)"
disabled
className="form-input"
/>
</div>
</div>
</div>
</div>
{/* System Settings Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-green-50 to-emerald-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">System Settings</h2>
<p className="text-slate-600 mt-1">Configure default system behavior</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="form-group">
<label htmlFor="defaultPickup" className="form-label">Default Pickup Location</label>
<input
type="text"
id="defaultPickup"
value={systemSettings.defaultPickupLocation || ''}
onChange={(e) => handleSettingChange('defaultPickupLocation', e.target.value)}
placeholder="e.g., JFK Airport Terminal 4"
className="form-input"
/>
</div>
<div className="form-group">
<label htmlFor="defaultDropoff" className="form-label">Default Dropoff Location</label>
<input
type="text"
id="defaultDropoff"
value={systemSettings.defaultDropoffLocation || ''}
onChange={(e) => handleSettingChange('defaultDropoffLocation', e.target.value)}
placeholder="e.g., Hilton Downtown"
className="form-input"
/>
</div>
<div className="form-group">
<label htmlFor="timezone" className="form-label">Time Zone</label>
<select
id="timezone"
value={systemSettings.timeZone || 'America/New_York'}
onChange={(e) => handleSettingChange('timeZone', e.target.value)}
className="form-select"
>
<option value="America/New_York">Eastern Time</option>
<option value="America/Chicago">Central Time</option>
<option value="America/Denver">Mountain Time</option>
<option value="America/Los_Angeles">Pacific Time</option>
<option value="UTC">UTC</option>
</select>
</div>
<div className="form-group">
<div className="checkbox-option">
<input
type="checkbox"
checked={systemSettings.notificationsEnabled || false}
onChange={(e) => handleSettingChange('notificationsEnabled', e.target.checked)}
className="form-checkbox mr-3"
/>
<span className="font-medium">Enable Email/SMS Notifications</span>
</div>
</div>
</div>
</div>
</div>
{/* Test VIP Data Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-orange-50 to-red-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">Test VIP Data Management</h2>
<p className="text-slate-600 mt-1">Create and manage test VIP data for application testing</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-green-50 border border-green-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Create Test VIPs</h3>
<p className="text-slate-600 mb-4">
Generate 20 diverse test VIPs (10 Admin department, 10 Office of Development) with realistic data including flights, transport modes, and special requirements.
</p>
<ul className="text-sm text-slate-600 mb-4 space-y-1">
<li> Mixed flight and self-driving transport modes</li>
<li> Single flights, connecting flights, and multi-segment journeys</li>
<li> Diverse organizations and special requirements</li>
<li> Realistic arrival dates (tomorrow and day after)</li>
</ul>
<button
className="btn btn-success w-full"
onClick={createTestVips}
disabled={testDataLoading}
>
{testDataLoading ? (
<>
<span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full mr-2"></span>
Creating Test VIPs...
</>
) : (
'🎭 Create 20 Test VIPs'
)}
</button>
</div>
<div className="bg-red-50 border border-red-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Remove Test VIPs</h3>
<p className="text-slate-600 mb-4">
Remove all test VIPs from the system. This will delete VIPs from the following test organizations:
</p>
<div className="text-xs text-slate-500 mb-4 max-h-20 overflow-y-auto">
<div className="grid grid-cols-1 gap-1">
{getTestOrganizations().slice(0, 8).map(org => (
<div key={org}> {org}</div>
))}
<div className="text-slate-400">... and 12 more organizations</div>
</div>
</div>
<button
className="btn btn-danger w-full"
onClick={removeTestVips}
disabled={testDataLoading}
>
{testDataLoading ? (
<>
<span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full mr-2"></span>
Removing Test VIPs...
</>
) : (
'🗑️ Remove All Test VIPs'
)}
</button>
</div>
</div>
{testDataStatus && (
<div className={`mt-6 p-4 rounded-lg text-center font-medium ${
testDataStatus.includes('✅') || testDataStatus.includes('🗑️')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{testDataStatus}
</div>
)}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-6">
<h4 className="font-semibold text-blue-900 mb-2">💡 Test Data Details</h4>
<div className="text-sm text-blue-800 space-y-1">
<p><strong>Admin Department (10 VIPs):</strong> University officials, ambassadors, ministers, and executives</p>
<p><strong>Office of Development (10 VIPs):</strong> Donors, foundation leaders, and philanthropists</p>
<p><strong>Transport Modes:</strong> Mix of flights (single, connecting, multi-segment) and self-driving</p>
<p><strong>Special Requirements:</strong> Dietary restrictions, accessibility needs, security details, interpreters</p>
<p><strong>Full Day Schedules:</strong> Each VIP gets 5-7 realistic events including meetings, meals, tours, and presentations</p>
<p><strong>Schedule Types:</strong> Airport pickup, welcome breakfast, department meetings, working lunches, campus tours, receptions</p>
</div>
</div>
</div>
</div>
{/* API Documentation Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-purple-50 to-pink-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">API Documentation</h2>
<p className="text-slate-600 mt-1">Developer resources and API testing</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-blue-50 border border-blue-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Interactive API Documentation</h3>
<p className="text-slate-600 mb-4">
Explore and test all API endpoints with the interactive Swagger UI documentation.
</p>
<button
className="btn btn-primary w-full mb-2"
onClick={() => window.open('http://localhost:3000/api-docs.html', '_blank')}
>
Open API Documentation
</button>
<p className="text-xs text-slate-500">
Opens in a new tab with full endpoint documentation and testing capabilities
</p>
</div>
<div className="bg-green-50 border border-green-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Quick API Examples</h3>
<div className="space-y-2 text-sm">
<div>
<span className="font-medium">Health Check:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/health</code>
</div>
<div>
<span className="font-medium">Get VIPs:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/vips</code>
</div>
<div>
<span className="font-medium">Get Drivers:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/drivers</code>
</div>
<div>
<span className="font-medium">Flight Info:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/flights/UA1234</code>
</div>
</div>
<button
className="btn btn-secondary w-full mt-4"
onClick={() => window.open('/README-API.md', '_blank')}
>
View API Guide
</button>
</div>
</div>
<div className="bg-amber-50 border border-amber-200 rounded-lg p-4 mt-6">
<p className="text-amber-800">
<strong>Pro Tip:</strong> The interactive documentation allows you to test API endpoints directly in your browser.
Perfect for developers integrating with the VIP Coordinator system!
</p>
</div>
</div>
</div>
{/* Save Button */}
<div className="text-center">
<button
className="btn btn-success text-lg px-8 py-4"
onClick={saveSettings}
disabled={loading}
>
{loading ? 'Saving...' : 'Save All Settings'}
</button>
{saveStatus && (
<div className={`mt-4 p-4 rounded-lg ${
saveStatus.includes('successfully')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{saveStatus}
</div>
)}
</div>
</div>
);
};
export default AdminDashboard;

View File

@@ -1,800 +0,0 @@
import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiCall } from '../utils/api';
import { generateTestVips, getTestOrganizations, generateVipSchedule } from '../utils/testVipData';
interface User {
id: string;
email: string;
name: string;
role: string;
}
interface ApiKeys {
aviationStackKey?: string;
googleMapsKey?: string;
twilioKey?: string;
googleClientId?: string;
googleClientSecret?: string;
}
interface SystemSettings {
defaultPickupLocation?: string;
defaultDropoffLocation?: string;
timeZone?: string;
notificationsEnabled?: boolean;
}
const AdminDashboard: React.FC = () => {
const navigate = useNavigate();
const [user, setUser] = useState<User | null>(null);
const [apiKeys, setApiKeys] = useState<ApiKeys>({});
const [systemSettings, setSystemSettings] = useState<SystemSettings>({});
const [testResults, setTestResults] = useState<{ [key: string]: string }>({});
const [loading, setLoading] = useState(false);
const [saveStatus, setSaveStatus] = useState<string | null>(null);
const [showKeys, setShowKeys] = useState<{ [key: string]: boolean }>({});
const [savedKeys, setSavedKeys] = useState<{ [key: string]: boolean }>({});
const [testDataLoading, setTestDataLoading] = useState(false);
const [testDataStatus, setTestDataStatus] = useState<string | null>(null);
useEffect(() => {
// Check if user is authenticated and has admin role
const authToken = localStorage.getItem('authToken');
const userData = localStorage.getItem('user');
if (!authToken || !userData) {
navigate('/');
return;
}
const parsedUser = JSON.parse(userData);
if (parsedUser.role !== 'administrator' && parsedUser.role !== 'coordinator') {
navigate('/dashboard');
return;
}
setUser(parsedUser);
loadSettings();
}, [navigate]);
const loadSettings = async () => {
try {
const response = await apiCall('/api/admin/settings');
if (response.ok) {
const data = await response.json();
// Track which keys are already saved (masked keys start with ***)
const saved: { [key: string]: boolean } = {};
if (data.apiKeys) {
Object.entries(data.apiKeys).forEach(([key, value]) => {
if (value && (value as string).startsWith('***')) {
saved[key] = true;
}
});
}
setSavedKeys(saved);
// Don't load masked keys as actual values - keep them empty
const cleanedApiKeys: ApiKeys = {};
if (data.apiKeys) {
Object.entries(data.apiKeys).forEach(([key, value]) => {
// Only set the value if it's not a masked key
if (value && !(value as string).startsWith('***')) {
cleanedApiKeys[key as keyof ApiKeys] = value as string;
}
});
}
setApiKeys(cleanedApiKeys);
setSystemSettings(data.systemSettings || {});
}
} catch (error) {
console.error('Failed to load settings:', error);
}
};
const handleApiKeyChange = (key: keyof ApiKeys, value: string) => {
setApiKeys(prev => ({ ...prev, [key]: value }));
// If user is typing a new key, mark it as not saved anymore
if (value && !value.startsWith('***')) {
setSavedKeys(prev => ({ ...prev, [key]: false }));
}
};
const handleSettingChange = (key: keyof SystemSettings, value: any) => {
setSystemSettings(prev => ({ ...prev, [key]: value }));
};
const testApiConnection = async (apiType: string) => {
setTestResults(prev => ({ ...prev, [apiType]: 'Testing...' }));
try {
const response = await fetch(`/api/admin/test-api/${apiType}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Admin-Auth': sessionStorage.getItem('adminAuthenticated') || ''
},
body: JSON.stringify({
apiKey: apiKeys[apiType as keyof ApiKeys]
})
});
const result = await response.json();
if (response.ok) {
setTestResults(prev => ({
...prev,
[apiType]: `Success: ${result.message}`
}));
} else {
setTestResults(prev => ({
...prev,
[apiType]: `Failed: ${result.error}`
}));
}
} catch (error) {
setTestResults(prev => ({
...prev,
[apiType]: 'Connection error'
}));
}
};
const saveSettings = async () => {
setLoading(true);
setSaveStatus(null);
try {
const response = await fetch('/api/admin/settings', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Admin-Auth': sessionStorage.getItem('adminAuthenticated') || ''
},
body: JSON.stringify({
apiKeys,
systemSettings
})
});
if (response.ok) {
setSaveStatus('Settings saved successfully!');
// Mark keys as saved if they have values
const newSavedKeys: { [key: string]: boolean } = {};
Object.entries(apiKeys).forEach(([key, value]) => {
if (value && !value.startsWith('***')) {
newSavedKeys[key] = true;
}
});
setSavedKeys(prev => ({ ...prev, ...newSavedKeys }));
// Clear the input fields after successful save
setApiKeys({});
setTimeout(() => setSaveStatus(null), 3000);
} else {
setSaveStatus('Failed to save settings');
}
} catch (error) {
setSaveStatus('Error saving settings');
} finally {
setLoading(false);
}
};
const handleLogout = () => {
sessionStorage.removeItem('adminAuthenticated');
setIsAuthenticated(false);
navigate('/');
};
// Test VIP functions
const createTestVips = async () => {
setTestDataLoading(true);
setTestDataStatus('Creating test VIPs and schedules...');
try {
const token = localStorage.getItem('authToken');
const testVips = generateTestVips();
let vipSuccessCount = 0;
let vipErrorCount = 0;
let scheduleSuccessCount = 0;
let scheduleErrorCount = 0;
const createdVipIds: string[] = [];
// First, create all VIPs
for (const vipData of testVips) {
try {
const response = await apiCall('/api/vips', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(vipData),
});
if (response.ok) {
const createdVip = await response.json();
createdVipIds.push(createdVip.id);
vipSuccessCount++;
} else {
vipErrorCount++;
console.error(`Failed to create VIP: ${vipData.name}`);
}
} catch (error) {
vipErrorCount++;
console.error(`Error creating VIP ${vipData.name}:`, error);
}
}
setTestDataStatus(`Created ${vipSuccessCount} VIPs, now creating schedules...`);
// Then, create schedules for each successfully created VIP
for (let i = 0; i < createdVipIds.length; i++) {
const vipId = createdVipIds[i];
const vipData = testVips[i];
try {
const scheduleEvents = generateVipSchedule(vipData.department, vipData.transportMode);
for (const event of scheduleEvents) {
try {
const eventWithId = {
...event,
id: Date.now().toString() + Math.random().toString(36).substr(2, 9)
};
const scheduleResponse = await apiCall(`/api/vips/${vipId}/schedule`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(eventWithId),
});
if (scheduleResponse.ok) {
scheduleSuccessCount++;
} else {
scheduleErrorCount++;
console.error(`Failed to create schedule event for ${vipData.name}: ${event.title}`);
}
} catch (error) {
scheduleErrorCount++;
console.error(`Error creating schedule event for ${vipData.name}:`, error);
}
}
} catch (error) {
console.error(`Error generating schedule for ${vipData.name}:`, error);
}
}
setTestDataStatus(`✅ Created ${vipSuccessCount} VIPs with ${scheduleSuccessCount} schedule events! ${vipErrorCount > 0 || scheduleErrorCount > 0 ? `(${vipErrorCount + scheduleErrorCount} failed)` : ''}`);
} catch (error) {
setTestDataStatus('❌ Failed to create test VIPs and schedules');
console.error('Error creating test data:', error);
} finally {
setTestDataLoading(false);
setTimeout(() => setTestDataStatus(null), 8000);
}
};
const removeTestVips = async () => {
if (!confirm('Are you sure you want to remove all test VIPs? This will delete VIPs from the test organizations.')) {
return;
}
setTestDataLoading(true);
setTestDataStatus('Removing test VIPs...');
try {
const token = localStorage.getItem('authToken');
// First, get all VIPs
const response = await apiCall('/api/vips', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch VIPs');
}
const allVips = await response.json();
// Filter test VIPs by organization names
const testOrganizations = getTestOrganizations();
const testVips = allVips.filter((vip: any) => testOrganizations.includes(vip.organization));
let successCount = 0;
let errorCount = 0;
for (const vip of testVips) {
try {
const deleteResponse = await apiCall(`/api/vips/${vip.id}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (deleteResponse.ok) {
successCount++;
} else {
errorCount++;
console.error(`Failed to delete VIP: ${vip.name}`);
}
} catch (error) {
errorCount++;
console.error(`Error deleting VIP ${vip.name}:`, error);
}
}
setTestDataStatus(`🗑️ Removed ${successCount} test VIPs successfully! ${errorCount > 0 ? `(${errorCount} failed)` : ''}`);
} catch (error) {
setTestDataStatus('❌ Failed to remove test VIPs');
console.error('Error removing test VIPs:', error);
} finally {
setTestDataLoading(false);
setTimeout(() => setTestDataStatus(null), 5000);
}
};
if (!user) {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex justify-center items-center">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-amber-500 border-t-transparent mx-auto"></div>
<p className="mt-4 text-slate-600">Loading...</p>
</div>
</div>
);
}
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
Admin Dashboard
</h1>
<p className="text-slate-600 mt-2">System configuration and API management</p>
</div>
<div className="flex items-center space-x-4">
<button
className="btn btn-secondary"
onClick={() => navigate('/')}
>
Back to Dashboard
</button>
<button
className="btn btn-danger"
onClick={handleLogout}
>
Logout
</button>
</div>
</div>
</div>
{/* API Keys Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">API Key Management</h2>
<p className="text-slate-600 mt-1">Configure external service integrations</p>
</div>
<div className="p-8 space-y-8">
{/* AviationStack API */}
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">AviationStack API</h3>
{savedKeys.aviationStackKey && (
<span className="bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
Configured
</span>
)}
</div>
<div className="grid grid-cols-1 lg:grid-cols-4 gap-4 items-end">
<div className="lg:col-span-2">
<label className="form-label">API Key</label>
<div className="relative">
<input
type={showKeys.aviationStackKey ? 'text' : 'password'}
placeholder={savedKeys.aviationStackKey ? 'Key saved (enter new key to update)' : 'Enter AviationStack API key'}
value={apiKeys.aviationStackKey || ''}
onChange={(e) => handleApiKeyChange('aviationStackKey', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.aviationStackKey && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, aviationStackKey: !prev.aviationStackKey }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.aviationStackKey ? 'Hide' : 'Show'}
</button>
)}
</div>
<p className="text-xs text-slate-500 mt-1">
Get your key from: https://aviationstack.com/dashboard
</p>
</div>
<div>
<button
className="btn btn-secondary w-full"
onClick={() => testApiConnection('aviationStackKey')}
>
Test Connection
</button>
</div>
<div>
{testResults.aviationStackKey && (
<div className={`p-3 rounded-lg text-sm ${
testResults.aviationStackKey.includes('Success')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{testResults.aviationStackKey}
</div>
)}
</div>
</div>
</div>
{/* Google OAuth Credentials */}
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Google OAuth Credentials</h3>
{(savedKeys.googleClientId && savedKeys.googleClientSecret) && (
<span className="bg-green-100 text-green-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
Configured
</span>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="form-group">
<label className="form-label">Client ID</label>
<div className="relative">
<input
type={showKeys.googleClientId ? 'text' : 'password'}
placeholder={savedKeys.googleClientId ? 'Client ID saved' : 'Enter Google OAuth Client ID'}
value={apiKeys.googleClientId || ''}
onChange={(e) => handleApiKeyChange('googleClientId', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.googleClientId && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, googleClientId: !prev.googleClientId }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.googleClientId ? 'Hide' : 'Show'}
</button>
)}
</div>
</div>
<div className="form-group">
<label className="form-label">Client Secret</label>
<div className="relative">
<input
type={showKeys.googleClientSecret ? 'text' : 'password'}
placeholder={savedKeys.googleClientSecret ? 'Client Secret saved' : 'Enter Google OAuth Client Secret'}
value={apiKeys.googleClientSecret || ''}
onChange={(e) => handleApiKeyChange('googleClientSecret', e.target.value)}
className="form-input pr-12"
/>
{savedKeys.googleClientSecret && (
<button
type="button"
onClick={() => setShowKeys(prev => ({ ...prev, googleClientSecret: !prev.googleClientSecret }))}
className="absolute right-3 top-1/2 transform -translate-y-1/2 text-slate-400 hover:text-slate-600"
>
{showKeys.googleClientSecret ? 'Hide' : 'Show'}
</button>
)}
</div>
</div>
</div>
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-4">
<h4 className="font-semibold text-blue-900 mb-2">Setup Instructions</h4>
<ol className="text-sm text-blue-800 space-y-1 list-decimal list-inside">
<li>Go to Google Cloud Console</li>
<li>Create or select a project</li>
<li>Enable the Google+ API</li>
<li>Go to "Credentials" "Create Credentials" "OAuth 2.0 Client IDs"</li>
<li>Set authorized redirect URI: https://your-domain.com/auth/google/callback</li>
<li>Set authorized JavaScript origins: https://your-domain.com</li>
</ol>
</div>
</div>
{/* Future APIs */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 opacity-50">
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Google Maps API</h3>
<span className="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-0.5 rounded-full">
Coming Soon
</span>
</div>
<input
type="password"
placeholder="Google Maps API key (not yet implemented)"
disabled
className="form-input"
/>
</div>
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Twilio API</h3>
<span className="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-0.5 rounded-full">
Coming Soon
</span>
</div>
<input
type="password"
placeholder="Twilio API key (not yet implemented)"
disabled
className="form-input"
/>
</div>
</div>
</div>
</div>
{/* System Settings Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-green-50 to-emerald-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">System Settings</h2>
<p className="text-slate-600 mt-1">Configure default system behavior</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="form-group">
<label htmlFor="defaultPickup" className="form-label">Default Pickup Location</label>
<input
type="text"
id="defaultPickup"
value={systemSettings.defaultPickupLocation || ''}
onChange={(e) => handleSettingChange('defaultPickupLocation', e.target.value)}
placeholder="e.g., JFK Airport Terminal 4"
className="form-input"
/>
</div>
<div className="form-group">
<label htmlFor="defaultDropoff" className="form-label">Default Dropoff Location</label>
<input
type="text"
id="defaultDropoff"
value={systemSettings.defaultDropoffLocation || ''}
onChange={(e) => handleSettingChange('defaultDropoffLocation', e.target.value)}
placeholder="e.g., Hilton Downtown"
className="form-input"
/>
</div>
<div className="form-group">
<label htmlFor="timezone" className="form-label">Time Zone</label>
<select
id="timezone"
value={systemSettings.timeZone || 'America/New_York'}
onChange={(e) => handleSettingChange('timeZone', e.target.value)}
className="form-select"
>
<option value="America/New_York">Eastern Time</option>
<option value="America/Chicago">Central Time</option>
<option value="America/Denver">Mountain Time</option>
<option value="America/Los_Angeles">Pacific Time</option>
<option value="UTC">UTC</option>
</select>
</div>
<div className="form-group">
<div className="checkbox-option">
<input
type="checkbox"
checked={systemSettings.notificationsEnabled || false}
onChange={(e) => handleSettingChange('notificationsEnabled', e.target.checked)}
className="form-checkbox mr-3"
/>
<span className="font-medium">Enable Email/SMS Notifications</span>
</div>
</div>
</div>
</div>
</div>
{/* Test VIP Data Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-orange-50 to-red-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">Test VIP Data Management</h2>
<p className="text-slate-600 mt-1">Create and manage test VIP data for application testing</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-green-50 border border-green-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Create Test VIPs</h3>
<p className="text-slate-600 mb-4">
Generate 20 diverse test VIPs (10 Admin department, 10 Office of Development) with realistic data including flights, transport modes, and special requirements.
</p>
<ul className="text-sm text-slate-600 mb-4 space-y-1">
<li> Mixed flight and self-driving transport modes</li>
<li> Single flights, connecting flights, and multi-segment journeys</li>
<li> Diverse organizations and special requirements</li>
<li> Realistic arrival dates (tomorrow and day after)</li>
</ul>
<button
className="btn btn-success w-full"
onClick={createTestVips}
disabled={testDataLoading}
>
{testDataLoading ? (
<>
<span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full mr-2"></span>
Creating Test VIPs...
</>
) : (
'🎭 Create 20 Test VIPs'
)}
</button>
</div>
<div className="bg-red-50 border border-red-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Remove Test VIPs</h3>
<p className="text-slate-600 mb-4">
Remove all test VIPs from the system. This will delete VIPs from the following test organizations:
</p>
<div className="text-xs text-slate-500 mb-4 max-h-20 overflow-y-auto">
<div className="grid grid-cols-1 gap-1">
{getTestOrganizations().slice(0, 8).map(org => (
<div key={org}> {org}</div>
))}
<div className="text-slate-400">... and 12 more organizations</div>
</div>
</div>
<button
className="btn btn-danger w-full"
onClick={removeTestVips}
disabled={testDataLoading}
>
{testDataLoading ? (
<>
<span className="animate-spin inline-block w-4 h-4 border-2 border-white border-t-transparent rounded-full mr-2"></span>
Removing Test VIPs...
</>
) : (
'🗑️ Remove All Test VIPs'
)}
</button>
</div>
</div>
{testDataStatus && (
<div className={`mt-6 p-4 rounded-lg text-center font-medium ${
testDataStatus.includes('✅') || testDataStatus.includes('🗑️')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{testDataStatus}
</div>
)}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-6">
<h4 className="font-semibold text-blue-900 mb-2">💡 Test Data Details</h4>
<div className="text-sm text-blue-800 space-y-1">
<p><strong>Admin Department (10 VIPs):</strong> University officials, ambassadors, ministers, and executives</p>
<p><strong>Office of Development (10 VIPs):</strong> Donors, foundation leaders, and philanthropists</p>
<p><strong>Transport Modes:</strong> Mix of flights (single, connecting, multi-segment) and self-driving</p>
<p><strong>Special Requirements:</strong> Dietary restrictions, accessibility needs, security details, interpreters</p>
<p><strong>Full Day Schedules:</strong> Each VIP gets 5-7 realistic events including meetings, meals, tours, and presentations</p>
<p><strong>Schedule Types:</strong> Airport pickup, welcome breakfast, department meetings, working lunches, campus tours, receptions</p>
</div>
</div>
</div>
</div>
{/* API Documentation Section */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-purple-50 to-pink-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800">API Documentation</h2>
<p className="text-slate-600 mt-1">Developer resources and API testing</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-blue-50 border border-blue-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Interactive API Documentation</h3>
<p className="text-slate-600 mb-4">
Explore and test all API endpoints with the interactive Swagger UI documentation.
</p>
<button
className="btn btn-primary w-full mb-2"
onClick={() => window.open('http://localhost:3000/api-docs.html', '_blank')}
>
Open API Documentation
</button>
<p className="text-xs text-slate-500">
Opens in a new tab with full endpoint documentation and testing capabilities
</p>
</div>
<div className="bg-green-50 border border-green-200 rounded-xl p-6">
<h3 className="text-lg font-bold text-slate-800 mb-3">Quick API Examples</h3>
<div className="space-y-2 text-sm">
<div>
<span className="font-medium">Health Check:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/health</code>
</div>
<div>
<span className="font-medium">Get VIPs:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/vips</code>
</div>
<div>
<span className="font-medium">Get Drivers:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/drivers</code>
</div>
<div>
<span className="font-medium">Flight Info:</span>
<code className="ml-2 bg-white px-2 py-1 rounded text-xs">GET /api/flights/UA1234</code>
</div>
</div>
<button
className="btn btn-secondary w-full mt-4"
onClick={() => window.open('/README-API.md', '_blank')}
>
View API Guide
</button>
</div>
</div>
<div className="bg-amber-50 border border-amber-200 rounded-lg p-4 mt-6">
<p className="text-amber-800">
<strong>Pro Tip:</strong> The interactive documentation allows you to test API endpoints directly in your browser.
Perfect for developers integrating with the VIP Coordinator system!
</p>
</div>
</div>
</div>
{/* Save Button */}
<div className="text-center">
<button
className="btn btn-success text-lg px-8 py-4"
onClick={saveSettings}
disabled={loading}
>
{loading ? 'Saving...' : 'Save All Settings'}
</button>
{saveStatus && (
<div className={`mt-4 p-4 rounded-lg ${
saveStatus.includes('successfully')
? 'bg-green-50 text-green-700 border border-green-200'
: 'bg-red-50 text-red-700 border border-red-200'
}`}>
{saveStatus}
</div>
)}
</div>
</div>
);
};
export default AdminDashboard;

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth0 } from '@auth0/auth0-react';
export function Callback() {
const { isAuthenticated, isLoading } = useAuth0();
const navigate = useNavigate();
useEffect(() => {
if (!isLoading && isAuthenticated) {
navigate('/dashboard');
}
}, [isAuthenticated, isLoading, navigate]);
return (
<div className="min-h-screen flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary mx-auto mb-4"></div>
<p className="text-muted-foreground">Completing sign in...</p>
</div>
</div>
);
}

View File

@@ -0,0 +1,501 @@
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Loading } from '@/components/Loading';
import {
Car,
Clock,
MapPin,
Users,
AlertTriangle,
CheckCircle,
Plane,
Radio,
} from 'lucide-react';
import { useEffect } from 'react';
interface Event {
id: string;
title: string;
pickupLocation: string | null;
dropoffLocation: string | null;
location: string | null;
startTime: string;
endTime: string;
actualStartTime: string | null;
status: string;
type: string;
vip: {
id: string;
name: string;
};
driver: {
id: string;
name: string;
} | null;
vehicle: {
id: string;
name: string;
type: string;
seatCapacity: number;
} | null;
}
interface Vehicle {
id: string;
name: string;
type: string;
seatCapacity: number;
status: string;
currentDriver: { name: string } | null;
}
interface VIP {
id: string;
name: string;
organization: string | null;
arrivalMode: string;
expectedArrival: string | null;
flights: Array<{
id: string;
flightNumber: string;
arrivalAirport: string;
scheduledArrival: string | null;
status: string | null;
}>;
}
export function CommandCenter() {
const { data: events, refetch: refetchEvents } = useQuery<Event[]>({
queryKey: ['events'],
queryFn: async () => {
const { data } = await api.get('/events');
return data;
},
});
const { data: vehicles, refetch: refetchVehicles } = useQuery<Vehicle[]>({
queryKey: ['vehicles'],
queryFn: async () => {
const { data } = await api.get('/vehicles');
return data;
},
});
const { data: vips, refetch: refetchVips } = useQuery<VIP[]>({
queryKey: ['vips'],
queryFn: async () => {
const { data } = await api.get('/vips');
return data;
},
});
// Auto-refresh every 30 seconds
useEffect(() => {
const interval = setInterval(() => {
refetchEvents();
refetchVehicles();
refetchVips();
}, 30000);
return () => clearInterval(interval);
}, [refetchEvents, refetchVehicles, refetchVips]);
if (!events || !vehicles || !vips) {
return <Loading message="Loading Command Center..." />;
}
const now = new Date();
const twoHoursLater = new Date(now.getTime() + 2 * 60 * 60 * 1000);
const fourHoursLater = new Date(now.getTime() + 4 * 60 * 60 * 1000);
// Active trips (next 2 hours)
const activeTrips = events
.filter((event) => {
const start = new Date(event.startTime);
return start > now && start <= twoHoursLater && event.type === 'TRANSPORT';
})
.sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
// En route trips (already started, not completed)
const enRouteTrips = events.filter(
(event) =>
event.status === 'IN_PROGRESS' && event.type === 'TRANSPORT'
);
// Upcoming arrivals (next 4 hours)
const upcomingArrivals = vips
.filter((vip) => {
if (vip.expectedArrival) {
const arrival = new Date(vip.expectedArrival);
return arrival > now && arrival <= fourHoursLater;
}
// Check flight arrivals
return vip.flights.some((flight) => {
if (flight.scheduledArrival) {
const arrival = new Date(flight.scheduledArrival);
return arrival > now && arrival <= fourHoursLater;
}
return false;
});
})
.sort((a, b) => {
const aTime = a.expectedArrival || a.flights[0]?.scheduledArrival || '';
const bTime = b.expectedArrival || b.flights[0]?.scheduledArrival || '';
return new Date(aTime).getTime() - new Date(bTime).getTime();
});
// Vehicle status
const availableVehicles = vehicles.filter((v) => v.status === 'AVAILABLE');
const inUseVehicles = vehicles.filter((v) => v.status === 'IN_USE');
// Get time until event
const getTimeUntil = (dateStr: string) => {
const eventTime = new Date(dateStr);
const diff = eventTime.getTime() - now.getTime();
const minutes = Math.floor(diff / 60000);
if (minutes < 0) return 'NOW';
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
const remainingMin = minutes % 60;
return `${hours}h ${remainingMin}m`;
};
const getStatusColor = (status: string) => {
switch (status) {
case 'SCHEDULED':
return 'bg-blue-100 text-blue-800';
case 'IN_PROGRESS':
return 'bg-green-100 text-green-800';
case 'COMPLETED':
return 'bg-gray-100 text-gray-800';
case 'CANCELLED':
return 'bg-red-100 text-red-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
return (
<div className="space-y-6">
<div className="flex justify-between items-center">
<h1 className="text-3xl font-bold text-gray-900">Command Center</h1>
<div className="flex items-center gap-2 text-sm text-gray-500">
<Radio className="h-4 w-4 animate-pulse text-green-500" />
Auto-refreshing every 30s
</div>
</div>
{/* Resource Status Summary */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="bg-white p-4 rounded-lg shadow border-l-4 border-green-500">
<div className="flex justify-between items-center">
<div>
<p className="text-sm text-gray-600">Vehicles Available</p>
<p className="text-2xl font-bold text-green-600">
{availableVehicles.length}/{vehicles.length}
</p>
</div>
<Car className="h-8 w-8 text-green-500" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow border-l-4 border-blue-500">
<div className="flex justify-between items-center">
<div>
<p className="text-sm text-gray-600">Vehicles In Use</p>
<p className="text-2xl font-bold text-blue-600">{inUseVehicles.length}</p>
</div>
<Car className="h-8 w-8 text-blue-500" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow border-l-4 border-yellow-500">
<div className="flex justify-between items-center">
<div>
<p className="text-sm text-gray-600">Upcoming Trips</p>
<p className="text-2xl font-bold text-yellow-600">{activeTrips.length}</p>
</div>
<Clock className="h-8 w-8 text-yellow-500" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow border-l-4 border-purple-500">
<div className="flex justify-between items-center">
<div>
<p className="text-sm text-gray-600">VIP Arrivals</p>
<p className="text-2xl font-bold text-purple-600">{upcomingArrivals.length}</p>
</div>
<Plane className="h-8 w-8 text-purple-500" />
</div>
</div>
</div>
{/* En Route Trips */}
{enRouteTrips.length > 0 && (
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="bg-green-600 px-6 py-3 flex items-center">
<Car className="h-5 w-5 text-white mr-2" />
<h2 className="text-lg font-semibold text-white">
En Route Now ({enRouteTrips.length})
</h2>
</div>
<div className="divide-y divide-gray-200">
{enRouteTrips.map((trip) => (
<div key={trip.id} className="p-6 hover:bg-gray-50">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
<span className={`px-2 py-1 rounded text-xs font-medium ${getStatusColor(trip.status)}`}>
{trip.status}
</span>
<span className="text-sm font-medium text-gray-900">
{trip.vip.name}
</span>
</div>
<div className="flex items-center gap-4 text-sm text-gray-600">
<div className="flex items-center gap-1">
<MapPin className="h-4 w-4" />
{trip.pickupLocation} {trip.dropoffLocation}
</div>
{trip.driver && (
<div className="flex items-center gap-1">
<Users className="h-4 w-4" />
Driver: {trip.driver.name}
</div>
)}
{trip.vehicle && (
<div className="flex items-center gap-1">
<Car className="h-4 w-4" />
{trip.vehicle.name}
</div>
)}
</div>
</div>
<div className="text-right">
<p className="text-sm text-gray-500">
Started {new Date(trip.actualStartTime || trip.startTime).toLocaleTimeString()}
</p>
<p className="text-xs text-gray-400">
ETA: {new Date(trip.endTime).toLocaleTimeString()}
</p>
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Active Trips - Next 2 Hours */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="bg-blue-600 px-6 py-3 flex items-center">
<Clock className="h-5 w-5 text-white mr-2" />
<h2 className="text-lg font-semibold text-white">
Upcoming Trips - Next 2 Hours ({activeTrips.length})
</h2>
</div>
{activeTrips.length === 0 ? (
<div className="p-6 text-center text-gray-500">
<CheckCircle className="h-12 w-12 mx-auto mb-2 text-gray-400" />
<p>No scheduled trips in the next 2 hours</p>
</div>
) : (
<div className="divide-y divide-gray-200">
{activeTrips.map((trip) => {
const timeUntil = getTimeUntil(trip.startTime);
const isUrgent = new Date(trip.startTime).getTime() - now.getTime() < 15 * 60 * 1000;
return (
<div
key={trip.id}
className={`p-6 hover:bg-gray-50 ${isUrgent ? 'bg-yellow-50' : ''}`}
>
<div className="flex items-start justify-between">
<div className="flex-1">
{isUrgent && (
<div className="flex items-center gap-1 mb-2">
<AlertTriangle className="h-4 w-4 text-yellow-600" />
<span className="text-xs font-medium text-yellow-600">URGENT</span>
</div>
)}
<div className="flex items-center gap-2 mb-2">
<span className={`px-2 py-1 rounded text-xs font-medium ${getStatusColor(trip.status)}`}>
{trip.status}
</span>
<span className="text-sm font-medium text-gray-900">
{trip.vip.name}
</span>
</div>
<div className="flex items-center gap-4 text-sm text-gray-600">
<div className="flex items-center gap-1">
<MapPin className="h-4 w-4" />
{trip.pickupLocation || trip.location} {trip.dropoffLocation || 'Destination'}
</div>
{trip.driver && (
<div className="flex items-center gap-1">
<Users className="h-4 w-4" />
Driver: {trip.driver.name}
</div>
)}
{trip.vehicle && (
<div className="flex items-center gap-1">
<Car className="h-4 w-4" />
{trip.vehicle.name} ({trip.vehicle.seatCapacity} seats)
</div>
)}
{!trip.driver && (
<span className="text-red-600 font-medium"> NO DRIVER ASSIGNED</span>
)}
{!trip.vehicle && (
<span className="text-red-600 font-medium"> NO VEHICLE ASSIGNED</span>
)}
</div>
</div>
<div className="text-right">
<p className="text-lg font-bold text-blue-600">
in {timeUntil}
</p>
<p className="text-sm text-gray-500">
Departs: {new Date(trip.startTime).toLocaleTimeString()}
</p>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Upcoming VIP Arrivals */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="bg-purple-600 px-6 py-3 flex items-center">
<Plane className="h-5 w-5 text-white mr-2" />
<h2 className="text-lg font-semibold text-white">
Incoming VIPs - Next 4 Hours ({upcomingArrivals.length})
</h2>
</div>
{upcomingArrivals.length === 0 ? (
<div className="p-6 text-center text-gray-500">
<CheckCircle className="h-12 w-12 mx-auto mb-2 text-gray-400" />
<p>No VIP arrivals in the next 4 hours</p>
</div>
) : (
<div className="divide-y divide-gray-200">
{upcomingArrivals.map((vip) => {
const arrival = vip.expectedArrival || vip.flights[0]?.scheduledArrival;
const flight = vip.flights[0];
return (
<div key={vip.id} className="p-6 hover:bg-gray-50">
<div className="flex items-start justify-between">
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
{vip.arrivalMode === 'FLIGHT' ? (
<Plane className="h-4 w-4 text-purple-600" />
) : (
<Car className="h-4 w-4 text-gray-600" />
)}
<span className="text-sm font-medium text-gray-900">{vip.name}</span>
{vip.organization && (
<span className="text-xs text-gray-500">({vip.organization})</span>
)}
</div>
{flight && (
<div className="text-sm text-gray-600 mb-1">
Flight {flight.flightNumber} {flight.arrivalAirport}
{flight.status && (
<span className="ml-2 text-xs">
Status: {flight.status}
</span>
)}
</div>
)}
<div className="text-sm text-gray-600">
Mode: {vip.arrivalMode.replace('_', ' ')}
</div>
</div>
<div className="text-right">
<p className="text-lg font-bold text-purple-600">
in {getTimeUntil(arrival!)}
</p>
<p className="text-sm text-gray-500">
{new Date(arrival!).toLocaleTimeString()}
</p>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
{/* Available Resources */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Available Vehicles */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="bg-gray-700 px-6 py-3 flex items-center">
<Car className="h-5 w-5 text-white mr-2" />
<h2 className="text-lg font-semibold text-white">
Available Vehicles ({availableVehicles.length})
</h2>
</div>
{availableVehicles.length === 0 ? (
<div className="p-6 text-center text-gray-500">
<AlertTriangle className="h-12 w-12 mx-auto mb-2 text-yellow-500" />
<p>No vehicles currently available</p>
</div>
) : (
<ul className="divide-y divide-gray-200">
{availableVehicles.map((vehicle) => (
<li key={vehicle.id} className="px-6 py-3">
<div className="flex justify-between items-center">
<div>
<p className="text-sm font-medium text-gray-900">{vehicle.name}</p>
<p className="text-xs text-gray-500">
{vehicle.type.replace('_', ' ')} - {vehicle.seatCapacity} seats
</p>
</div>
<CheckCircle className="h-5 w-5 text-green-500" />
</div>
</li>
))}
</ul>
)}
</div>
{/* In-Use Vehicles */}
<div className="bg-white rounded-lg shadow overflow-hidden">
<div className="bg-gray-700 px-6 py-3 flex items-center">
<Car className="h-5 w-5 text-white mr-2" />
<h2 className="text-lg font-semibold text-white">
In-Use Vehicles ({inUseVehicles.length})
</h2>
</div>
{inUseVehicles.length === 0 ? (
<div className="p-6 text-center text-gray-500">
<CheckCircle className="h-12 w-12 mx-auto mb-2 text-gray-400" />
<p>No vehicles currently in use</p>
</div>
) : (
<ul className="divide-y divide-gray-200">
{inUseVehicles.map((vehicle) => (
<li key={vehicle.id} className="px-6 py-3">
<div className="flex justify-between items-center">
<div>
<p className="text-sm font-medium text-gray-900">{vehicle.name}</p>
<p className="text-xs text-gray-500">
{vehicle.type.replace('_', ' ')} - {vehicle.seatCapacity} seats
{vehicle.currentDriver && ` - ${vehicle.currentDriver.name}`}
</p>
</div>
<div className="h-2 w-2 rounded-full bg-blue-500 animate-pulse" />
</div>
</li>
))}
</ul>
)}
</div>
</div>
</div>
);
}

View File

@@ -1,378 +1,334 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { apiCall } from '../config/api';
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { useAuth } from '@/contexts/AuthContext';
import { Users, Car, Calendar, Plane, UserCheck, Clock } from 'lucide-react';
import { VIP, Driver, ScheduleEvent } from '@/types';
import { formatDateTime } from '@/lib/utils';
interface ScheduleEvent {
interface User {
id: string;
title: string;
location: string;
startTime: string;
endTime: string;
status: 'scheduled' | 'in-progress' | 'completed' | 'cancelled';
type: 'transport' | 'meeting' | 'event' | 'meal' | 'accommodation';
email: string;
name: string | null;
role: string;
isApproved: boolean;
createdAt: string;
}
interface Vip {
interface Flight {
id: string;
name: string;
organization: string;
transportMode: 'flight' | 'self-driving';
flightNumber?: string;
flights?: Array<{
flightNumber: string;
flightDate: string;
segment: number;
}>;
expectedArrival?: string;
arrivalTime?: string;
needsAirportPickup?: boolean;
needsVenueTransport: boolean;
notes?: string;
currentEvent?: ScheduleEvent;
nextEvent?: ScheduleEvent;
nextEventTime?: string;
vipId: string;
vip?: {
name: string;
organization: string | null;
};
flightNumber: string;
flightDate: string;
segment: number;
departureAirport: string;
arrivalAirport: string;
scheduledDeparture: string | null;
scheduledArrival: string | null;
actualDeparture: string | null;
actualArrival: string | null;
status: string | null;
}
interface Driver {
id: string;
name: string;
phone: string;
currentLocation: { lat: number; lng: number };
assignedVipIds: string[];
}
export function Dashboard() {
const { backendUser } = useAuth();
const isAdmin = backendUser?.role === 'ADMINISTRATOR';
const Dashboard: React.FC = () => {
const [vips, setVips] = useState<Vip[]>([]);
const [drivers, setDrivers] = useState<Driver[]>([]);
const [loading, setLoading] = useState(true);
const { data: vips } = useQuery<VIP[]>({
queryKey: ['vips'],
queryFn: async () => {
const { data } = await api.get('/vips');
return data;
},
});
// Helper functions for event management
const getCurrentEvent = (events: ScheduleEvent[]) => {
const now = new Date();
return events.find(event =>
new Date(event.startTime) <= now &&
new Date(event.endTime) > now &&
event.status === 'in-progress'
) || null;
};
const { data: drivers } = useQuery<Driver[]>({
queryKey: ['drivers'],
queryFn: async () => {
const { data } = await api.get('/drivers');
return data;
},
});
const getNextEvent = (events: ScheduleEvent[]) => {
const now = new Date();
const upcomingEvents = events.filter(event =>
new Date(event.startTime) > now && event.status === 'scheduled'
).sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
return upcomingEvents.length > 0 ? upcomingEvents[0] : null;
};
const { data: events } = useQuery<ScheduleEvent[]>({
queryKey: ['events'],
queryFn: async () => {
const { data } = await api.get('/events');
return data;
},
});
const formatTime = (timeString: string) => {
return new Date(timeString).toLocaleString([], {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
const { data: users } = useQuery<User[]>({
queryKey: ['users'],
queryFn: async () => {
const { data } = await api.get('/users');
return data;
},
enabled: isAdmin,
});
useEffect(() => {
const fetchData = async () => {
try {
const token = localStorage.getItem('authToken');
const authHeaders = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const [vipsResponse, driversResponse] = await Promise.all([
apiCall('/api/vips', { headers: authHeaders }),
apiCall('/api/drivers', { headers: authHeaders })
]);
if (!vipsResponse.ok || !driversResponse.ok) {
throw new Error('Failed to fetch data');
}
const vipsData = await vipsResponse.json();
const driversData = await driversResponse.json();
// Fetch schedule for each VIP and determine current/next events
const vipsWithSchedules = await Promise.all(
vipsData.map(async (vip: Vip) => {
try {
const scheduleResponse = await apiCall(`/api/vips/${vip.id}/schedule`, {
headers: authHeaders
});
if (scheduleResponse.ok) {
const scheduleData = await scheduleResponse.json();
const currentEvent = getCurrentEvent(scheduleData);
const nextEvent = getNextEvent(scheduleData);
return {
...vip,
currentEvent,
nextEvent,
nextEventTime: nextEvent ? nextEvent.startTime : null
};
} else {
return { ...vip, currentEvent: null, nextEvent: null, nextEventTime: null };
}
} catch (error) {
console.error(`Error fetching schedule for VIP ${vip.id}:`, error);
return { ...vip, currentEvent: null, nextEvent: null, nextEventTime: null };
}
})
);
// Sort VIPs by next event time (soonest first), then by name
const sortedVips = vipsWithSchedules.sort((a, b) => {
// VIPs with current events first
if (a.currentEvent && !b.currentEvent) return -1;
if (!a.currentEvent && b.currentEvent) return 1;
// Then by next event time (soonest first)
if (a.nextEventTime && b.nextEventTime) {
return new Date(a.nextEventTime).getTime() - new Date(b.nextEventTime).getTime();
}
if (a.nextEventTime && !b.nextEventTime) return -1;
if (!a.nextEventTime && b.nextEventTime) return 1;
// Finally by name if no events
return a.name.localeCompare(b.name);
});
setVips(sortedVips);
setDrivers(driversData);
} catch (error) {
console.error('Error fetching data:', error);
} finally {
setLoading(false);
}
};
const { data: flights } = useQuery<Flight[]>({
queryKey: ['flights'],
queryFn: async () => {
const { data } = await api.get('/flights');
return data;
},
});
fetchData();
}, []);
const today = new Date();
today.setHours(0, 0, 0, 0);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
if (loading) {
return (
<div className="flex justify-center items-center min-h-64">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4">
<div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
<span className="text-lg font-medium text-slate-700">Loading dashboard...</span>
</div>
</div>
);
}
const eventsToday = events?.filter((e) => {
const eventDate = new Date(e.startTime);
return eventDate >= today && eventDate < tomorrow && e.status !== 'CANCELLED';
}).length || 0;
const flightsToday = flights?.filter((f) => {
const flightDate = new Date(f.flightDate);
return flightDate >= today && flightDate < tomorrow;
}).length || 0;
const pendingApprovals = users?.filter((u) => !u.isApproved).length || 0;
const upcomingEvents = events
?.filter((e) => e.status === 'SCHEDULED' && new Date(e.startTime) >= today)
.sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime())
.slice(0, 5) || [];
const upcomingFlights = flights
?.filter((f) => {
const flightDate = new Date(f.flightDate);
return flightDate >= today && f.status !== 'cancelled';
})
.sort((a, b) => new Date(a.flightDate).getTime() - new Date(b.flightDate).getTime())
.slice(0, 5) || [];
const stats = [
{
name: 'Total VIPs',
value: vips?.length || 0,
icon: Users,
color: 'bg-blue-500',
},
{
name: 'Active Drivers',
value: drivers?.length || 0,
icon: Car,
color: 'bg-green-500',
},
{
name: 'Events Today',
value: eventsToday,
icon: Clock,
color: 'bg-purple-500',
},
{
name: 'Flights Today',
value: flightsToday,
icon: Plane,
color: 'bg-indigo-500',
},
...(isAdmin ? [{
name: 'Pending Approvals',
value: pendingApprovals,
icon: UserCheck,
color: 'bg-yellow-500',
}] : []),
];
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex items-center justify-between">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
VIP Coordinator Dashboard
</h1>
<p className="text-slate-600 mt-2">Real-time overview of VIP activities and coordination</p>
</div>
<div className="flex items-center space-x-4">
<div className="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
{vips.length} Active VIPs
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-8">Dashboard</h1>
{/* Stats Grid */}
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-8">
{stats.map((stat) => {
const Icon = stat.icon;
return (
<div
key={stat.name}
className="bg-white overflow-hidden shadow rounded-lg"
>
<div className="p-5">
<div className="flex items-center">
<div className={`flex-shrink-0 ${stat.color} rounded-md p-3`}>
<Icon className="h-6 w-6 text-white" />
</div>
<div className="ml-5 w-0 flex-1">
<dl>
<dt className="text-sm font-medium text-gray-500 truncate">
{stat.name}
</dt>
<dd className="text-3xl font-semibold text-gray-900">
{stat.value}
</dd>
</dl>
</div>
</div>
</div>
</div>
<div className="bg-gradient-to-r from-green-500 to-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
{drivers.length} Drivers
</div>
</div>
</div>
);
})}
</div>
<div className="grid grid-cols-1 xl:grid-cols-3 gap-8">
{/* VIP Status Dashboard */}
<div className="xl:col-span-2">
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-6 py-4 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center">
VIP Status Dashboard
<span className="ml-2 bg-blue-100 text-blue-800 text-sm font-medium px-2.5 py-0.5 rounded-full">
{vips.length} VIPs
</span>
</h2>
</div>
<div className="p-6">
{vips.length === 0 ? (
<div className="text-center py-12">
<div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
<div className="w-8 h-8 bg-slate-300 rounded-full"></div>
</div>
<p className="text-slate-500 font-medium">No VIPs currently scheduled</p>
</div>
) : (
<div className="space-y-4">
{vips.map((vip) => {
const hasCurrentEvent = !!vip.currentEvent;
const hasNextEvent = !!vip.nextEvent;
return (
<div key={vip.id} className={`
relative rounded-xl border-2 p-6 transition-all duration-200 hover:shadow-lg
${hasCurrentEvent
? 'border-amber-300 bg-gradient-to-r from-amber-50 to-orange-50'
: hasNextEvent
? 'border-blue-300 bg-gradient-to-r from-blue-50 to-indigo-50'
: 'border-slate-200 bg-slate-50'
}
`}>
<div className="flex justify-between items-start">
<div className="flex-1">
<div className="flex items-center gap-3 mb-3">
<h3 className="text-lg font-bold text-slate-900">{vip.name}</h3>
{hasCurrentEvent && (
<span className="bg-gradient-to-r from-amber-500 to-orange-500 text-white px-3 py-1 rounded-full text-xs font-bold animate-pulse">
ACTIVE
</span>
)}
</div>
<p className="text-slate-600 text-sm mb-4">{vip.organization}</p>
{/* Current Event */}
{vip.currentEvent && (
<div className="bg-white border border-amber-200 rounded-lg p-4 mb-3 shadow-sm">
<div className="flex items-center gap-2 mb-2">
<span className="text-amber-600 font-bold text-sm">CURRENT EVENT</span>
</div>
<div className="flex items-center gap-2 mb-1">
<span className="font-semibold text-slate-900">{vip.currentEvent.title}</span>
</div>
<p className="text-slate-600 text-sm mb-1">Location: {vip.currentEvent.location}</p>
<p className="text-slate-500 text-xs">Until {formatTime(vip.currentEvent.endTime)}</p>
</div>
)}
{/* Next Event */}
{vip.nextEvent && (
<div className="bg-white border border-blue-200 rounded-lg p-4 mb-3 shadow-sm">
<div className="flex items-center gap-2 mb-2">
<span className="text-blue-600 font-bold text-sm">NEXT EVENT</span>
</div>
<div className="flex items-center gap-2 mb-1">
<span className="font-semibold text-slate-900">{vip.nextEvent.title}</span>
</div>
<p className="text-slate-600 text-sm mb-1">Location: {vip.nextEvent.location}</p>
<p className="text-slate-500 text-xs">{formatTime(vip.nextEvent.startTime)} - {formatTime(vip.nextEvent.endTime)}</p>
</div>
)}
{/* No Events */}
{!vip.currentEvent && !vip.nextEvent && (
<div className="bg-white border border-slate-200 rounded-lg p-4 mb-3">
<p className="text-slate-500 text-sm italic">No scheduled events</p>
</div>
)}
{/* Transport Info */}
<div className="flex items-center gap-2 text-xs text-slate-500 bg-white/50 rounded-lg px-3 py-2">
{vip.transportMode === 'flight' ? (
<span>Flight: {vip.flights && vip.flights.length > 0 ?
vip.flights.map(f => f.flightNumber).join(' → ') :
vip.flightNumber || 'TBD'}
</span>
) : (
<span>Self-driving | Expected: {vip.expectedArrival ? formatTime(vip.expectedArrival) : 'TBD'}</span>
)}
</div>
</div>
<div className="flex flex-col gap-2 ml-6">
<Link
to={`/vips/${vip.id}`}
className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
>
Details
</Link>
<Link
to={`/vips/${vip.id}#schedule`}
className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
>
Schedule
</Link>
</div>
</div>
</div>
);
})}
</div>
)}
</div>
</div>
</div>
{/* Sidebar */}
<div className="space-y-6">
{/* Drivers Card */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-green-50 to-emerald-50 px-6 py-4 border-b border-slate-200/60">
<h2 className="text-lg font-bold text-slate-800 flex items-center">
Available Drivers
<span className="ml-2 bg-green-100 text-green-800 text-sm font-medium px-2.5 py-0.5 rounded-full">
{drivers.length}
</span>
</h2>
</div>
<div className="p-6">
{drivers.length === 0 ? (
<div className="text-center py-8">
<div className="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3">
<div className="w-6 h-6 bg-slate-300 rounded-full"></div>
</div>
<p className="text-slate-500 text-sm">No drivers available</p>
</div>
) : (
<div className="space-y-3">
{drivers.map((driver) => (
<div key={driver.id} className="bg-slate-50 rounded-lg p-4 border border-slate-200">
<div className="flex items-center justify-between">
<div>
<h4 className="font-semibold text-slate-900">{driver.name}</h4>
<p className="text-slate-600 text-sm">{driver.phone}</p>
</div>
<div className="text-right">
<span className="bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">
{driver.assignedVipIds.length} VIPs
</span>
</div>
</div>
</div>
))}
</div>
)}
</div>
{/* Recent VIPs */}
<div className="bg-white shadow rounded-lg p-6 mb-8">
<h2 className="text-lg font-medium text-gray-900 mb-4">Recent VIPs</h2>
{vips && vips.length > 0 ? (
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead>
<tr>
<th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Organization
</th>
<th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Arrival Mode
</th>
<th className="px-6 py-3 bg-gray-50 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Events
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{vips.slice(0, 5).map((vip) => (
<tr key={vip.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{vip.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.organization || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.arrivalMode}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.events?.length || 0}
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="text-sm text-gray-500 text-center py-4">
No VIPs yet. Add your first VIP to get started.
</p>
)}
</div>
{/* Quick Actions Card */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-purple-50 to-pink-50 px-6 py-4 border-b border-slate-200/60">
<h2 className="text-lg font-bold text-slate-800">Quick Actions</h2>
</div>
<div className="p-6 space-y-3">
<Link
to="/vips"
className="block w-full bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-4 py-3 rounded-lg font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
{/* Upcoming Flights */}
<div className="bg-white shadow rounded-lg p-6 mb-8">
<h2 className="text-lg font-medium text-gray-900 mb-4">
Upcoming Flights
</h2>
{upcomingFlights.length > 0 ? (
<div className="space-y-4">
{upcomingFlights.map((flight) => (
<div
key={flight.id}
className="border-l-4 border-indigo-500 pl-4 py-2"
>
Manage VIPs
</Link>
<Link
to="/drivers"
className="block w-full bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-3 rounded-lg font-medium transition-all duration-200 text-center shadow-lg hover:shadow-xl"
>
Manage Drivers
</Link>
</div>
<div className="flex justify-between items-start">
<div>
<h3 className="text-sm font-medium text-gray-900 flex items-center gap-2">
<Plane className="h-4 w-4" />
{flight.flightNumber}
</h3>
<p className="text-sm text-gray-500">
{flight.vip?.name} {flight.departureAirport} {flight.arrivalAirport}
</p>
{flight.scheduledDeparture && (
<p className="text-xs text-gray-400 mt-1">
Departs: {formatDateTime(flight.scheduledDeparture)}
</p>
)}
</div>
<div className="text-right">
<span className="text-xs text-gray-500 block">
{new Date(flight.flightDate).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
year: 'numeric',
})}
</span>
<span className={`inline-block mt-1 px-2 py-1 text-xs rounded-full ${
flight.status?.toLowerCase() === 'scheduled' ? 'bg-blue-100 text-blue-800' :
flight.status?.toLowerCase() === 'boarding' ? 'bg-yellow-100 text-yellow-800' :
flight.status?.toLowerCase() === 'departed' ? 'bg-purple-100 text-purple-800' :
flight.status?.toLowerCase() === 'landed' ? 'bg-green-100 text-green-800' :
flight.status?.toLowerCase() === 'delayed' ? 'bg-orange-100 text-orange-800' :
'bg-gray-100 text-gray-800'
}`}>
{flight.status || 'Unknown'}
</span>
</div>
</div>
</div>
))}
</div>
</div>
) : (
<p className="text-sm text-gray-500 text-center py-4">
No upcoming flights tracked.
</p>
)}
</div>
{/* Upcoming Events */}
<div className="bg-white shadow rounded-lg p-6">
<h2 className="text-lg font-medium text-gray-900 mb-4">
Upcoming Events
</h2>
{upcomingEvents.length > 0 ? (
<div className="space-y-4">
{upcomingEvents.map((event) => (
<div
key={event.id}
className="border-l-4 border-primary pl-4 py-2"
>
<div className="flex justify-between items-start">
<div>
<h3 className="text-sm font-medium text-gray-900">
{event.title}
</h3>
<p className="text-sm text-gray-500">
{event.vip?.name} {event.driver?.name || 'No driver assigned'}
</p>
{event.location && (
<p className="text-xs text-gray-400 mt-1">{event.location}</p>
)}
</div>
<div className="text-right">
<span className="text-xs text-gray-500 block">
{formatDateTime(event.startTime)}
</span>
<span className={`inline-block mt-1 px-2 py-1 text-xs rounded-full ${
event.type === 'TRANSPORT' ? 'bg-blue-100 text-blue-800' :
event.type === 'MEETING' ? 'bg-purple-100 text-purple-800' :
event.type === 'MEAL' ? 'bg-green-100 text-green-800' :
'bg-gray-100 text-gray-800'
}`}>
{event.type}
</span>
</div>
</div>
</div>
))}
</div>
) : (
<p className="text-sm text-gray-500 text-center py-4">
No upcoming events scheduled.
</p>
)}
</div>
</div>
);
};
export default Dashboard;
}

View File

@@ -1,756 +0,0 @@
import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { apiCall } from '../config/api';
import GanttChart from '../components/GanttChart';
interface DriverScheduleEvent {
id: string;
title: string;
location: string;
startTime: string;
endTime: string;
description?: string;
status: 'scheduled' | 'in-progress' | 'completed' | 'cancelled';
type: 'transport' | 'meeting' | 'event' | 'meal' | 'accommodation';
vipId: string;
vipName: string;
}
interface Driver {
id: string;
name: string;
phone: string;
}
interface DriverScheduleData {
driver: Driver;
schedule: DriverScheduleEvent[];
}
const DriverDashboard: React.FC = () => {
const { driverId } = useParams<{ driverId: string }>();
const [scheduleData, setScheduleData] = useState<DriverScheduleData | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (driverId) {
fetchDriverSchedule();
}
}, [driverId]);
const fetchDriverSchedule = async () => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/drivers/${driverId}/schedule`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
setScheduleData(data);
} else {
setError('Driver not found');
}
} catch (err) {
setError('Error loading driver schedule');
} finally {
setLoading(false);
}
};
const getStatusColor = (status: string) => {
switch (status) {
case 'scheduled': return '#3498db';
case 'in-progress': return '#f39c12';
case 'completed': return '#2ecc71';
case 'cancelled': return '#e74c3c';
default: return '#95a5a6';
}
};
const getTypeIcon = (type: string) => {
switch (type) {
case 'transport': return '🚗';
case 'meeting': return '🤝';
case 'event': return '🎉';
case 'meal': return '🍽️';
case 'accommodation': return '🏨';
default: return '📅';
}
};
const formatTime = (timeString: string) => {
return new Date(timeString).toLocaleString([], {
hour: '2-digit',
minute: '2-digit'
});
};
const getNextEvent = () => {
if (!scheduleData?.schedule) return null;
const now = new Date();
const upcomingEvents = scheduleData.schedule.filter(event =>
new Date(event.startTime) > now && event.status === 'scheduled'
).sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
return upcomingEvents.length > 0 ? upcomingEvents[0] : null;
};
const getCurrentEvent = () => {
if (!scheduleData?.schedule) return null;
const now = new Date();
return scheduleData.schedule.find(event =>
new Date(event.startTime) <= now &&
new Date(event.endTime) > now &&
event.status === 'in-progress'
) || null;
};
const groupEventsByDay = (events: DriverScheduleEvent[]) => {
const grouped: { [key: string]: DriverScheduleEvent[] } = {};
events.forEach(event => {
const date = new Date(event.startTime).toDateString();
if (!grouped[date]) {
grouped[date] = [];
}
grouped[date].push(event);
});
// Sort events within each day by start time
Object.keys(grouped).forEach(date => {
grouped[date].sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
});
return grouped;
};
const handlePrintSchedule = () => {
if (!scheduleData) return;
const printWindow = window.open('', '_blank');
if (!printWindow) return;
const groupedSchedule = groupEventsByDay(scheduleData.schedule);
const printContent = `
<!DOCTYPE html>
<html>
<head>
<title>Driver Schedule - ${scheduleData.driver.name}</title>
<meta charset="UTF-8">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #2d3748;
background: #ffffff;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 40px 30px;
}
.header {
text-align: center;
margin-bottom: 40px;
padding-bottom: 30px;
border-bottom: 3px solid #e2e8f0;
background: linear-gradient(135deg, #e53e3e 0%, #c53030 100%);
color: white;
padding: 40px 30px;
border-radius: 15px;
margin: -40px -30px 40px -30px;
}
.header h1 {
font-size: 2.5rem;
font-weight: 700;
margin-bottom: 10px;
text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.header h2 {
font-size: 1.8rem;
font-weight: 600;
margin-bottom: 20px;
opacity: 0.95;
}
.driver-info {
background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
padding: 25px;
border-radius: 12px;
margin-bottom: 30px;
border: 1px solid #e2e8f0;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.driver-info p {
margin-bottom: 8px;
font-size: 1rem;
}
.driver-info strong {
color: #4a5568;
font-weight: 600;
}
.day-section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.day-header {
background: linear-gradient(135deg, #e53e3e 0%, #c53030 100%);
color: white;
padding: 20px 25px;
font-size: 1.3rem;
font-weight: 700;
margin-bottom: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
text-align: center;
}
.event {
background: white;
border: 1px solid #e2e8f0;
margin-bottom: 15px;
padding: 25px;
border-radius: 12px;
display: flex;
align-items: flex-start;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.event-time {
min-width: 120px;
background: linear-gradient(135deg, #edf2f7 0%, #e2e8f0 100%);
padding: 15px;
border-radius: 8px;
text-align: center;
margin-right: 25px;
border: 1px solid #cbd5e0;
}
.event-time .time {
font-weight: 700;
font-size: 1rem;
color: #2d3748;
display: block;
}
.event-time .separator {
font-size: 0.8rem;
color: #718096;
margin: 5px 0;
}
.event-details {
flex: 1;
}
.event-title {
font-weight: 700;
font-size: 1.2rem;
margin-bottom: 10px;
color: #2d3748;
display: flex;
align-items: center;
gap: 8px;
}
.event-icon {
font-size: 1.3rem;
}
.event-location {
color: #4a5568;
margin-bottom: 8px;
font-weight: 500;
display: flex;
align-items: center;
gap: 6px;
}
.event-vip {
color: #e53e3e;
font-weight: 600;
margin-bottom: 8px;
display: flex;
align-items: center;
gap: 6px;
}
.event-description {
background: #f7fafc;
padding: 12px 15px;
border-radius: 8px;
font-style: italic;
color: #4a5568;
margin-bottom: 10px;
border-left: 4px solid #cbd5e0;
}
.footer {
margin-top: 50px;
text-align: center;
color: #718096;
font-size: 0.9rem;
padding-top: 20px;
border-top: 1px solid #e2e8f0;
}
.company-logo {
width: 60px;
height: 60px;
background: linear-gradient(135deg, #e53e3e 0%, #c53030 100%);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 20px;
color: white;
font-size: 1.5rem;
font-weight: bold;
}
@media print {
body {
margin: 0;
padding: 0;
}
.container {
padding: 20px;
}
.header {
margin: -20px -20px 30px -20px;
}
.day-section {
page-break-inside: avoid;
}
.event {
page-break-inside: avoid;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="company-logo">🚗</div>
<h1>Driver Schedule</h1>
<h2>${scheduleData.driver.name}</h2>
</div>
<div class="driver-info">
<p><strong>Driver:</strong> ${scheduleData.driver.name}</p>
<p><strong>Phone:</strong> ${scheduleData.driver.phone}</p>
<p><strong>Total Assignments:</strong> ${scheduleData.schedule.length}</p>
</div>
${Object.entries(groupedSchedule).map(([date, events]) => `
<div class="day-section">
<div class="day-header">
${new Date(date).toLocaleDateString([], {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
})}
</div>
${events.map(event => `
<div class="event">
<div class="event-time">
<span class="time">${formatTime(event.startTime)}</span>
<div class="separator">to</div>
<span class="time">${formatTime(event.endTime)}</span>
</div>
<div class="event-details">
<div class="event-title">
<span class="event-icon">${getTypeIcon(event.type)}</span>
${event.title}
</div>
<div class="event-vip">
<span>👤</span>
VIP: ${event.vipName}
</div>
<div class="event-location">
<span>📍</span>
${event.location}
</div>
${event.description ? `<div class="event-description">${event.description}</div>` : ''}
</div>
</div>
`).join('')}
</div>
`).join('')}
<div class="footer">
<p><strong>VIP Coordinator System</strong></p>
<p>Generated on ${new Date().toLocaleDateString([], {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}</p>
</div>
</div>
</body>
</html>
`;
printWindow.document.write(printContent);
printWindow.document.close();
printWindow.focus();
setTimeout(() => {
printWindow.print();
printWindow.close();
}, 250);
};
async function updateEventStatus(eventId: string, status: string) {
if (!scheduleData) return;
// Find the event to get the VIP ID
const event = scheduleData.schedule.find(e => e.id === eventId);
if (!event) return;
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${event.vipId}/schedule/${eventId}/status`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ status }),
});
if (response.ok) {
await fetchDriverSchedule(); // Refresh the schedule
}
} catch (error) {
console.error('Error updating event status:', error);
}
}
if (loading) {
return (
<div className="flex justify-center items-center min-h-64">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4">
<div className="w-8 h-8 border-4 border-red-600 border-t-transparent rounded-full animate-spin"></div>
<span className="text-lg font-medium text-slate-700">Loading driver schedule...</span>
</div>
</div>
);
}
if (error || !scheduleData) {
return (
<div className="space-y-8">
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60 text-center">
<div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
<span className="text-2xl"></span>
</div>
<h1 className="text-2xl font-bold text-slate-800 mb-2">Error</h1>
<p className="text-slate-600 mb-6">{error || 'Driver not found'}</p>
<Link
to="/drivers"
className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
>
Back to Drivers
</Link>
</div>
</div>
);
}
const nextEvent = getNextEvent();
const currentEvent = getCurrentEvent();
const groupedSchedule = groupEventsByDay(scheduleData.schedule);
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent flex items-center gap-3">
🚗 Driver Dashboard: {scheduleData.driver.name}
</h1>
<p className="text-slate-600 mt-2">Real-time schedule and assignment management</p>
</div>
<div className="flex items-center space-x-4">
<button
className="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={handlePrintSchedule}
>
🖨 Print Schedule
</button>
<Link
to="/drivers"
className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
>
Back to Drivers
</Link>
</div>
</div>
</div>
{/* Current Status */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-green-50 to-emerald-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
📍 Current Status
</h2>
<p className="text-slate-600 mt-1">Real-time driver activity and next assignment</p>
</div>
<div className="p-8 space-y-6">
{currentEvent ? (
<div className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-xl p-6">
<div className="flex items-center gap-3 mb-4">
<span className="text-2xl">{getTypeIcon(currentEvent.type)}</span>
<div>
<h3 className="text-lg font-bold text-amber-900">Currently Active</h3>
<p className="text-amber-700 font-semibold">{currentEvent.title}</p>
</div>
<span
className="ml-auto px-3 py-1 rounded-full text-xs font-bold text-white"
style={{ backgroundColor: getStatusColor(currentEvent.status) }}
>
{currentEvent.status.toUpperCase()}
</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm">
<div className="flex items-center gap-2 text-amber-800">
<span>📍</span>
<span>{currentEvent.location}</span>
</div>
<div className="flex items-center gap-2 text-amber-800">
<span>👤</span>
<span>VIP: {currentEvent.vipName}</span>
</div>
<div className="flex items-center gap-2 text-amber-800">
<span></span>
<span>Until {formatTime(currentEvent.endTime)}</span>
</div>
</div>
</div>
) : (
<div className="bg-gradient-to-r from-green-50 to-emerald-50 border border-green-200 rounded-xl p-6">
<div className="flex items-center gap-3">
<span className="text-2xl"></span>
<div>
<h3 className="text-lg font-bold text-green-900">Currently Available</h3>
<p className="text-green-700">Ready for next assignment</p>
</div>
</div>
</div>
)}
{nextEvent && (
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 border border-blue-200 rounded-xl p-6">
<div className="flex items-center gap-3 mb-4">
<span className="text-2xl">{getTypeIcon(nextEvent.type)}</span>
<div>
<h3 className="text-lg font-bold text-blue-900">Next Assignment</h3>
<p className="text-blue-700 font-semibold">{nextEvent.title}</p>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-sm mb-4">
<div className="flex items-center gap-2 text-blue-800">
<span>📍</span>
<span>{nextEvent.location}</span>
</div>
<div className="flex items-center gap-2 text-blue-800">
<span>👤</span>
<span>VIP: {nextEvent.vipName}</span>
</div>
<div className="flex items-center gap-2 text-blue-800">
<span></span>
<span>{formatTime(nextEvent.startTime)} - {formatTime(nextEvent.endTime)}</span>
</div>
</div>
<button
className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={() => window.open(`https://maps.google.com/?q=${encodeURIComponent(nextEvent.location)}`, '_blank')}
>
🗺 Get Directions
</button>
</div>
)}
</div>
</div>
{/* Full Schedule */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-purple-50 to-pink-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
📅 Complete Schedule
<span className="bg-purple-100 text-purple-800 text-sm font-medium px-2.5 py-0.5 rounded-full">
{scheduleData.schedule.length} assignments
</span>
</h2>
<p className="text-slate-600 mt-1">All scheduled events and assignments</p>
</div>
<div className="p-8">
{scheduleData.schedule.length === 0 ? (
<div className="text-center py-12">
<div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
<span className="text-2xl">📅</span>
</div>
<p className="text-slate-500 font-medium">No assignments scheduled</p>
</div>
) : (
<div className="space-y-8">
{Object.entries(groupedSchedule).map(([date, events]) => (
<div key={date} className="space-y-4">
<div className="bg-gradient-to-r from-slate-600 to-slate-700 text-white px-6 py-3 rounded-xl shadow-lg">
<h3 className="text-lg font-bold">
{new Date(date).toLocaleDateString([], {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
})}
</h3>
</div>
<div className="grid gap-4">
{events.map((event) => (
<div key={event.id} className="bg-gradient-to-r from-slate-50 to-slate-100 rounded-xl border border-slate-200/60 p-6 hover:shadow-lg transition-all duration-200">
<div className="flex items-start gap-6">
{/* Time Column */}
<div className="flex-shrink-0 text-center">
<div className="bg-white rounded-lg border border-slate-200 p-3 shadow-sm">
<div className="text-sm font-bold text-slate-900">
{formatTime(event.startTime)}
</div>
<div className="text-xs text-slate-500 mt-1">
to
</div>
<div className="text-sm font-bold text-slate-900">
{formatTime(event.endTime)}
</div>
</div>
</div>
{/* Event Content */}
<div className="flex-1">
<div className="flex items-center gap-3 mb-3">
<span className="text-2xl">{getTypeIcon(event.type)}</span>
<h4 className="text-lg font-bold text-slate-900">{event.title}</h4>
<span
className="px-3 py-1 rounded-full text-xs font-bold text-white shadow-sm"
style={{ backgroundColor: getStatusColor(event.status) }}
>
{event.status.toUpperCase()}
</span>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
<div className="flex items-center gap-2 text-slate-600">
<span>📍</span>
<span className="font-medium">{event.location}</span>
</div>
<div className="flex items-center gap-2 text-slate-600">
<span>👤</span>
<span className="font-medium">VIP: {event.vipName}</span>
</div>
</div>
{event.description && (
<div className="text-slate-600 mb-4 bg-white/50 rounded-lg p-3 border border-slate-200/50">
{event.description}
</div>
)}
<div className="flex items-center gap-3">
<button
className="bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={() => window.open(`https://maps.google.com/?q=${encodeURIComponent(event.location)}`, '_blank')}
>
🗺 Directions
</button>
{event.status === 'scheduled' && (
<button
className="bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={() => updateEventStatus(event.id, 'in-progress')}
>
Start
</button>
)}
{event.status === 'in-progress' && (
<button
className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={() => updateEventStatus(event.id, 'completed')}
>
Complete
</button>
)}
{event.status === 'completed' && (
<span className="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-medium flex items-center gap-1">
Completed
</span>
)}
</div>
</div>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
</div>
{/* Gantt Chart */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-indigo-50 to-purple-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
📊 Schedule Timeline
</h2>
<p className="text-slate-600 mt-1">Visual timeline of all assignments</p>
</div>
<div className="p-8">
<GanttChart
events={scheduleData.schedule}
driverName={scheduleData.driver.name}
/>
</div>
</div>
</div>
);
};
export default DriverDashboard;

View File

@@ -1,293 +1,191 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { apiCall } from '../config/api';
import DriverForm from '../components/DriverForm';
import EditDriverForm from '../components/EditDriverForm';
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { Driver } from '@/types';
import { Plus, Edit, Trash2 } from 'lucide-react';
import { DriverForm, DriverFormData } from '@/components/DriverForm';
import { Loading } from '@/components/Loading';
interface Driver {
id: string;
name: string;
phone: string;
currentLocation: { lat: number; lng: number };
assignedVipIds: string[];
vehicleCapacity?: number;
}
const DriverList: React.FC = () => {
const [drivers, setDrivers] = useState<Driver[]>([]);
const [loading, setLoading] = useState(true);
export function DriverList() {
const queryClient = useQueryClient();
const [showForm, setShowForm] = useState(false);
const [editingDriver, setEditingDriver] = useState<Driver | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
// Function to extract last name for sorting
const getLastName = (fullName: string) => {
const nameParts = fullName.trim().split(' ');
return nameParts[nameParts.length - 1].toLowerCase();
const { data: drivers, isLoading } = useQuery<Driver[]>({
queryKey: ['drivers'],
queryFn: async () => {
const { data } = await api.get('/drivers');
return data;
},
});
const createMutation = useMutation({
mutationFn: async (data: DriverFormData) => {
await api.post('/drivers', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['drivers'] });
setShowForm(false);
setIsSubmitting(false);
toast.success('Driver created successfully');
},
onError: (error: any) => {
console.error('[DRIVER] Failed to create:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to create driver');
},
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: DriverFormData }) => {
await api.patch(`/drivers/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['drivers'] });
setShowForm(false);
setEditingDriver(null);
setIsSubmitting(false);
toast.success('Driver updated successfully');
},
onError: (error: any) => {
console.error('[DRIVER] Failed to update:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to update driver');
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await api.delete(`/drivers/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['drivers'] });
toast.success('Driver deleted successfully');
},
onError: (error: any) => {
console.error('[DRIVER] Failed to delete:', error);
toast.error(error.response?.data?.message || 'Failed to delete driver');
},
});
const handleAdd = () => {
setEditingDriver(null);
setShowForm(true);
};
// Function to sort drivers by last name
const sortDriversByLastName = (driverList: Driver[]) => {
return [...driverList].sort((a, b) => {
const lastNameA = getLastName(a.name);
const lastNameB = getLastName(b.name);
return lastNameA.localeCompare(lastNameB);
});
const handleEdit = (driver: Driver) => {
setEditingDriver(driver);
setShowForm(true);
};
useEffect(() => {
const fetchDrivers = async () => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
const sortedDrivers = sortDriversByLastName(data);
setDrivers(sortedDrivers);
} else {
console.error('Failed to fetch drivers:', response.status);
}
} catch (error) {
console.error('Error fetching drivers:', error);
} finally {
setLoading(false);
}
};
fetchDrivers();
}, []);
const handleAddDriver = async (driverData: any) => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(driverData),
});
if (response.ok) {
const newDriver = await response.json();
setDrivers(prev => sortDriversByLastName([...prev, newDriver]));
setShowForm(false);
} else {
console.error('Failed to add driver:', response.status);
}
} catch (error) {
console.error('Error adding driver:', error);
const handleDelete = (id: string, name: string) => {
if (confirm(`Delete driver "${name}"? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleEditDriver = async (driverData: any) => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/drivers/${driverData.id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(driverData),
});
if (response.ok) {
const updatedDriver = await response.json();
setDrivers(prev => sortDriversByLastName(prev.map(driver =>
driver.id === updatedDriver.id ? updatedDriver : driver
)));
setEditingDriver(null);
} else {
console.error('Failed to update driver:', response.status);
}
} catch (error) {
console.error('Error updating driver:', error);
const handleSubmit = (data: DriverFormData) => {
setIsSubmitting(true);
if (editingDriver) {
updateMutation.mutate({ id: editingDriver.id, data });
} else {
createMutation.mutate(data);
}
};
const handleDeleteDriver = async (driverId: string) => {
if (!confirm('Are you sure you want to delete this driver?')) {
return;
}
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/drivers/${driverId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
setDrivers(prev => prev.filter(driver => driver.id !== driverId));
} else {
console.error('Failed to delete driver:', response.status);
}
} catch (error) {
console.error('Error deleting driver:', error);
}
const handleCancel = () => {
setShowForm(false);
setEditingDriver(null);
setIsSubmitting(false);
};
if (loading) {
return (
<div className="flex justify-center items-center min-h-64">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4">
<div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
<span className="text-lg font-medium text-slate-700">Loading drivers...</span>
</div>
</div>
);
if (isLoading) {
return <Loading message="Loading drivers..." />;
}
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
Driver Management
</h1>
<p className="text-slate-600 mt-2">Manage driver profiles and assignments</p>
</div>
<div className="flex items-center space-x-4">
<div className="bg-gradient-to-r from-green-500 to-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium">
{drivers.length} Active Drivers
</div>
<button
className="btn btn-primary"
onClick={() => setShowForm(true)}
>
Add New Driver
</button>
</div>
</div>
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-900">Drivers</h1>
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90"
>
<Plus className="h-4 w-4 mr-2" />
Add Driver
</button>
</div>
{/* Driver Grid */}
{drivers.length === 0 ? (
<div className="bg-white rounded-2xl shadow-lg p-12 border border-slate-200/60 text-center">
<div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
<div className="w-8 h-8 bg-slate-300 rounded-full"></div>
</div>
<h3 className="text-lg font-semibold text-slate-800 mb-2">No Drivers Found</h3>
<p className="text-slate-600 mb-6">Get started by adding your first driver</p>
<button
className="btn btn-primary"
onClick={() => setShowForm(true)}
>
Add New Driver
</button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{drivers.map((driver) => (
<div key={driver.id} className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden hover:shadow-xl transition-shadow duration-200">
<div className="p-6">
{/* Driver Header */}
<div className="flex items-center justify-between mb-4">
<h3 className="text-xl font-bold text-slate-900">{driver.name}</h3>
<div className="w-10 h-10 bg-gradient-to-br from-green-400 to-green-600 rounded-full flex items-center justify-center">
<span className="text-white text-sm font-bold">
{driver.name.charAt(0).toUpperCase()}
</span>
</div>
</div>
{/* Driver Information */}
<div className="space-y-3 mb-6">
<div className="bg-slate-50 rounded-lg p-3">
<div className="text-sm font-medium text-slate-700 mb-1">Contact</div>
<div className="text-slate-600">{driver.phone}</div>
</div>
<div className="bg-slate-50 rounded-lg p-3">
<div className="text-sm font-medium text-slate-700 mb-1">Current Location</div>
<div className="text-slate-600 text-sm">
{driver.currentLocation.lat.toFixed(4)}, {driver.currentLocation.lng.toFixed(4)}
</div>
</div>
<div className="bg-slate-50 rounded-lg p-3">
<div className="text-sm font-medium text-slate-700 mb-1">Vehicle Capacity</div>
<div className="flex items-center gap-2 text-slate-600">
<span>🚗</span>
<span className="font-medium">{driver.vehicleCapacity || 4} passengers</span>
</div>
</div>
<div className="bg-slate-50 rounded-lg p-3">
<div className="text-sm font-medium text-slate-700 mb-1">Assignments</div>
<div className="flex items-center gap-2">
<span className="bg-blue-100 text-blue-800 text-xs font-medium px-2 py-1 rounded-full">
{driver.assignedVipIds.length} VIPs
</span>
<span className={`text-xs font-medium px-2 py-1 rounded-full ${
driver.assignedVipIds.length === 0
? 'bg-green-100 text-green-800'
: 'bg-amber-100 text-amber-800'
}`}>
{driver.assignedVipIds.length === 0 ? 'Available' : 'Assigned'}
</span>
</div>
</div>
</div>
{/* Action Buttons */}
<div className="space-y-3">
<Link
to={`/drivers/${driver.id}`}
className="bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white px-4 py-2 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow-md w-full text-center block"
>
View Dashboard
</Link>
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Phone
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Department
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Assigned Events
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{drivers?.map((driver) => (
<tr key={driver.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{driver.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{driver.phone}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{driver.department || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{driver.events?.length || 0}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-3 py-2 rounded-lg text-xs font-medium transition-all duration-200 shadow-sm hover:shadow-md flex-1"
onClick={() => setEditingDriver(driver)}
<button
onClick={() => handleEdit(driver)}
className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80"
>
<Edit className="h-4 w-4 mr-1" />
Edit
</button>
<button
className="bg-gradient-to-r from-red-500 to-red-600 hover:from-red-600 hover:to-red-700 text-white px-3 py-2 rounded-lg text-xs font-medium transition-all duration-200 shadow-sm hover:shadow-md flex-1"
onClick={() => handleDeleteDriver(driver.id)}
<button
onClick={() => handleDelete(driver.id, driver.name)}
className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4 mr-1" />
Delete
</button>
</div>
</div>
</div>
</div>
))}
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Modals */}
{showForm && (
<DriverForm
onSubmit={handleAddDriver}
onCancel={() => setShowForm(false)}
/>
)}
{editingDriver && (
<EditDriverForm
driver={editingDriver}
onSubmit={handleEditDriver}
onCancel={() => setEditingDriver(null)}
onSubmit={handleSubmit}
onCancel={handleCancel}
isSubmitting={isSubmitting}
/>
)}
</div>
);
};
export default DriverList;
}

View File

@@ -0,0 +1,205 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { ScheduleEvent } from '@/types';
import { formatDateTime } from '@/lib/utils';
import { Plus, Edit, Trash2 } from 'lucide-react';
import { EventForm, EventFormData } from '@/components/EventForm';
import { Loading } from '@/components/Loading';
export function EventList() {
const queryClient = useQueryClient();
const [showForm, setShowForm] = useState(false);
const [editingEvent, setEditingEvent] = useState<ScheduleEvent | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { data: events, isLoading } = useQuery<ScheduleEvent[]>({
queryKey: ['events'],
queryFn: async () => {
const { data } = await api.get('/events');
return data;
},
});
const createMutation = useMutation({
mutationFn: async (data: EventFormData) => {
await api.post('/events', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['events'] });
setShowForm(false);
setIsSubmitting(false);
toast.success('Event created successfully');
},
onError: (error: any) => {
console.error('[EVENT] Failed to create:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to create event');
},
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: EventFormData }) => {
await api.patch(`/events/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['events'] });
setShowForm(false);
setEditingEvent(null);
setIsSubmitting(false);
toast.success('Event updated successfully');
},
onError: (error: any) => {
console.error('[EVENT] Failed to update:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to update event');
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await api.delete(`/events/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['events'] });
toast.success('Event deleted successfully');
},
onError: (error: any) => {
console.error('[EVENT] Failed to delete:', error);
toast.error(error.response?.data?.message || 'Failed to delete event');
},
});
const handleAdd = () => {
setEditingEvent(null);
setShowForm(true);
};
const handleEdit = (event: ScheduleEvent) => {
setEditingEvent(event);
setShowForm(true);
};
const handleDelete = (id: string, title: string) => {
if (confirm(`Delete event "${title}"? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleSubmit = (data: EventFormData) => {
setIsSubmitting(true);
if (editingEvent) {
updateMutation.mutate({ id: editingEvent.id, data });
} else {
createMutation.mutate(data);
}
};
const handleCancel = () => {
setShowForm(false);
setEditingEvent(null);
setIsSubmitting(false);
};
if (isLoading) {
return <Loading message="Loading events..." />;
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-900">Schedule</h1>
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90"
>
<Plus className="h-4 w-4 mr-2" />
Add Event
</button>
</div>
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Title
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
VIP
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Driver
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Start Time
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{events?.map((event) => (
<tr key={event.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{event.title}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.vip?.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{event.driver?.name || 'Unassigned'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{formatDateTime(event.startTime)}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`px-2 py-1 text-xs rounded-full ${
event.status === 'SCHEDULED' ? 'bg-blue-100 text-blue-800' :
event.status === 'IN_PROGRESS' ? 'bg-yellow-100 text-yellow-800' :
event.status === 'COMPLETED' ? 'bg-green-100 text-green-800' :
'bg-gray-100 text-gray-800'
}`}>
{event.status}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
onClick={() => handleEdit(event)}
className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80"
>
<Edit className="h-4 w-4 mr-1" />
Edit
</button>
<button
onClick={() => handleDelete(event.id, event.title)}
className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4 mr-1" />
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
{showForm && (
<EventForm
event={editingEvent}
onSubmit={handleSubmit}
onCancel={handleCancel}
isSubmitting={isSubmitting}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,296 @@
import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { Plus, Edit, Trash2, Plane } from 'lucide-react';
import { FlightForm, FlightFormData } from '@/components/FlightForm';
import { Loading } from '@/components/Loading';
import { ErrorMessage } from '@/components/ErrorMessage';
interface Flight {
id: string;
vipId: string;
vip?: {
name: string;
organization: string | null;
};
flightNumber: string;
flightDate: string;
segment: number;
departureAirport: string;
arrivalAirport: string;
scheduledDeparture: string | null;
scheduledArrival: string | null;
actualDeparture: string | null;
actualArrival: string | null;
status: string | null;
}
export function FlightList() {
const queryClient = useQueryClient();
const [showForm, setShowForm] = useState(false);
const [editingFlight, setEditingFlight] = useState<Flight | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
const { data: flights, isLoading, isError, error, refetch } = useQuery<Flight[]>({
queryKey: ['flights'],
queryFn: async () => {
const { data } = await api.get('/flights');
return data;
},
});
const createMutation = useMutation({
mutationFn: async (data: FlightFormData) => {
await api.post('/flights', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['flights'] });
setShowForm(false);
setIsSubmitting(false);
toast.success('Flight created successfully');
},
onError: (error: any) => {
console.error('[FLIGHT] Failed to create:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to create flight');
},
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: FlightFormData }) => {
await api.patch(`/flights/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['flights'] });
setShowForm(false);
setEditingFlight(null);
setIsSubmitting(false);
toast.success('Flight updated successfully');
},
onError: (error: any) => {
console.error('[FLIGHT] Failed to update:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to update flight');
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await api.delete(`/flights/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['flights'] });
toast.success('Flight deleted successfully');
},
onError: (error: any) => {
console.error('[FLIGHT] Failed to delete:', error);
toast.error(error.response?.data?.message || 'Failed to delete flight');
},
});
const handleAdd = () => {
setEditingFlight(null);
setShowForm(true);
};
const handleEdit = (flight: Flight) => {
setEditingFlight(flight);
setShowForm(true);
};
const handleDelete = (id: string, flightNumber: string) => {
if (confirm(`Delete flight ${flightNumber}? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleSubmit = (data: FlightFormData) => {
setIsSubmitting(true);
if (editingFlight) {
updateMutation.mutate({ id: editingFlight.id, data });
} else {
createMutation.mutate(data);
}
};
const handleCancel = () => {
setShowForm(false);
setEditingFlight(null);
setIsSubmitting(false);
};
const formatTime = (isoString: string | null) => {
if (!isoString) return '-';
return new Date(isoString).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
};
const getStatusColor = (status: string | null) => {
switch (status?.toLowerCase()) {
case 'scheduled':
return 'bg-blue-100 text-blue-800';
case 'boarding':
return 'bg-yellow-100 text-yellow-800';
case 'departed':
case 'en-route':
return 'bg-purple-100 text-purple-800';
case 'landed':
return 'bg-green-100 text-green-800';
case 'delayed':
return 'bg-orange-100 text-orange-800';
case 'cancelled':
return 'bg-red-100 text-red-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
if (isLoading) {
return <Loading message="Loading flights..." />;
}
if (isError) {
return (
<ErrorMessage
title="Failed to load flights"
message={(error as any)?.message || 'An error occurred while loading flights'}
onRetry={() => refetch()}
/>
);
}
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-900">Flights</h1>
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90"
>
<Plus className="h-4 w-4 mr-2" />
Add Flight
</button>
</div>
{flights && flights.length > 0 ? (
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Flight
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
VIP
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Route
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Scheduled
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{flights.map((flight) => (
<tr key={flight.id}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<Plane className="h-4 w-4 text-gray-400 mr-2" />
<div>
<div className="text-sm font-medium text-gray-900">
{flight.flightNumber}
</div>
<div className="text-xs text-gray-500">
Segment {flight.segment}
</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<div className="font-medium text-gray-900">{flight.vip?.name}</div>
{flight.vip?.organization && (
<div className="text-xs text-gray-500">{flight.vip.organization}</div>
)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<div className="flex items-center">
<span className="font-medium">{flight.departureAirport}</span>
<span className="mx-2"></span>
<span className="font-medium">{flight.arrivalAirport}</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<div className="text-xs">
<div>Dep: {formatTime(flight.scheduledDeparture)}</div>
<div>Arr: {formatTime(flight.scheduledArrival)}</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span
className={`px-2 py-1 text-xs rounded-full ${getStatusColor(
flight.status
)}`}
>
{flight.status || 'Unknown'}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
onClick={() => handleEdit(flight)}
className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80"
>
<Edit className="h-4 w-4 mr-1" />
Edit
</button>
<button
onClick={() => handleDelete(flight.id, flight.flightNumber)}
className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4 mr-1" />
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<div className="bg-white shadow rounded-lg p-12 text-center">
<Plane className="h-12 w-12 text-gray-400 mx-auto mb-4" />
<p className="text-gray-500 mb-4">No flights tracked yet.</p>
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90"
>
<Plus className="h-4 w-4 mr-2" />
Add Your First Flight
</button>
</div>
)}
{showForm && (
<FlightForm
flight={editingFlight}
onSubmit={handleSubmit}
onCancel={handleCancel}
isSubmitting={isSubmitting}
/>
)}
</div>
);
}

View File

@@ -0,0 +1,45 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '@/contexts/AuthContext';
import { Plane } from 'lucide-react';
export function Login() {
const { isAuthenticated, loginWithRedirect } = useAuth();
const navigate = useNavigate();
useEffect(() => {
if (isAuthenticated) {
navigate('/dashboard');
}
}, [isAuthenticated, navigate]);
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
<div className="max-w-md w-full bg-white rounded-lg shadow-xl p-8">
<div className="text-center mb-8">
<div className="inline-block p-3 bg-primary/10 rounded-full mb-4">
<Plane className="h-12 w-12 text-primary" />
</div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">
VIP Coordinator
</h1>
<p className="text-gray-600">
Transportation logistics and event coordination
</p>
</div>
<button
onClick={() => loginWithRedirect()}
className="w-full bg-primary text-primary-foreground py-3 px-4 rounded-lg font-medium hover:bg-primary/90 transition-colors"
>
Sign In with Auth0
</button>
<div className="mt-6 text-center text-sm text-gray-500">
<p>First user becomes administrator</p>
<p>Subsequent users require admin approval</p>
</div>
</div>
</div>
);
}

View File

@@ -1,105 +1,44 @@
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiCall } from '../utils/api';
import { User } from '../types';
import { useAuth } from '@/contexts/AuthContext';
import { Clock, Mail } from 'lucide-react';
const PendingApproval: React.FC = () => {
const navigate = useNavigate();
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
// Get user data from localStorage
const savedUser = localStorage.getItem('user');
if (savedUser) {
setUser(JSON.parse(savedUser));
}
setLoading(false);
// Check status every 30 seconds
const interval = setInterval(checkUserStatus, 30000);
return () => clearInterval(interval);
}, []);
const checkUserStatus = async () => {
try {
const token = localStorage.getItem('authToken');
const { data: userData } = await apiCall('/auth/users/me', {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (userData) {
setUser(userData);
// If user is approved, redirect to dashboard
if (userData.status === 'active') {
window.location.href = '/';
}
}
} catch (error) {
console.error('Error checking user status:', error);
}
};
const handleLogout = () => {
localStorage.removeItem('authToken');
localStorage.removeItem('user');
window.location.href = '/';
};
if (loading) {
return (
<div className="min-h-screen bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 flex items-center justify-center">
<div className="text-center">
<div className="animate-spin rounded-full h-16 w-16 border-4 border-amber-500 border-t-transparent mx-auto"></div>
<p className="mt-4 text-slate-600">Loading...</p>
</div>
</div>
);
}
export function PendingApproval() {
const { user, logout } = useAuth();
return (
<div className="min-h-screen bg-gradient-to-br from-amber-50 via-orange-50 to-yellow-50 flex items-center justify-center p-4">
<div className="bg-white rounded-3xl shadow-2xl max-w-md w-full p-8 text-center relative overflow-hidden">
{/* Decorative element */}
<div className="absolute top-0 right-0 w-40 h-40 bg-gradient-to-br from-amber-200 to-orange-200 rounded-full blur-3xl opacity-30 -translate-y-20 translate-x-20"></div>
<div className="relative z-10">
{/* Icon */}
<div className="w-24 h-24 bg-gradient-to-br from-amber-400 to-orange-500 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg">
<svg className="w-12 h-12 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-blue-50 to-indigo-100">
<div className="max-w-md w-full bg-white rounded-lg shadow-xl p-8">
<div className="text-center">
<div className="inline-block p-3 bg-yellow-100 rounded-full mb-4">
<Clock className="h-12 w-12 text-yellow-600" />
</div>
{/* Welcome message */}
<h1 className="text-3xl font-bold bg-gradient-to-r from-amber-600 to-orange-600 bg-clip-text text-transparent mb-2">
Welcome, {user?.name?.split(' ')[0]}!
<h1 className="text-3xl font-bold text-gray-900 mb-2">
Account Pending Approval
</h1>
<p className="text-lg text-slate-600 mb-8">
Your account is being reviewed
<p className="text-gray-600 mb-6">
Your account is awaiting administrator approval. You will be able to access the system once your account has been approved.
</p>
{/* Status message */}
<div className="bg-gradient-to-r from-amber-50 to-orange-50 border border-amber-200 rounded-2xl p-6 mb-8">
<p className="text-amber-800 leading-relaxed">
Thank you for signing up! An administrator will review your account request shortly.
We'll notify you once your access has been approved.
{user?.email && (
<div className="bg-gray-50 rounded-lg p-4 mb-6">
<div className="flex items-center justify-center text-sm text-gray-700">
<Mail className="h-4 w-4 mr-2" />
<span>{user.email}</span>
</div>
</div>
)}
<div className="text-sm text-gray-500 mb-6">
<p>Please contact your administrator if you have any questions.</p>
<p className="mt-2">
<strong>Note:</strong> The first user is automatically approved as Administrator.
</p>
</div>
{/* Auto-refresh notice */}
<p className="text-sm text-slate-500 mb-8">
This page checks for updates automatically
</p>
{/* Logout button */}
<button
onClick={handleLogout}
className="w-full bg-gradient-to-r from-slate-600 to-slate-700 hover:from-slate-700 hover:to-slate-800 text-white font-medium py-3 px-6 rounded-xl transition-all duration-200 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5"
onClick={() => logout()}
className="w-full bg-gray-600 text-white py-3 px-4 rounded-lg font-medium hover:bg-gray-700 transition-colors"
>
Sign Out
</button>
@@ -107,6 +46,4 @@ const PendingApproval: React.FC = () => {
</div>
</div>
);
};
export default PendingApproval;
}

View File

@@ -1,111 +0,0 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { useApi, useMutation } from '../hooks/useApi';
import { vipApi } from '../api/client';
import VipForm from '../components/VipForm';
import { LoadingSpinner } from '../components/LoadingSpinner';
import { ErrorMessage } from '../components/ErrorMessage';
// Simplified VIP List - no more manual loading states, error handling, or token management
const SimplifiedVipList: React.FC = () => {
const [showForm, setShowForm] = useState(false);
const { data: vips, loading, error, refetch } = useApi(() => vipApi.list());
const createVip = useMutation(vipApi.create);
const deleteVip = useMutation(vipApi.delete);
const handleAddVip = async (vipData: any) => {
try {
await createVip.mutate(vipData);
setShowForm(false);
refetch(); // Refresh the list
} catch (error) {
// Error is already handled by the hook
}
};
const handleDeleteVip = async (id: string) => {
if (!confirm('Are you sure you want to delete this VIP?')) return;
try {
await deleteVip.mutate(id);
refetch(); // Refresh the list
} catch (error) {
// Error is already handled by the hook
}
};
if (loading) return <LoadingSpinner message="Loading VIPs..." />;
if (error) return <ErrorMessage message={error} onDismiss={() => refetch()} />;
if (!vips) return null;
return (
<div className="p-6">
<div className="flex justify-between items-center mb-6">
<h1 className="text-2xl font-bold">VIP Management</h1>
<button
onClick={() => setShowForm(true)}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
Add VIP
</button>
</div>
{createVip.error && (
<ErrorMessage message={createVip.error} className="mb-4" />
)}
{deleteVip.error && (
<ErrorMessage message={deleteVip.error} className="mb-4" />
)}
<div className="grid gap-4">
{vips.map((vip) => (
<div key={vip.id} className="bg-white p-4 rounded-lg shadow">
<div className="flex justify-between items-start">
<div>
<h3 className="text-lg font-semibold">{vip.name}</h3>
<p className="text-gray-600">{vip.organization}</p>
<p className="text-sm text-gray-500">
{vip.transportMode === 'flight'
? `Flight: ${vip.flights?.[0]?.flightNumber || 'TBD'}`
: `Driving - Arrival: ${new Date(vip.expectedArrival).toLocaleString()}`
}
</p>
</div>
<div className="flex gap-2">
<Link
to={`/vips/${vip.id}`}
className="text-blue-500 hover:text-blue-700"
>
View Details
</Link>
<button
onClick={() => handleDeleteVip(vip.id)}
disabled={deleteVip.loading}
className="text-red-500 hover:text-red-700 disabled:opacity-50"
>
Delete
</button>
</div>
</div>
</div>
))}
</div>
{showForm && (
<div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4">
<div className="bg-white rounded-lg p-6 max-w-2xl w-full max-h-[90vh] overflow-y-auto">
<h2 className="text-xl font-bold mb-4">Add New VIP</h2>
<VipForm
onSubmit={handleAddVip}
onCancel={() => setShowForm(false)}
/>
</div>
</div>
)}
</div>
);
};
export default SimplifiedVipList;

View File

@@ -0,0 +1,267 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { Check, X, UserCheck, UserX, Shield, Trash2 } from 'lucide-react';
import { useState } from 'react';
import { Loading } from '@/components/Loading';
interface User {
id: string;
email: string;
name: string | null;
role: string;
isApproved: boolean;
createdAt: string;
}
export function UserList() {
const queryClient = useQueryClient();
const [processingUser, setProcessingUser] = useState<string | null>(null);
const { data: users, isLoading } = useQuery<User[]>({
queryKey: ['users'],
queryFn: async () => {
const { data } = await api.get('/users');
return data;
},
});
const approveMutation = useMutation({
mutationFn: async (userId: string) => {
await api.patch(`/users/${userId}/approve`, { isApproved: true });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] });
setProcessingUser(null);
toast.success('User approved successfully');
},
onError: (error: any) => {
console.error('[USERS] Failed to approve user:', error);
setProcessingUser(null);
toast.error(error.response?.data?.message || 'Failed to approve user');
},
});
const deleteUserMutation = useMutation({
mutationFn: async (userId: string) => {
await api.delete(`/users/${userId}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] });
setProcessingUser(null);
toast.success('User deleted successfully');
},
onError: (error: any) => {
console.error('[USERS] Failed to delete user:', error);
setProcessingUser(null);
toast.error(error.response?.data?.message || 'Failed to delete user');
},
});
const changeRoleMutation = useMutation({
mutationFn: async ({ userId, role }: { userId: string; role: string }) => {
await api.patch(`/users/${userId}`, { role });
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['users'] });
toast.success('User role updated successfully');
},
onError: (error: any) => {
console.error('[USERS] Failed to update user role:', error);
toast.error(error.response?.data?.message || 'Failed to update user role');
},
});
const handleRoleChange = (userId: string, newRole: string) => {
if (confirm(`Change user role to ${newRole}?`)) {
changeRoleMutation.mutate({ userId, role: newRole });
}
};
const handleApprove = (userId: string) => {
if (confirm('Approve this user?')) {
setProcessingUser(userId);
approveMutation.mutate(userId);
}
};
const handleDeny = (userId: string) => {
if (confirm('Delete this user? This action cannot be undone.')) {
setProcessingUser(userId);
deleteUserMutation.mutate(userId);
}
};
if (isLoading) {
return <Loading message="Loading users..." />;
}
const pendingUsers = users?.filter((u) => !u.isApproved) || [];
const approvedUsers = users?.filter((u) => u.isApproved) || [];
return (
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-6">User Management</h1>
{/* Pending Approval Section */}
{pendingUsers.length > 0 && (
<div className="mb-8">
<div className="flex items-center mb-4">
<UserX className="h-5 w-5 text-yellow-600 mr-2" />
<h2 className="text-xl font-semibold text-gray-900">
Pending Approval ({pendingUsers.length})
</h2>
</div>
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Email
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Role
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Requested
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{pendingUsers.map((user) => (
<tr key={user.id} className="bg-yellow-50">
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{user.name || 'Unknown User'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{user.email}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<span className="px-2 py-1 bg-gray-100 rounded text-xs font-medium">
{user.role}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{new Date(user.createdAt).toLocaleDateString()}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
onClick={() => handleApprove(user.id)}
disabled={processingUser === user.id}
className="inline-flex items-center px-3 py-1 bg-green-600 text-white rounded hover:bg-green-700 disabled:opacity-50"
>
<Check className="h-4 w-4 mr-1" />
Approve
</button>
<button
onClick={() => handleDeny(user.id)}
disabled={processingUser === user.id}
className="inline-flex items-center px-3 py-1 bg-red-600 text-white rounded hover:bg-red-700 disabled:opacity-50"
>
<X className="h-4 w-4 mr-1" />
Deny
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Approved Users Section */}
<div>
<div className="flex items-center mb-4">
<UserCheck className="h-5 w-5 text-green-600 mr-2" />
<h2 className="text-xl font-semibold text-gray-900">
Approved Users ({approvedUsers.length})
</h2>
</div>
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Email
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Role
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{approvedUsers.map((user) => (
<tr key={user.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{user.name || 'Unknown User'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{user.email}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
<span
className={`px-2 py-1 rounded text-xs font-medium ${
user.role === 'ADMINISTRATOR'
? 'bg-purple-100 text-purple-800'
: user.role === 'COORDINATOR'
? 'bg-blue-100 text-blue-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{user.role === 'ADMINISTRATOR' && <Shield className="h-3 w-3 inline mr-1" />}
{user.role}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-green-600 font-medium">
<Check className="h-4 w-4 inline mr-1" />
Active
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex items-center gap-2">
<select
value={user.role}
onChange={(e) => handleRoleChange(user.id, e.target.value)}
className="text-sm border border-gray-300 rounded px-2 py-1 focus:ring-primary focus:border-primary"
>
<option value="DRIVER">Driver</option>
<option value="COORDINATOR">Coordinator</option>
<option value="ADMINISTRATOR">Administrator</option>
</select>
<button
onClick={() => handleDeny(user.id)}
className="inline-flex items-center px-2 py-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded"
title="Delete user"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,404 @@
import { useQuery } from '@tanstack/react-query';
import { useParams, useNavigate } from 'react-router-dom';
import { api } from '@/lib/api';
import { Loading } from '@/components/Loading';
import {
ArrowLeft,
Calendar,
Clock,
MapPin,
Car,
User,
Plane,
Download,
Mail,
} from 'lucide-react';
interface VIP {
id: string;
name: string;
organization: string | null;
department: string;
arrivalMode: string;
expectedArrival: string | null;
airportPickup: boolean;
venueTransport: boolean;
notes: string | null;
flights: Array<{
id: string;
flightNumber: string;
departureAirport: string;
arrivalAirport: string;
scheduledDeparture: string | null;
scheduledArrival: string | null;
status: string | null;
}>;
}
interface ScheduleEvent {
id: string;
title: string;
pickupLocation: string | null;
dropoffLocation: string | null;
location: string | null;
startTime: string;
endTime: string;
type: string;
status: string;
description: string | null;
vip: {
id: string;
name: string;
};
driver: {
id: string;
name: string;
} | null;
vehicle: {
id: string;
name: string;
type: string;
seatCapacity: number;
} | null;
}
export function VIPSchedule() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { data: vip, isLoading: vipLoading } = useQuery<VIP>({
queryKey: ['vip', id],
queryFn: async () => {
const { data } = await api.get(`/vips/${id}`);
return data;
},
});
const { data: events, isLoading: eventsLoading } = useQuery<ScheduleEvent[]>({
queryKey: ['events'],
queryFn: async () => {
const { data } = await api.get('/events');
return data;
},
});
if (vipLoading || eventsLoading) {
return <Loading message="Loading VIP schedule..." />;
}
if (!vip) {
return (
<div className="text-center py-12">
<p className="text-gray-500">VIP not found</p>
</div>
);
}
// Filter events for this VIP
const vipEvents = events?.filter((event) => event.vip.id === id) || [];
// Sort events by start time
const sortedEvents = [...vipEvents].sort(
(a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
);
// Group events by day
const eventsByDay = sortedEvents.reduce((acc, event) => {
const date = new Date(event.startTime).toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
if (!acc[date]) {
acc[date] = [];
}
acc[date].push(event);
return acc;
}, {} as Record<string, ScheduleEvent[]>);
const getEventTypeColor = (type: string) => {
switch (type) {
case 'TRANSPORT':
return 'bg-blue-100 text-blue-800';
case 'MEETING':
return 'bg-purple-100 text-purple-800';
case 'EVENT':
return 'bg-green-100 text-green-800';
case 'MEAL':
return 'bg-orange-100 text-orange-800';
case 'ACCOMMODATION':
return 'bg-gray-100 text-gray-800';
default:
return 'bg-gray-100 text-gray-800';
}
};
const getEventTypeIcon = (type: string) => {
switch (type) {
case 'TRANSPORT':
return <Car className="h-4 w-4" />;
case 'MEETING':
case 'EVENT':
return <Calendar className="h-4 w-4" />;
default:
return <Clock className="h-4 w-4" />;
}
};
const formatTime = (dateStr: string) => {
return new Date(dateStr).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
});
};
const handleExport = () => {
// TODO: Implement PDF export
alert('PDF export feature coming soon!');
};
const handleEmail = () => {
// TODO: Implement email functionality
alert('Email feature coming soon!');
};
return (
<div className="max-w-4xl mx-auto">
{/* Header */}
<div className="mb-6">
<button
onClick={() => navigate('/vips')}
className="inline-flex items-center text-sm text-gray-600 hover:text-gray-900 mb-4"
>
<ArrowLeft className="h-4 w-4 mr-1" />
Back to VIPs
</button>
<div className="bg-white rounded-lg shadow-lg p-6">
<div className="flex justify-between items-start mb-4">
<div>
<h1 className="text-3xl font-bold text-gray-900 mb-2">{vip.name}</h1>
{vip.organization && (
<p className="text-lg text-gray-600">{vip.organization}</p>
)}
<p className="text-sm text-gray-500">{vip.department.replace('_', ' ')}</p>
</div>
<div className="flex gap-2">
<button
onClick={handleEmail}
className="inline-flex items-center px-3 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50"
>
<Mail className="h-4 w-4 mr-2" />
Email Schedule
</button>
<button
onClick={handleExport}
className="inline-flex items-center px-3 py-2 bg-primary text-white rounded-lg text-sm font-medium hover:bg-primary/90"
>
<Download className="h-4 w-4 mr-2" />
Export PDF
</button>
</div>
</div>
{/* Arrival Info */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 mt-6 pt-6 border-t">
<div>
<p className="text-sm text-gray-500 mb-1">Arrival Mode</p>
<div className="flex items-center gap-2">
{vip.arrivalMode === 'FLIGHT' ? (
<Plane className="h-5 w-5 text-blue-600" />
) : (
<Car className="h-5 w-5 text-gray-600" />
)}
<span className="font-medium">{vip.arrivalMode.replace('_', ' ')}</span>
</div>
</div>
{vip.expectedArrival && (
<div>
<p className="text-sm text-gray-500 mb-1">Expected Arrival</p>
<p className="font-medium">
{new Date(vip.expectedArrival).toLocaleString('en-US', {
weekday: 'short',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})}
</p>
</div>
)}
</div>
{/* Flight Information */}
{vip.flights && vip.flights.length > 0 && (
<div className="mt-6 pt-6 border-t">
<h3 className="text-lg font-semibold mb-3 flex items-center">
<Plane className="h-5 w-5 mr-2 text-blue-600" />
Flight Information
</h3>
<div className="space-y-2">
{vip.flights.map((flight) => (
<div
key={flight.id}
className="bg-blue-50 rounded-lg p-3 flex justify-between items-center"
>
<div>
<p className="font-medium text-blue-900">
Flight {flight.flightNumber}
</p>
<p className="text-sm text-blue-700">
{flight.departureAirport} {flight.arrivalAirport}
</p>
</div>
<div className="text-right">
{flight.scheduledArrival && (
<p className="text-sm text-blue-900">
Arrives:{' '}
{new Date(flight.scheduledArrival).toLocaleString('en-US', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit',
})}
</p>
)}
{flight.status && (
<p className="text-xs text-blue-600">Status: {flight.status}</p>
)}
</div>
</div>
))}
</div>
</div>
)}
{vip.notes && (
<div className="mt-6 pt-6 border-t">
<p className="text-sm text-gray-500 mb-1">Notes</p>
<p className="text-gray-700">{vip.notes}</p>
</div>
)}
</div>
</div>
{/* Schedule */}
<div className="bg-white rounded-lg shadow-lg p-6">
<h2 className="text-2xl font-bold text-gray-900 mb-6 flex items-center">
<Calendar className="h-6 w-6 mr-2 text-primary" />
Schedule & Itinerary
</h2>
{sortedEvents.length === 0 ? (
<div className="text-center py-12">
<Calendar className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<p className="text-gray-500">No scheduled events yet</p>
</div>
) : (
<div className="space-y-8">
{Object.entries(eventsByDay).map(([date, dayEvents]) => (
<div key={date}>
<h3 className="text-lg font-semibold text-gray-900 mb-4 pb-2 border-b">
{date}
</h3>
<div className="space-y-4">
{dayEvents.map((event) => (
<div
key={event.id}
className="flex gap-4 p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors"
>
{/* Time */}
<div className="flex-shrink-0 w-32">
<div className="flex items-center text-sm font-medium text-gray-900">
<Clock className="h-4 w-4 mr-1" />
{formatTime(event.startTime)}
</div>
<div className="text-xs text-gray-500 ml-5">
to {formatTime(event.endTime)}
</div>
</div>
{/* Event Details */}
<div className="flex-1">
<div className="flex items-center gap-2 mb-2">
{getEventTypeIcon(event.type)}
<span
className={`px-2 py-1 rounded text-xs font-medium ${getEventTypeColor(event.type)}`}
>
{event.type}
</span>
<h4 className="font-semibold text-gray-900">{event.title}</h4>
</div>
{/* Location */}
{event.type === 'TRANSPORT' ? (
<div className="flex items-center gap-1 text-sm text-gray-600 mb-2">
<MapPin className="h-4 w-4" />
<span>
{event.pickupLocation || 'Pickup'} {' '}
{event.dropoffLocation || 'Dropoff'}
</span>
</div>
) : (
event.location && (
<div className="flex items-center gap-1 text-sm text-gray-600 mb-2">
<MapPin className="h-4 w-4" />
<span>{event.location}</span>
</div>
)
)}
{/* Description */}
{event.description && (
<p className="text-sm text-gray-600 mb-2">{event.description}</p>
)}
{/* Transport Details */}
{event.type === 'TRANSPORT' && (
<div className="flex gap-4 mt-2">
{event.driver && (
<div className="flex items-center gap-1 text-sm text-gray-600">
<User className="h-4 w-4" />
<span>Driver: {event.driver.name}</span>
</div>
)}
{event.vehicle && (
<div className="flex items-center gap-1 text-sm text-gray-600">
<Car className="h-4 w-4" />
<span>
{event.vehicle.name} ({event.vehicle.type.replace('_', ' ')})
</span>
</div>
)}
</div>
)}
{/* Status */}
<div className="mt-2">
<span
className={`text-xs px-2 py-1 rounded ${
event.status === 'COMPLETED'
? 'bg-green-100 text-green-800'
: event.status === 'IN_PROGRESS'
? 'bg-blue-100 text-blue-800'
: event.status === 'CANCELLED'
? 'bg-red-100 text-red-800'
: 'bg-gray-100 text-gray-800'
}`}
>
{event.status}
</span>
</div>
</div>
</div>
))}
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,442 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { useState } from 'react';
import { Loading } from '@/components/Loading';
import { Car, Plus, Edit2, Trash2, CheckCircle, XCircle, Wrench } from 'lucide-react';
interface Vehicle {
id: string;
name: string;
type: string;
licensePlate: string | null;
seatCapacity: number;
status: string;
currentDriver: {
id: string;
name: string;
} | null;
events: any[];
notes: string | null;
createdAt: string;
}
const VEHICLE_TYPES = [
{ value: 'VAN', label: 'Van (7-15 seats)' },
{ value: 'SUV', label: 'SUV (5-8 seats)' },
{ value: 'SEDAN', label: 'Sedan (4-5 seats)' },
{ value: 'BUS', label: 'Bus (15+ seats)' },
{ value: 'GOLF_CART', label: 'Golf Cart (2-6 seats)' },
{ value: 'TRUCK', label: 'Truck' },
];
const VEHICLE_STATUS = [
{ value: 'AVAILABLE', label: 'Available', color: 'green' },
{ value: 'IN_USE', label: 'In Use', color: 'blue' },
{ value: 'MAINTENANCE', label: 'Maintenance', color: 'orange' },
{ value: 'RESERVED', label: 'Reserved', color: 'yellow' },
];
export function VehicleList() {
const queryClient = useQueryClient();
const [showForm, setShowForm] = useState(false);
const [editingVehicle, setEditingVehicle] = useState<Vehicle | null>(null);
const [formData, setFormData] = useState({
name: '',
type: 'VAN' as string,
licensePlate: '',
seatCapacity: 8,
status: 'AVAILABLE' as string,
notes: '',
});
const { data: vehicles, isLoading } = useQuery<Vehicle[]>({
queryKey: ['vehicles'],
queryFn: async () => {
const { data } = await api.get('/vehicles');
return data;
},
});
const createMutation = useMutation({
mutationFn: async (vehicleData: any) => {
await api.post('/vehicles', vehicleData);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vehicles'] });
toast.success('Vehicle created successfully');
resetForm();
},
onError: (error: any) => {
console.error('[VEHICLES] Failed to create vehicle:', error);
toast.error(error.response?.data?.message || 'Failed to create vehicle');
},
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: any }) => {
await api.patch(`/vehicles/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vehicles'] });
toast.success('Vehicle updated successfully');
resetForm();
},
onError: (error: any) => {
console.error('[VEHICLES] Failed to update vehicle:', error);
toast.error(error.response?.data?.message || 'Failed to update vehicle');
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await api.delete(`/vehicles/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vehicles'] });
toast.success('Vehicle deleted successfully');
},
onError: (error: any) => {
console.error('[VEHICLES] Failed to delete vehicle:', error);
toast.error(error.response?.data?.message || 'Failed to delete vehicle');
},
});
const resetForm = () => {
setFormData({
name: '',
type: 'VAN',
licensePlate: '',
seatCapacity: 8,
status: 'AVAILABLE',
notes: '',
});
setEditingVehicle(null);
setShowForm(false);
};
const handleEdit = (vehicle: Vehicle) => {
setEditingVehicle(vehicle);
setFormData({
name: vehicle.name,
type: vehicle.type,
licensePlate: vehicle.licensePlate || '',
seatCapacity: vehicle.seatCapacity,
status: vehicle.status,
notes: vehicle.notes || '',
});
setShowForm(true);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const vehicleData = {
...formData,
licensePlate: formData.licensePlate || null,
notes: formData.notes || null,
};
if (editingVehicle) {
updateMutation.mutate({ id: editingVehicle.id, data: vehicleData });
} else {
createMutation.mutate(vehicleData);
}
};
const handleDelete = (id: string, name: string) => {
if (confirm(`Are you sure you want to delete ${name}?`)) {
deleteMutation.mutate(id);
}
};
const getStatusBadge = (status: string) => {
const statusConfig = VEHICLE_STATUS.find((s) => s.value === status);
const colorClasses = {
green: 'bg-green-100 text-green-800',
blue: 'bg-blue-100 text-blue-800',
orange: 'bg-orange-100 text-orange-800',
yellow: 'bg-yellow-100 text-yellow-800',
};
return (
<span className={`px-2 py-1 rounded text-xs font-medium ${colorClasses[statusConfig?.color as keyof typeof colorClasses] || 'bg-gray-100 text-gray-800'}`}>
{statusConfig?.label || status}
</span>
);
};
const getStatusIcon = (status: string) => {
switch (status) {
case 'AVAILABLE':
return <CheckCircle className="h-4 w-4 text-green-600" />;
case 'MAINTENANCE':
return <Wrench className="h-4 w-4 text-orange-600" />;
case 'IN_USE':
return <Car className="h-4 w-4 text-blue-600" />;
default:
return <XCircle className="h-4 w-4 text-gray-600" />;
}
};
if (isLoading) {
return <Loading message="Loading vehicles..." />;
}
const availableVehicles = vehicles?.filter((v) => v.status === 'AVAILABLE') || [];
const inUseVehicles = vehicles?.filter((v) => v.status === 'IN_USE') || [];
const maintenanceVehicles = vehicles?.filter((v) => v.status === 'MAINTENANCE') || [];
return (
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-900">Vehicle Management</h1>
<button
onClick={() => setShowForm(!showForm)}
className="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90"
>
<Plus className="h-5 w-5 mr-2" />
{showForm ? 'Cancel' : 'Add Vehicle'}
</button>
</div>
{/* Stats Summary */}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div className="bg-white p-4 rounded-lg shadow">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Total Vehicles</p>
<p className="text-2xl font-bold text-gray-900">{vehicles?.length || 0}</p>
</div>
<Car className="h-8 w-8 text-gray-400" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Available</p>
<p className="text-2xl font-bold text-green-600">{availableVehicles.length}</p>
</div>
<CheckCircle className="h-8 w-8 text-green-400" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">In Use</p>
<p className="text-2xl font-bold text-blue-600">{inUseVehicles.length}</p>
</div>
<Car className="h-8 w-8 text-blue-400" />
</div>
</div>
<div className="bg-white p-4 rounded-lg shadow">
<div className="flex items-center justify-between">
<div>
<p className="text-sm text-gray-600">Maintenance</p>
<p className="text-2xl font-bold text-orange-600">{maintenanceVehicles.length}</p>
</div>
<Wrench className="h-8 w-8 text-orange-400" />
</div>
</div>
</div>
{/* Add/Edit Form */}
{showForm && (
<div className="bg-white p-6 rounded-lg shadow mb-6">
<h2 className="text-xl font-semibold mb-4">
{editingVehicle ? 'Edit Vehicle' : 'Add New Vehicle'}
</h2>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Vehicle Name *
</label>
<input
type="text"
required
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
placeholder="e.g., Blue Van, Suburban #3"
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Vehicle Type *
</label>
<select
required
value={formData.type}
onChange={(e) => setFormData({ ...formData, type: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
>
{VEHICLE_TYPES.map((type) => (
<option key={type.value} value={type.value}>
{type.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
License Plate
</label>
<input
type="text"
value={formData.licensePlate}
onChange={(e) => setFormData({ ...formData, licensePlate: e.target.value })}
placeholder="ABC-1234"
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Seat Capacity *
</label>
<input
type="number"
required
min="1"
max="60"
value={formData.seatCapacity}
onChange={(e) => setFormData({ ...formData, seatCapacity: parseInt(e.target.value) })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
/>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Status *
</label>
<select
required
value={formData.status}
onChange={(e) => setFormData({ ...formData, status: e.target.value })}
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
>
{VEHICLE_STATUS.map((status) => (
<option key={status.value} value={status.value}>
{status.label}
</option>
))}
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Notes
</label>
<input
type="text"
value={formData.notes}
onChange={(e) => setFormData({ ...formData, notes: e.target.value })}
placeholder="Optional notes"
className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-primary focus:border-primary"
/>
</div>
</div>
<div className="flex gap-2">
<button
type="submit"
disabled={createMutation.isPending || updateMutation.isPending}
className="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 disabled:opacity-50"
>
{editingVehicle ? 'Update Vehicle' : 'Create Vehicle'}
</button>
<button
type="button"
onClick={resetForm}
className="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300"
>
Cancel
</button>
</div>
</form>
</div>
)}
{/* Vehicle List */}
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Vehicle
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Type
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
License Plate
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Seats
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Current Driver
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Upcoming Trips
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{vehicles?.map((vehicle) => (
<tr key={vehicle.id}>
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
{getStatusIcon(vehicle.status)}
<span className="ml-2 text-sm font-medium text-gray-900">
{vehicle.name}
</span>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vehicle.type.replace('_', ' ')}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vehicle.licensePlate || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vehicle.seatCapacity}
</td>
<td className="px-6 py-4 whitespace-nowrap">
{getStatusBadge(vehicle.status)}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vehicle.currentDriver?.name || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vehicle.events?.length || 0}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
onClick={() => handleEdit(vehicle)}
className="text-blue-600 hover:text-blue-800"
title="Edit vehicle"
>
<Edit2 className="h-4 w-4" />
</button>
<button
onClick={() => handleDelete(vehicle.id, vehicle.name)}
className="text-red-600 hover:text-red-800"
title="Delete vehicle"
>
<Trash2 className="h-4 w-4" />
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}

View File

@@ -1,683 +0,0 @@
import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom';
import { apiCall } from '../config/api';
import FlightStatus from '../components/FlightStatus';
import ScheduleManager from '../components/ScheduleManager';
interface Flight {
flightNumber: string;
flightDate: string;
segment: number;
}
interface Vip {
id: string;
name: string;
organization: string;
transportMode: 'flight' | 'self-driving';
flightNumber?: string; // Legacy
flightDate?: string; // Legacy
flights?: Flight[]; // New
expectedArrival?: string;
arrivalTime?: string; // Legacy
needsAirportPickup?: boolean;
needsVenueTransport: boolean;
notes: string;
assignedDriverIds: string[];
}
const VipDetails: React.FC = () => {
const { id } = useParams<{ id: string }>();
const [vip, setVip] = useState<Vip | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [schedule, setSchedule] = useState<any[]>([]);
useEffect(() => {
const fetchVip = async () => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const vips = await response.json();
const foundVip = vips.find((v: Vip) => v.id === id);
if (foundVip) {
setVip(foundVip);
} else {
setError('VIP not found');
}
} else {
setError('Failed to fetch VIP data');
}
} catch (err) {
setError('Error loading VIP data');
} finally {
setLoading(false);
}
};
if (id) {
fetchVip();
}
}, [id]);
// Fetch schedule data
useEffect(() => {
const fetchSchedule = async () => {
if (vip) {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vip.id}/schedule`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const scheduleData = await response.json();
setSchedule(scheduleData);
}
} catch (error) {
console.error('Error fetching schedule:', error);
}
}
};
fetchSchedule();
}, [vip]);
// Auto-scroll to schedule section if accessed via #schedule anchor
useEffect(() => {
if (vip && window.location.hash === '#schedule') {
setTimeout(() => {
const scheduleElement = document.getElementById('schedule-section');
if (scheduleElement) {
scheduleElement.scrollIntoView({ behavior: 'smooth' });
}
}, 100);
}
}, [vip]);
// Helper function to get flight info
const getFlightInfo = () => {
if (!vip) return null;
if (vip.transportMode === 'flight') {
if (vip.flights && vip.flights.length > 0) {
return {
flights: vip.flights,
primaryFlight: vip.flights[0]
};
} else if (vip.flightNumber) {
// Legacy support
return {
flights: [{
flightNumber: vip.flightNumber,
flightDate: vip.flightDate || '',
segment: 1
}],
primaryFlight: {
flightNumber: vip.flightNumber,
flightDate: vip.flightDate || '',
segment: 1
}
};
}
}
return null;
};
const handlePrintSchedule = () => {
if (!vip) return;
const printWindow = window.open('', '_blank');
if (!printWindow) return;
const groupEventsByDay = (events: any[]) => {
const grouped: { [key: string]: any[] } = {};
events.forEach(event => {
const date = new Date(event.startTime).toDateString();
if (!grouped[date]) {
grouped[date] = [];
}
grouped[date].push(event);
});
Object.keys(grouped).forEach(date => {
grouped[date].sort((a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime());
});
return grouped;
};
const formatTime = (timeString: string) => {
return new Date(timeString).toLocaleString([], {
hour: '2-digit',
minute: '2-digit'
});
};
const getTypeIcon = (type: string) => {
switch (type) {
case 'transport': return '🚗';
case 'meeting': return '🤝';
case 'event': return '🎉';
case 'meal': return '🍽️';
case 'accommodation': return '🏨';
default: return '📅';
}
};
const groupedSchedule = groupEventsByDay(schedule);
const flightInfo = getFlightInfo();
const printContent = `
<!DOCTYPE html>
<html>
<head>
<title>VIP Schedule - ${vip.name}</title>
<meta charset="UTF-8">
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
color: #2d3748;
background: #ffffff;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 40px 30px;
}
.header {
text-align: center;
margin-bottom: 40px;
padding-bottom: 30px;
border-bottom: 3px solid #e2e8f0;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 40px 30px;
border-radius: 15px;
margin: -40px -30px 40px -30px;
}
.header h1 {
font-size: 2.5rem;
font-weight: 700;
margin-bottom: 10px;
text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.header h2 {
font-size: 1.8rem;
font-weight: 600;
margin-bottom: 20px;
opacity: 0.95;
}
.vip-info {
background: linear-gradient(135deg, #f7fafc 0%, #edf2f7 100%);
padding: 25px;
border-radius: 12px;
margin-bottom: 30px;
border: 1px solid #e2e8f0;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.vip-info p {
margin-bottom: 8px;
font-size: 1rem;
}
.vip-info strong {
color: #4a5568;
font-weight: 600;
}
.day-section {
margin-bottom: 40px;
page-break-inside: avoid;
}
.day-header {
background: linear-gradient(135deg, #4a5568 0%, #2d3748 100%);
color: white;
padding: 20px 25px;
font-size: 1.3rem;
font-weight: 700;
margin-bottom: 20px;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
text-align: center;
}
.event {
background: white;
border: 1px solid #e2e8f0;
margin-bottom: 15px;
padding: 25px;
border-radius: 12px;
display: flex;
align-items: flex-start;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
transition: all 0.2s ease;
}
.event:hover {
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.event-time {
min-width: 120px;
background: linear-gradient(135deg, #edf2f7 0%, #e2e8f0 100%);
padding: 15px;
border-radius: 8px;
text-align: center;
margin-right: 25px;
border: 1px solid #cbd5e0;
}
.event-time .time {
font-weight: 700;
font-size: 1rem;
color: #2d3748;
display: block;
}
.event-time .separator {
font-size: 0.8rem;
color: #718096;
margin: 5px 0;
}
.event-details {
flex: 1;
}
.event-title {
font-weight: 700;
font-size: 1.2rem;
margin-bottom: 10px;
color: #2d3748;
display: flex;
align-items: center;
gap: 8px;
}
.event-icon {
font-size: 1.3rem;
}
.event-location {
color: #4a5568;
margin-bottom: 8px;
font-weight: 500;
display: flex;
align-items: center;
gap: 6px;
}
.event-description {
background: #f7fafc;
padding: 12px 15px;
border-radius: 8px;
font-style: italic;
color: #4a5568;
margin-bottom: 10px;
border-left: 4px solid #cbd5e0;
}
.event-driver {
color: #3182ce;
font-weight: 600;
font-size: 0.9rem;
background: #ebf8ff;
padding: 8px 12px;
border-radius: 6px;
display: inline-flex;
align-items: center;
gap: 6px;
}
.status-badge {
display: inline-block;
padding: 4px 12px;
border-radius: 20px;
font-size: 0.8rem;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.status-scheduled {
background: #bee3f8;
color: #2b6cb0;
}
.status-in-progress {
background: #fbd38d;
color: #c05621;
}
.status-completed {
background: #c6f6d5;
color: #276749;
}
.footer {
margin-top: 50px;
text-align: center;
color: #718096;
font-size: 0.9rem;
padding-top: 20px;
border-top: 1px solid #e2e8f0;
}
.company-logo {
width: 60px;
height: 60px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 20px;
color: white;
font-size: 1.5rem;
font-weight: bold;
}
@media print {
body {
margin: 0;
padding: 0;
}
.container {
padding: 20px;
}
.header {
margin: -20px -20px 30px -20px;
}
.day-section {
page-break-inside: avoid;
}
.event {
page-break-inside: avoid;
}
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="company-logo">VC</div>
<h1>📅 VIP Schedule</h1>
<h2>${vip.name}</h2>
</div>
<div class="vip-info">
<p><strong>Organization:</strong> ${vip.organization}</p>
${vip.transportMode === 'flight' && flightInfo ? `
<p><strong>Flight Information:</strong> ${flightInfo.flights.map(f => f.flightNumber).join(' → ')}</p>
<p><strong>Flight Date:</strong> ${flightInfo.primaryFlight.flightDate ? new Date(flightInfo.primaryFlight.flightDate).toLocaleDateString() : 'TBD'}</p>
` : vip.transportMode === 'self-driving' ? `
<p><strong>Transport Mode:</strong> 🚗 Self-Driving</p>
<p><strong>Expected Arrival:</strong> ${vip.expectedArrival ? new Date(vip.expectedArrival).toLocaleString() : 'TBD'}</p>
` : ''}
<p><strong>Airport Pickup:</strong> ${vip.needsAirportPickup ? '✅ Required' : '❌ Not Required'}</p>
<p><strong>Venue Transport:</strong> ${vip.needsVenueTransport ? '✅ Required' : '❌ Not Required'}</p>
${vip.notes ? `<p><strong>Special Notes:</strong> ${vip.notes}</p>` : ''}
</div>
${Object.entries(groupedSchedule).map(([date, events]) => `
<div class="day-section">
<div class="day-header">
${new Date(date).toLocaleDateString([], {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
})}
</div>
${events.map(event => `
<div class="event">
<div class="event-time">
<span class="time">${formatTime(event.startTime)}</span>
<div class="separator">to</div>
<span class="time">${formatTime(event.endTime)}</span>
</div>
<div class="event-details">
<div class="event-title">
<span class="event-icon">${getTypeIcon(event.type)}</span>
${event.title}
<span class="status-badge status-${event.status}">${event.status}</span>
</div>
<div class="event-location">
<span>📍</span>
${event.location}
</div>
${event.description ? `<div class="event-description">${event.description}</div>` : ''}
${event.assignedDriverId ? `<div class="event-driver"><span>👤</span> Driver: ${event.assignedDriverId}</div>` : ''}
</div>
</div>
`).join('')}
</div>
`).join('')}
<div class="footer">
<p><strong>VIP Coordinator System</strong></p>
<p>Generated on ${new Date().toLocaleDateString([], {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
})}</p>
</div>
</div>
</body>
</html>
`;
printWindow.document.write(printContent);
printWindow.document.close();
printWindow.focus();
setTimeout(() => {
printWindow.print();
printWindow.close();
}, 250);
};
if (loading) {
return <div>Loading VIP details...</div>;
}
if (error || !vip) {
return (
<div>
<h1>Error</h1>
<p>{error || 'VIP not found'}</p>
<Link to="/vips" className="btn">Back to VIP List</Link>
</div>
);
}
const flightInfo = getFlightInfo();
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
VIP Details: {vip.name}
</h1>
<p className="text-slate-600 mt-2">Complete profile and schedule management</p>
</div>
<div className="flex items-center space-x-4">
<button
className="bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 shadow-lg hover:shadow-xl flex items-center gap-2"
onClick={handlePrintSchedule}
>
🖨 Print Schedule
</button>
<Link
to="/vips"
className="bg-gradient-to-r from-slate-500 to-slate-600 hover:from-slate-600 hover:to-slate-700 text-white px-6 py-3 rounded-lg font-medium transition-all duration-200 shadow-lg hover:shadow-xl"
>
Back to VIP List
</Link>
</div>
</div>
</div>
{/* VIP Information Card */}
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-blue-50 to-indigo-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
📋 VIP Information
</h2>
<p className="text-slate-600 mt-1">Personal details and travel arrangements</p>
</div>
<div className="p-8">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div className="bg-slate-50 rounded-xl p-4 border border-slate-200/60">
<div className="text-sm font-medium text-slate-500 mb-1">Name</div>
<div className="text-lg font-bold text-slate-900">{vip.name}</div>
</div>
<div className="bg-slate-50 rounded-xl p-4 border border-slate-200/60">
<div className="text-sm font-medium text-slate-500 mb-1">Organization</div>
<div className="text-lg font-bold text-slate-900">{vip.organization}</div>
</div>
{vip.transportMode === 'flight' && flightInfo ? (
<>
<div className="bg-blue-50 rounded-xl p-4 border border-blue-200/60">
<div className="text-sm font-medium text-blue-600 mb-1">Flight{flightInfo.flights.length > 1 ? 's' : ''}</div>
<div className="text-lg font-bold text-blue-900">{flightInfo.flights.map(f => f.flightNumber).join(' → ')}</div>
</div>
<div className="bg-blue-50 rounded-xl p-4 border border-blue-200/60">
<div className="text-sm font-medium text-blue-600 mb-1">Flight Date</div>
<div className="text-lg font-bold text-blue-900">
{flightInfo.primaryFlight.flightDate ? new Date(flightInfo.primaryFlight.flightDate).toLocaleDateString() : 'TBD'}
</div>
</div>
</>
) : vip.transportMode === 'self-driving' ? (
<>
<div className="bg-green-50 rounded-xl p-4 border border-green-200/60">
<div className="text-sm font-medium text-green-600 mb-1">Transport Mode</div>
<div className="text-lg font-bold text-green-900 flex items-center gap-2">
🚗 Self-Driving
</div>
</div>
<div className="bg-green-50 rounded-xl p-4 border border-green-200/60">
<div className="text-sm font-medium text-green-600 mb-1">Expected Arrival</div>
<div className="text-lg font-bold text-green-900">
{vip.expectedArrival ? new Date(vip.expectedArrival).toLocaleString() : 'TBD'}
</div>
</div>
</>
) : null}
<div className={`rounded-xl p-4 border ${vip.needsAirportPickup ? 'bg-green-50 border-green-200/60' : 'bg-red-50 border-red-200/60'}`}>
<div className={`text-sm font-medium mb-1 ${vip.needsAirportPickup ? 'text-green-600' : 'text-red-600'}`}>Airport Pickup</div>
<div className={`text-lg font-bold flex items-center gap-2 ${vip.needsAirportPickup ? 'text-green-900' : 'text-red-900'}`}>
{vip.needsAirportPickup ? '✅ Required' : '❌ Not Required'}
</div>
</div>
<div className={`rounded-xl p-4 border ${vip.needsVenueTransport ? 'bg-green-50 border-green-200/60' : 'bg-red-50 border-red-200/60'}`}>
<div className={`text-sm font-medium mb-1 ${vip.needsVenueTransport ? 'text-green-600' : 'text-red-600'}`}>Venue Transport</div>
<div className={`text-lg font-bold flex items-center gap-2 ${vip.needsVenueTransport ? 'text-green-900' : 'text-red-900'}`}>
{vip.needsVenueTransport ? '✅ Required' : '❌ Not Required'}
</div>
</div>
</div>
{vip.notes && (
<div className="mt-6">
<div className="text-sm font-medium text-slate-500 mb-2">Special Notes</div>
<div className="bg-amber-50 border border-amber-200 rounded-xl p-4">
<p className="text-amber-800">{vip.notes}</p>
</div>
</div>
)}
{vip.assignedDriverIds && vip.assignedDriverIds.length > 0 && (
<div className="mt-6">
<div className="text-sm font-medium text-slate-500 mb-2">Assigned Drivers</div>
<div className="flex flex-wrap gap-2">
{vip.assignedDriverIds.map(driverId => (
<span
key={driverId}
className="bg-gradient-to-r from-blue-500 to-blue-600 text-white px-4 py-2 rounded-full text-sm font-medium flex items-center gap-2"
>
👤 {driverId}
</span>
))}
</div>
</div>
)}
</div>
</div>
{/* Flight Status */}
{vip.transportMode === 'flight' && flightInfo && (
<div className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden">
<div className="bg-gradient-to-r from-sky-50 to-blue-50 px-8 py-6 border-b border-slate-200/60">
<h2 className="text-xl font-bold text-slate-800 flex items-center gap-2">
Flight Information
</h2>
<p className="text-slate-600 mt-1">Real-time flight status and details</p>
</div>
<div className="p-8 space-y-6">
{flightInfo.flights.map((flight, index) => (
<div key={index} className="bg-slate-50 rounded-xl p-6 border border-slate-200/60">
<h3 className="text-lg font-bold text-slate-900 mb-4">
{index === 0 ? 'Primary Flight' : `Connecting Flight ${index}`}: {flight.flightNumber}
</h3>
<FlightStatus
flightNumber={flight.flightNumber}
flightDate={flight.flightDate}
/>
</div>
))}
</div>
</div>
)}
{/* Schedule Management */}
<div id="schedule-section">
<ScheduleManager vipId={vip.id} vipName={vip.name} />
</div>
</div>
);
};
export default VipDetails;

View File

@@ -1,311 +1,339 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { apiCall } from '../config/api';
import VipForm from '../components/VipForm';
import EditVipForm from '../components/EditVipForm';
import FlightStatus from '../components/FlightStatus';
import { useState, useMemo } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useNavigate } from 'react-router-dom';
import toast from 'react-hot-toast';
import { api } from '@/lib/api';
import { VIP } from '@/types';
import { Plus, Edit, Trash2, Search, X, Calendar } from 'lucide-react';
import { VIPForm, VIPFormData } from '@/components/VIPForm';
import { Loading } from '@/components/Loading';
interface Vip {
id: string;
name: string;
organization: string;
department: 'Office of Development' | 'Admin';
transportMode: 'flight' | 'self-driving';
flightNumber?: string; // Legacy
flightDate?: string; // Legacy
flights?: Array<{
flightNumber: string;
flightDate: string;
segment: number;
}>; // New
expectedArrival?: string;
arrivalTime?: string;
needsAirportPickup?: boolean;
needsVenueTransport: boolean;
notes?: string;
}
const VipList: React.FC = () => {
const [vips, setVips] = useState<Vip[]>([]);
const [loading, setLoading] = useState(true);
export function VIPList() {
const queryClient = useQueryClient();
const navigate = useNavigate();
const [showForm, setShowForm] = useState(false);
const [editingVip, setEditingVip] = useState<Vip | null>(null);
const [editingVIP, setEditingVIP] = useState<VIP | null>(null);
const [isSubmitting, setIsSubmitting] = useState(false);
// Function to extract last name for sorting
const getLastName = (fullName: string) => {
const nameParts = fullName.trim().split(' ');
return nameParts[nameParts.length - 1].toLowerCase();
};
// Search and filter state
const [searchTerm, setSearchTerm] = useState('');
const [selectedDepartments, setSelectedDepartments] = useState<string[]>([]);
const [selectedArrivalModes, setSelectedArrivalModes] = useState<string[]>([]);
// Function to sort VIPs by last name
const sortVipsByLastName = (vipList: Vip[]) => {
return [...vipList].sort((a, b) => {
const lastNameA = getLastName(a.name);
const lastNameB = getLastName(b.name);
return lastNameA.localeCompare(lastNameB);
const { data: vips, isLoading } = useQuery<VIP[]>({
queryKey: ['vips'],
queryFn: async () => {
const { data } = await api.get('/vips');
return data;
},
});
const createMutation = useMutation({
mutationFn: async (data: VIPFormData) => {
await api.post('/vips', data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vips'] });
setShowForm(false);
setIsSubmitting(false);
toast.success('VIP created successfully');
},
onError: (error: any) => {
console.error('[VIP] Failed to create:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to create VIP');
},
});
const updateMutation = useMutation({
mutationFn: async ({ id, data }: { id: string; data: VIPFormData }) => {
await api.patch(`/vips/${id}`, data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vips'] });
setShowForm(false);
setEditingVIP(null);
setIsSubmitting(false);
toast.success('VIP updated successfully');
},
onError: (error: any) => {
console.error('[VIP] Failed to update:', error);
setIsSubmitting(false);
toast.error(error.response?.data?.message || 'Failed to update VIP');
},
});
const deleteMutation = useMutation({
mutationFn: async (id: string) => {
await api.delete(`/vips/${id}`);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['vips'] });
toast.success('VIP deleted successfully');
},
onError: (error: any) => {
console.error('[VIP] Failed to delete:', error);
toast.error(error.response?.data?.message || 'Failed to delete VIP');
},
});
// Filter VIPs based on search and filters
const filteredVIPs = useMemo(() => {
if (!vips) return [];
return vips.filter((vip) => {
// Search by name
const matchesSearch = searchTerm === '' ||
vip.name.toLowerCase().includes(searchTerm.toLowerCase());
// Filter by department
const matchesDepartment = selectedDepartments.length === 0 ||
selectedDepartments.includes(vip.department);
// Filter by arrival mode
const matchesArrivalMode = selectedArrivalModes.length === 0 ||
selectedArrivalModes.includes(vip.arrivalMode);
return matchesSearch && matchesDepartment && matchesArrivalMode;
});
};
}, [vips, searchTerm, selectedDepartments, selectedArrivalModes]);
useEffect(() => {
const fetchVips = async () => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
const data = await response.json();
const sortedVips = sortVipsByLastName(data);
setVips(sortedVips);
} else {
console.error('Failed to fetch VIPs:', response.status);
}
} catch (error) {
console.error('Error fetching VIPs:', error);
} finally {
setLoading(false);
}
};
fetchVips();
}, []);
const handleAddVip = async (vipData: any) => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(vipData),
});
if (response.ok) {
const newVip = await response.json();
setVips(prev => sortVipsByLastName([...prev, newVip]));
setShowForm(false);
} else {
console.error('Failed to add VIP:', response.status);
}
} catch (error) {
console.error('Error adding VIP:', error);
}
};
const handleEditVip = async (vipData: any) => {
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vipData.id}`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(vipData),
});
if (response.ok) {
const updatedVip = await response.json();
setVips(prev => sortVipsByLastName(prev.map(vip => vip.id === updatedVip.id ? updatedVip : vip)));
setEditingVip(null);
} else {
console.error('Failed to update VIP:', response.status);
}
} catch (error) {
console.error('Error updating VIP:', error);
}
};
const handleDeleteVip = async (vipId: string) => {
if (!confirm('Are you sure you want to delete this VIP?')) {
return;
}
try {
const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vipId}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (response.ok) {
setVips(prev => prev.filter(vip => vip.id !== vipId));
} else {
console.error('Failed to delete VIP:', response.status);
}
} catch (error) {
console.error('Error deleting VIP:', error);
}
};
if (loading) {
return (
<div className="flex justify-center items-center min-h-64">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4">
<div className="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
<span className="text-lg font-medium text-slate-700">Loading VIPs...</span>
</div>
</div>
const handleDepartmentToggle = (department: string) => {
setSelectedDepartments((prev) =>
prev.includes(department)
? prev.filter((d) => d !== department)
: [...prev, department]
);
};
const handleArrivalModeToggle = (mode: string) => {
setSelectedArrivalModes((prev) =>
prev.includes(mode)
? prev.filter((m) => m !== mode)
: [...prev, mode]
);
};
const handleClearFilters = () => {
setSearchTerm('');
setSelectedDepartments([]);
setSelectedArrivalModes([]);
};
const handleAdd = () => {
setEditingVIP(null);
setShowForm(true);
};
const handleEdit = (vip: VIP) => {
setEditingVIP(vip);
setShowForm(true);
};
const handleDelete = (id: string, name: string) => {
if (confirm(`Delete VIP "${name}"? This action cannot be undone.`)) {
deleteMutation.mutate(id);
}
};
const handleSubmit = (data: VIPFormData) => {
setIsSubmitting(true);
if (editingVIP) {
updateMutation.mutate({ id: editingVIP.id, data });
} else {
createMutation.mutate(data);
}
};
const handleCancel = () => {
setShowForm(false);
setEditingVIP(null);
setIsSubmitting(false);
};
if (isLoading) {
return <Loading message="Loading VIPs..." />;
}
return (
<div className="space-y-8">
{/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center">
<div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
VIP Management
</h1>
<p className="text-slate-600 mt-2">Manage VIP profiles and travel arrangements</p>
<div>
<div className="flex justify-between items-center mb-6">
<h1 className="text-3xl font-bold text-gray-900">VIPs</h1>
<button
onClick={handleAdd}
className="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md text-white bg-primary hover:bg-primary/90"
>
<Plus className="h-4 w-4 mr-2" />
Add VIP
</button>
</div>
{/* Search and Filter Section */}
<div className="bg-white shadow rounded-lg p-4 mb-6">
<div className="flex flex-col gap-4">
{/* Search */}
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 text-gray-400" />
<input
type="text"
placeholder="Search by name..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-primary focus:border-primary"
/>
</div>
{/* Filters */}
<div className="flex flex-wrap gap-6">
{/* Department Filters */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Department
</label>
<div className="flex flex-col gap-2">
<label className="inline-flex items-center">
<input
type="checkbox"
checked={selectedDepartments.includes('OFFICE_OF_DEVELOPMENT')}
onChange={() => handleDepartmentToggle('OFFICE_OF_DEVELOPMENT')}
className="rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="ml-2 text-sm text-gray-700">Office of Development</span>
</label>
<label className="inline-flex items-center">
<input
type="checkbox"
checked={selectedDepartments.includes('ADMIN')}
onChange={() => handleDepartmentToggle('ADMIN')}
className="rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="ml-2 text-sm text-gray-700">Admin</span>
</label>
</div>
</div>
{/* Arrival Mode Filters */}
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">
Arrival Mode
</label>
<div className="flex flex-col gap-2">
<label className="inline-flex items-center">
<input
type="checkbox"
checked={selectedArrivalModes.includes('FLIGHT')}
onChange={() => handleArrivalModeToggle('FLIGHT')}
className="rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="ml-2 text-sm text-gray-700">Flight</span>
</label>
<label className="inline-flex items-center">
<input
type="checkbox"
checked={selectedArrivalModes.includes('SELF_DRIVING')}
onChange={() => handleArrivalModeToggle('SELF_DRIVING')}
className="rounded border-gray-300 text-primary focus:ring-primary"
/>
<span className="ml-2 text-sm text-gray-700">Self Driving</span>
</label>
</div>
</div>
</div>
{/* Results count and Clear Filters */}
<div className="flex items-center justify-between">
<div className="text-sm text-gray-600">
Showing {filteredVIPs.length} of {vips?.length || 0} VIPs
</div>
{(searchTerm || selectedDepartments.length > 0 || selectedArrivalModes.length > 0) && (
<button
onClick={handleClearFilters}
className="inline-flex items-center px-3 py-1 text-sm text-gray-600 hover:text-gray-900 border border-gray-300 rounded-md hover:bg-gray-50"
>
<X className="h-4 w-4 mr-1" />
Clear Filters
</button>
)}
</div>
<button
className="btn btn-primary"
onClick={() => setShowForm(true)}
>
Add New VIP
</button>
</div>
</div>
{/* VIP List */}
{vips.length === 0 ? (
<div className="bg-white rounded-2xl shadow-lg p-12 border border-slate-200/60 text-center">
<div className="w-16 h-16 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-4">
<div className="w-8 h-8 bg-slate-300 rounded-full"></div>
</div>
<h3 className="text-lg font-semibold text-slate-800 mb-2">No VIPs Found</h3>
<p className="text-slate-600 mb-6">Get started by adding your first VIP</p>
<button
className="btn btn-primary"
onClick={() => setShowForm(true)}
>
Add New VIP
</button>
</div>
) : (
<div className="space-y-4">
{vips.map((vip) => (
<div key={vip.id} className="bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden hover:shadow-xl transition-shadow duration-200">
<div className="p-6">
<div className="flex justify-between items-start">
<div className="flex-1">
<div className="flex items-center gap-3 mb-3">
<h3 className="text-xl font-bold text-slate-900">{vip.name}</h3>
<span className="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-0.5 rounded-full">
{vip.department}
</span>
</div>
<p className="text-slate-600 text-sm mb-4">{vip.organization}</p>
{/* Transport Information */}
<div className="bg-slate-50 rounded-lg p-4 mb-4">
{vip.transportMode === 'flight' ? (
<div className="space-y-2">
<div className="flex items-center gap-2 text-sm">
<span className="font-medium text-slate-700">Flight:</span>
<span className="text-slate-600">
{vip.flights && vip.flights.length > 0 ?
vip.flights.map(f => f.flightNumber).join(' → ') :
vip.flightNumber || 'No flight'}
</span>
</div>
<div className="flex items-center gap-2 text-sm">
<span className="font-medium text-slate-700">Airport Pickup:</span>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
vip.needsAirportPickup
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}>
{vip.needsAirportPickup ? 'Required' : 'Not needed'}
</span>
</div>
</div>
) : (
<div className="flex items-center gap-2 text-sm">
<span className="font-medium text-slate-700">Self-driving, Expected:</span>
<span className="text-slate-600">
{vip.expectedArrival ? new Date(vip.expectedArrival).toLocaleString() : 'TBD'}
</span>
</div>
)}
<div className="flex items-center gap-2 text-sm mt-2">
<span className="font-medium text-slate-700">Venue Transport:</span>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
vip.needsVenueTransport
? 'bg-blue-100 text-blue-800'
: 'bg-gray-100 text-gray-800'
}`}>
{vip.needsVenueTransport ? 'Required' : 'Not needed'}
</span>
</div>
</div>
</div>
{/* Action Buttons */}
<div className="flex flex-col gap-2 ml-6">
<Link
to={`/vips/${vip.id}`}
className="btn btn-success text-center"
<div className="bg-white shadow rounded-lg overflow-hidden">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Organization
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Department
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Arrival Mode
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{filteredVIPs.map((vip) => (
<tr key={vip.id}>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900">
{vip.name}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.organization || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.department}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
{vip.arrivalMode}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm">
<div className="flex gap-2">
<button
onClick={() => navigate(`/vips/${vip.id}/schedule`)}
className="inline-flex items-center px-3 py-1 text-blue-600 hover:text-blue-800"
title="View Schedule"
>
View Details
</Link>
<button
className="btn btn-secondary"
onClick={() => setEditingVip(vip)}
<Calendar className="h-4 w-4 mr-1" />
Schedule
</button>
<button
onClick={() => handleEdit(vip)}
className="inline-flex items-center px-3 py-1 text-primary hover:text-primary/80"
>
<Edit className="h-4 w-4 mr-1" />
Edit
</button>
<button
className="btn btn-danger"
onClick={() => handleDeleteVip(vip.id)}
<button
onClick={() => handleDelete(vip.id, vip.name)}
className="inline-flex items-center px-3 py-1 text-red-600 hover:text-red-800"
>
<Trash2 className="h-4 w-4 mr-1" />
Delete
</button>
</div>
</div>
{/* Flight Status */}
{vip.transportMode === 'flight' && vip.flightNumber && (
<div className="mt-4 pt-4 border-t border-slate-200">
<FlightStatus flightNumber={vip.flightNumber} />
</div>
)}
</div>
</div>
))}
</div>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* Modals */}
{showForm && (
<VipForm
onSubmit={handleAddVip}
onCancel={() => setShowForm(false)}
/>
)}
{editingVip && (
<EditVipForm
vip={{...editingVip, notes: editingVip.notes || ''}}
onSubmit={handleEditVip}
onCancel={() => setEditingVip(null)}
<VIPForm
vip={editingVIP}
onSubmit={handleSubmit}
onCancel={handleCancel}
isSubmitting={isSubmitting}
/>
)}
</div>
);
};
export default VipList;
}