Initial commit - Current state of vip-coordinator

This commit is contained in:
2026-01-24 09:30:26 +01:00
commit aa900505b9
96 changed files with 31868 additions and 0 deletions

View File

@@ -0,0 +1,825 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { apiCall, API_BASE_URL } from '../config/api';
import { generateTestVips, getTestOrganizations, generateVipSchedule } from '../utils/testVipData';
interface ApiKeys {
aviationStackKey?: string;
googleMapsKey?: string;
twilioKey?: string;
auth0Domain?: string;
auth0ClientId?: string;
auth0ClientSecret?: string;
auth0Audience?: string;
}
interface SystemSettings {
defaultPickupLocation?: string;
defaultDropoffLocation?: string;
timeZone?: string;
notificationsEnabled?: boolean;
}
const AdminDashboard: React.FC = () => {
const navigate = useNavigate();
const [apiKeys, setApiKeys] = useState<ApiKeys>({});
const [systemSettings, setSystemSettings] = useState<SystemSettings>({});
const [testResults, setTestResults] = useState<{ [key: string]: string }>({});
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [saveStatus, setSaveStatus] = useState<string | null>(null);
const [savedKeys, setSavedKeys] = useState<{ [key: string]: boolean }>({});
const [maskedKeyHints, setMaskedKeyHints] = useState<{ [key: string]: string }>({});
const [testDataLoading, setTestDataLoading] = useState(false);
const [testDataStatus, setTestDataStatus] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const buildAuthHeaders = (includeJson = false) => {
const headers: Record<string, string> = {};
const token = typeof window !== 'undefined' ? localStorage.getItem('authToken') : null;
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
if (includeJson) {
headers['Content-Type'] = 'application/json';
}
return headers;
};
const loadSettings = async () => {
try {
setLoading(true);
setError(null);
const response = await apiCall('/api/admin/settings', {
headers: buildAuthHeaders()
});
if (response.ok) {
const data = await response.json();
const saved: { [key: string]: boolean } = {};
const maskedHints: { [key: string]: string } = {};
const cleanedApiKeys: ApiKeys = {};
if (data.apiKeys) {
Object.entries(data.apiKeys).forEach(([key, value]) => {
if (value && (value as string).startsWith('***')) {
saved[key] = true;
maskedHints[key] = value as string;
} else if (value) {
cleanedApiKeys[key as keyof ApiKeys] = value as string;
}
});
}
setSavedKeys(saved);
setMaskedKeyHints(maskedHints);
setApiKeys(cleanedApiKeys);
setSystemSettings(data.systemSettings || {});
} else if (response.status === 403) {
setError('You need administrator access to view this page.');
} else if (response.status === 401) {
setError('Authentication required. Please sign in again.');
} else {
setError('Failed to load admin settings.');
}
} catch (err) {
console.error('Failed to load settings:', err);
setError('Failed to load admin settings.');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadSettings();
}, []);
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 }));
setMaskedKeyHints(prev => {
const next = { ...prev };
delete next[key];
return next;
});
}
};
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 apiCall(`/api/admin/test-api/${apiType}`, {
method: 'POST',
headers: buildAuthHeaders(true),
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 () => {
setSaving(true);
setSaveStatus(null);
try {
const response = await apiCall('/api/admin/settings', {
method: 'POST',
headers: buildAuthHeaders(true),
body: JSON.stringify({
apiKeys,
systemSettings
})
});
if (response.ok) {
setSaveStatus('Settings saved successfully!');
// Refresh the latest settings so saved states/labels stay accurate
await loadSettings();
setTimeout(() => setSaveStatus(null), 3000);
} else {
setSaveStatus('Failed to save settings');
}
} catch (error) {
setSaveStatus('Error saving settings');
} finally {
setSaving(false);
}
};
const handleLogout = () => {
localStorage.removeItem('authToken');
navigate('/');
window.location.reload();
};
// 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.name, 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 (loading) {
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 flex items-center space-x-4 border border-slate-200/60">
<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 admin settings...</span>
</div>
</div>
);
}
if (error) {
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-xl border border-rose-200/70">
<h2 className="text-2xl font-bold text-rose-700 mb-4">Admin access required</h2>
<p className="text-slate-600 mb-6">{error}</p>
<button
className="btn btn-primary"
onClick={() => navigate('/')}
>
Return to dashboard
</button>
</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>
<input
type="password"
placeholder={savedKeys.aviationStackKey && maskedKeyHints.aviationStackKey
? `Saved (${maskedKeyHints.aviationStackKey.slice(-4)})`
: 'Enter AviationStack API key'}
value={apiKeys.aviationStackKey || ''}
onChange={(e) => handleApiKeyChange('aviationStackKey', e.target.value)}
className="form-input"
/>
{savedKeys.aviationStackKey && maskedKeyHints.aviationStackKey && !apiKeys.aviationStackKey && (
<p className="text-xs text-slate-500 mt-1">
Currently saved key ends with {maskedKeyHints.aviationStackKey.slice(-4)}. Enter a new value to replace it.
</p>
)}
<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>
{/* Auth0 Credentials */}
<div className="form-section">
<div className="form-section-header">
<h3 className="form-section-title">Auth0 Configuration</h3>
{(savedKeys.auth0Domain || savedKeys.auth0ClientId || savedKeys.auth0ClientSecret) && (
<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">Auth0 Domain</label>
<input
type="text"
placeholder={savedKeys.auth0Domain && maskedKeyHints.auth0Domain
? `Saved (${maskedKeyHints.auth0Domain.slice(-4)})`
: 'e.g. dev-1234abcd.us.auth0.com'}
value={apiKeys.auth0Domain || ''}
onChange={(e) => handleApiKeyChange('auth0Domain', e.target.value)}
className="form-input"
/>
</div>
<div className="form-group">
<label className="form-label">Client ID</label>
<input
type="password"
placeholder={savedKeys.auth0ClientId && maskedKeyHints.auth0ClientId
? `Saved (${maskedKeyHints.auth0ClientId.slice(-4)})`
: 'Enter Auth0 application Client ID'}
value={apiKeys.auth0ClientId || ''}
onChange={(e) => handleApiKeyChange('auth0ClientId', e.target.value)}
className="form-input"
/>
{savedKeys.auth0ClientId && maskedKeyHints.auth0ClientId && !apiKeys.auth0ClientId && (
<p className="text-xs text-slate-500 mt-1">
Saved client ID ends with {maskedKeyHints.auth0ClientId.slice(-4)}. Provide a new ID to update it.
</p>
)}
</div>
<div className="form-group">
<label className="form-label">Client Secret</label>
<input
type="password"
placeholder={savedKeys.auth0ClientSecret && maskedKeyHints.auth0ClientSecret
? `Saved (${maskedKeyHints.auth0ClientSecret.slice(-4)})`
: 'Enter Auth0 application Client Secret'}
value={apiKeys.auth0ClientSecret || ''}
onChange={(e) => handleApiKeyChange('auth0ClientSecret', e.target.value)}
className="form-input"
/>
{savedKeys.auth0ClientSecret && maskedKeyHints.auth0ClientSecret && !apiKeys.auth0ClientSecret && (
<p className="text-xs text-slate-500 mt-1">
Saved client secret ends with {maskedKeyHints.auth0ClientSecret.slice(-4)}. Provide a new secret to rotate it.
</p>
)}
</div>
<div className="form-group">
<label className="form-label">API Audience (Identifier)</label>
<input
type="text"
placeholder={apiKeys.auth0Audience || 'https://your-api-identifier'}
value={apiKeys.auth0Audience || ''}
onChange={(e) => handleApiKeyChange('auth0Audience', e.target.value)}
className="form-input"
/>
<p className="text-xs text-slate-500 mt-1">
Create an API in Auth0 and use its Identifier here (e.g. https://vip-coordinator-api).
</p>
</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>Sign in to the Auth0 Dashboard</li>
<li>Create a <strong>Single Page Application</strong> for the frontend</li>
<li>Set Allowed Callback URL to <code>https://bsa.madeamess.online/auth/callback</code></li>
<li>Set Allowed Logout URL to <code>https://bsa.madeamess.online/</code></li>
<li>Set Allowed Web Origins to <code>https://bsa.madeamess.online</code></li>
<li>Create an <strong>API</strong> in Auth0 for the backend and use its Identifier as the audience</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(`${API_BASE_URL}/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={saving}
>
{saving ? '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

@@ -0,0 +1,378 @@
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { apiCall } from '../config/api';
interface ScheduleEvent {
id: string;
title: string;
location: string;
startTime: string;
endTime: string;
status: 'scheduled' | 'in-progress' | 'completed' | 'cancelled';
type: 'transport' | 'meeting' | 'event' | 'meal' | 'accommodation';
}
interface Vip {
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;
}
interface Driver {
id: string;
name: string;
phone: string;
currentLocation: { lat: number; lng: number };
assignedVipIds: string[];
}
const Dashboard: React.FC = () => {
const [vips, setVips] = useState<Vip[]>([]);
const [drivers, setDrivers] = useState<Driver[]>([]);
const [loading, setLoading] = useState(true);
// 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 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 formatTime = (timeString: string) => {
return new Date(timeString).toLocaleString([], {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit'
});
};
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);
}
};
fetchData();
}, []);
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>
);
}
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>
<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>
</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"
>
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>
</div>
</div>
</div>
);
};
export default Dashboard;

View File

@@ -0,0 +1,763 @@
import React, { 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 formatDate = (timeString: string) => {
return new Date(timeString).toLocaleDateString([], {
weekday: 'short',
month: 'short',
day: 'numeric'
});
};
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

@@ -0,0 +1,293 @@
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';
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);
const [showForm, setShowForm] = useState(false);
const [editingDriver, setEditingDriver] = useState<Driver | null>(null);
// Function to extract last name for sorting
const getLastName = (fullName: string) => {
const nameParts = fullName.trim().split(' ');
return nameParts[nameParts.length - 1].toLowerCase();
};
// 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);
});
};
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 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 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);
}
};
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>
);
}
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>
{/* 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="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)}
>
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)}
>
Delete
</button>
</div>
</div>
</div>
</div>
))}
</div>
)}
{/* Modals */}
{showForm && (
<DriverForm
onSubmit={handleAddDriver}
onCancel={() => setShowForm(false)}
/>
)}
{editingDriver && (
<EditDriverForm
driver={editingDriver}
onSubmit={handleEditDriver}
onCancel={() => setEditingDriver(null)}
/>
)}
</div>
);
};
export default DriverList;

View File

@@ -0,0 +1,683 @@
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

@@ -0,0 +1,311 @@
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';
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);
const [showForm, setShowForm] = useState(false);
const [editingVip, setEditingVip] = useState<Vip | null>(null);
// Function to extract last name for sorting
const getLastName = (fullName: string) => {
const nameParts = fullName.trim().split(' ');
return nameParts[nameParts.length - 1].toLowerCase();
};
// 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);
});
};
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>
);
}
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>
<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"
>
View Details
</Link>
<button
className="btn btn-secondary"
onClick={() => setEditingVip(vip)}
>
Edit
</button>
<button
className="btn btn-danger"
onClick={() => handleDeleteVip(vip.id)}
>
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>
)}
{/* Modals */}
{showForm && (
<VipForm
onSubmit={handleAddVip}
onCancel={() => setShowForm(false)}
/>
)}
{editingVip && (
<EditVipForm
vip={{...editingVip, notes: editingVip.notes || ''}}
onSubmit={handleEditVip}
onCancel={() => setEditingVip(null)}
/>
)}
</div>
);
};
export default VipList;