Backup: 2025-06-08 00:29 - User and admin online ready for dockerhub

[Restore from backup: vip-coordinator-backup-2025-06-08-00-29-user and admin online ready for dockerhub]
This commit is contained in:
2025-06-08 00:29:00 +02:00
parent 035f76fdd3
commit 715404d04f
33 changed files with 3676 additions and 3527 deletions

View File

@@ -1,26 +1,27 @@
# VIP Coordinator Environment Configuration
# Copy this file to .env and update the values for your deployment
# Database Configuration # Database Configuration
DB_PASSWORD=VipCoord2025SecureDB POSTGRES_DB=vip_coordinator
POSTGRES_USER=vip_user
POSTGRES_PASSWORD=your_secure_password_here
DATABASE_URL=postgresql://vip_user:your_secure_password_here@db:5432/vip_coordinator
# Domain Configuration (Update these for your domain) # Redis Configuration
DOMAIN=your-domain.com REDIS_URL=redis://redis:6379
VITE_API_URL=https://api.your-domain.com
# Google OAuth Configuration (Get these from Google Cloud Console) # Google OAuth Configuration
GOOGLE_CLIENT_ID=your-google-client-id.apps.googleusercontent.com GOOGLE_CLIENT_ID=your_google_client_id_here
GOOGLE_CLIENT_SECRET=your-google-client-secret GOOGLE_CLIENT_SECRET=your_google_client_secret_here
GOOGLE_REDIRECT_URI=https://api.your-domain.com/auth/google/callback GOOGLE_REDIRECT_URI=http://localhost:3000/auth/google/callback
FRONTEND_URL=http://localhost:5173
# Frontend URL # JWT Configuration
FRONTEND_URL=https://your-domain.com JWT_SECRET=your_jwt_secret_here_minimum_32_characters_long
# Admin Configuration # Environment
ADMIN_PASSWORD=ChangeThisSecurePassword NODE_ENV=development
# Flight API Configuration (Optional) # API Configuration
AVIATIONSTACK_API_KEY=your-aviationstack-api-key API_PORT=3000
# Port Configuration # Frontend Configuration (for production)
PORT=3000 VITE_API_URL=http://localhost:3000/api
VITE_GOOGLE_CLIENT_ID=your_google_client_id_here

View File

@@ -1,266 +1,232 @@
# 🚀 VIP Coordinator - Docker Hub Deployment Guide # 🚀 VIP Coordinator - Docker Hub Deployment Guide
Deploy the VIP Coordinator application on any system with Docker in just a few steps! ## 📋 Quick Start
## 📋 Prerequisites ### Prerequisites
- Docker and Docker Compose installed
- Google Cloud Console account (for OAuth setup)
- **Docker** and **Docker Compose** installed on your system ### 1. Download and Configure
- **Domain name** (optional, can run on localhost for testing)
- **Google Cloud Console** account for OAuth setup
## 🚀 Quick Start (5 Minutes)
### 1. Download Deployment Files
Create a new directory and download these files:
```bash ```bash
mkdir vip-coordinator # Pull the project
git clone <your-dockerhub-repo-url>
cd vip-coordinator cd vip-coordinator
# Download the deployment files # Copy environment template
curl -O https://raw.githubusercontent.com/your-repo/vip-coordinator/main/docker-compose.yml cp .env.example .env.prod
curl -O https://raw.githubusercontent.com/your-repo/vip-coordinator/main/.env.example
# Edit with your configuration
nano .env.prod
``` ```
### 2. Configure Environment ### 2. Required Configuration
Edit `.env.prod` with your values:
```bash ```bash
# Copy the environment template # Database Configuration
cp .env.example .env DB_PASSWORD=your-secure-database-password
# Edit the configuration (use your preferred editor) # Domain Configuration (update with your domains)
nano .env DOMAIN=your-domain.com
VITE_API_URL=https://api.your-domain.com/api
# Google OAuth Configuration (from Google Cloud Console)
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_REDIRECT_URI=https://api.your-domain.com/auth/google/callback
# Frontend URL
FRONTEND_URL=https://your-domain.com
# Admin Configuration
ADMIN_PASSWORD=your-secure-admin-password
``` ```
**Required Changes in `.env`:** ### 3. Google OAuth Setup
- `DB_PASSWORD`: Change to a secure password
- `ADMIN_PASSWORD`: Change to a secure password
- `GOOGLE_CLIENT_ID`: Your Google OAuth Client ID
- `GOOGLE_CLIENT_SECRET`: Your Google OAuth Client Secret
**For Production Deployment:** 1. **Create Google Cloud Project**:
- `DOMAIN`: Your domain name (e.g., `mycompany.com`) - Go to [Google Cloud Console](https://console.cloud.google.com/)
- `VITE_API_URL`: Your API URL (e.g., `https://api.mycompany.com`) - Create a new project
- `GOOGLE_REDIRECT_URI`: Your callback URL (e.g., `https://api.mycompany.com/auth/google/callback`)
- `FRONTEND_URL`: Your frontend URL (e.g., `https://mycompany.com`)
### 3. Set Up Google OAuth 2. **Enable Google+ API**:
- Navigate to "APIs & Services" > "Library"
- Search for "Google+ API" and enable it
1. Go to [Google Cloud Console](https://console.cloud.google.com/) 3. **Create OAuth Credentials**:
2. Create a new project or select existing one - Go to "APIs & Services" > "Credentials"
3. Enable the Google+ API - Click "Create Credentials" > "OAuth 2.0 Client IDs"
4. Go to "Credentials" → "Create Credentials" → "OAuth 2.0 Client IDs" - Application type: "Web application"
5. Set application type to "Web application" - Authorized redirect URIs: `https://api.your-domain.com/auth/google/callback`
6. Add authorized redirect URIs:
- For localhost: `http://localhost:3000/auth/google/callback`
- For production: `https://api.your-domain.com/auth/google/callback`
7. Copy the Client ID and Client Secret to your `.env` file
### 4. Deploy the Application ### 4. Deploy
```bash ```bash
# Pull the latest images from Docker Hub
docker-compose pull
# Start the application # Start the application
docker-compose up -d docker-compose -f docker-compose.prod.yml up -d
# Check status # Check status
docker-compose ps docker-compose -f docker-compose.prod.yml ps
# View logs
docker-compose -f docker-compose.prod.yml logs -f
``` ```
### 5. Access the Application ### 5. Access Your Application
- **Local Development**: http://localhost - **Frontend**: http://your-domain.com (or http://localhost if running locally)
- **Production**: https://your-domain.com - **Backend API**: http://api.your-domain.com (or http://localhost:3000)
- **API Documentation**: http://api.your-domain.com/api-docs.html
## 🔧 Configuration Options ### 6. First Login
- Visit your frontend URL
- Click "Continue with Google"
- The first user becomes the system administrator
- Subsequent users need admin approval
## 🔧 Configuration Details
### Environment Variables ### Environment Variables
| Variable | Description | Required | Default | | Variable | Required | Description | Example |
|----------|-------------|----------|---------| |----------|----------|-------------|---------|
| `DB_PASSWORD` | PostgreSQL database password | ✅ | - | | `DB_PASSWORD` | ✅ | PostgreSQL database password | `SecurePass123!` |
| `ADMIN_PASSWORD` | Admin interface password | ✅ | - | | `DOMAIN` | ✅ | Your main domain | `example.com` |
| `GOOGLE_CLIENT_ID` | Google OAuth Client ID | ✅ | - | | `VITE_API_URL` | ✅ | API endpoint URL | `https://api.example.com/api` |
| `GOOGLE_CLIENT_SECRET` | Google OAuth Client Secret | ✅ | - | | `GOOGLE_CLIENT_ID` | ✅ | Google OAuth client ID | `123456789-abc.apps.googleusercontent.com` |
| `GOOGLE_REDIRECT_URI` | OAuth callback URL | ✅ | - | | `GOOGLE_CLIENT_SECRET` | ✅ | Google OAuth client secret | `GOCSPX-abcdef123456` |
| `FRONTEND_URL` | Frontend application URL | ✅ | - | | `GOOGLE_REDIRECT_URI` | ✅ | OAuth redirect URI | `https://api.example.com/auth/google/callback` |
| `VITE_API_URL` | Backend API URL | ✅ | - | | `FRONTEND_URL` | ✅ | Frontend URL | `https://example.com` |
| `DOMAIN` | Your domain name | ❌ | localhost | | `ADMIN_PASSWORD` | ✅ | Admin panel password | `AdminPass123!` |
| `AVIATIONSTACK_API_KEY` | Flight data API key | ❌ | - |
| `PORT` | Backend port | ❌ | 3000 |
### Ports ### Optional Configuration
- **Frontend**: Port 80 (HTTP) - **AviationStack API Key**: Configure via admin interface for flight tracking
- **Backend**: Port 3000 (API) - **Custom Ports**: Modify docker-compose.prod.yml if needed
- **Database**: Internal only (PostgreSQL)
- **Redis**: Internal only (Cache)
## 🌐 Production Deployment ## 🏗️ Architecture
### With Reverse Proxy (Recommended) ### Services
- **Frontend**: React app served by Nginx (Port 80)
- **Backend**: Node.js API server (Port 3000)
- **Database**: PostgreSQL with automatic schema setup
- **Redis**: Caching and real-time updates
For production, use a reverse proxy like Nginx or Traefik: ### Security Features
- JWT tokens with automatic key rotation (24-hour cycle)
- Non-root containers for enhanced security
- Health checks for all services
- Secure headers and CORS configuration
```nginx ## 🔐 Security Best Practices
# Nginx configuration example
server {
listen 80;
server_name your-domain.com;
return 301 https://$server_name$request_uri;
}
server { ### Required Changes
listen 443 ssl; 1. **Change default passwords**: Update `DB_PASSWORD` and `ADMIN_PASSWORD`
server_name your-domain.com; 2. **Use HTTPS**: Configure SSL/TLS certificates for production
3. **Secure domains**: Use your own domains, not the examples
4. **Google OAuth**: Create your own OAuth credentials
# SSL configuration ### Recommended
ssl_certificate /path/to/cert.pem; - Use strong, unique passwords (20+ characters)
ssl_certificate_key /path/to/key.pem; - Enable firewall rules for your server
- Regular security updates for the host system
- Monitor logs for suspicious activity
location / { ## 🚨 Troubleshooting
proxy_pass http://localhost:80;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
server {
listen 443 ssl;
server_name api.your-domain.com;
# SSL configuration
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
```
### SSL/HTTPS Setup
1. Obtain SSL certificates (Let's Encrypt recommended)
2. Configure your reverse proxy for HTTPS
3. Update your `.env` file with HTTPS URLs
4. Update Google OAuth redirect URIs to use HTTPS
## 🔍 Troubleshooting
### Common Issues ### Common Issues
**1. OAuth Login Fails** **OAuth Not Working**:
- Check Google OAuth configuration
- Verify redirect URIs match exactly
- Ensure HTTPS is used in production
**2. Database Connection Issues**
- Check if PostgreSQL container is healthy: `docker-compose ps`
- Verify database password in `.env`
**3. Frontend Can't Reach Backend**
- Verify `VITE_API_URL` in `.env` matches your backend URL
- Check if backend is accessible: `curl http://localhost:3000/health`
**4. Permission Denied Errors**
- Ensure Docker has proper permissions
- Check file ownership and permissions
### Viewing Logs
```bash ```bash
# View all logs # Check Google OAuth configuration
docker-compose logs docker-compose -f docker-compose.prod.yml logs backend | grep -i oauth
# View specific service logs # Verify redirect URI matches exactly in Google Console
docker-compose logs backend ```
docker-compose logs frontend
docker-compose logs db
# Follow logs in real-time **Database Connection Error**:
docker-compose logs -f backend ```bash
# Check database status
docker-compose -f docker-compose.prod.yml ps db
# View database logs
docker-compose -f docker-compose.prod.yml logs db
```
**Frontend Can't Connect to Backend**:
```bash
# Verify backend is running
curl http://localhost:3000/api/health
# Check CORS configuration
docker-compose -f docker-compose.prod.yml logs backend | grep -i cors
``` ```
### Health Checks ### Health Checks
```bash ```bash
# Check container status # Check all service health
docker-compose ps docker-compose -f docker-compose.prod.yml ps
# Check backend health # Test API health endpoint
curl http://localhost:3000/health curl http://localhost:3000/api/health
# Check frontend # Test frontend
curl http://localhost/ curl http://localhost/
``` ```
## 🔄 Updates
To update to the latest version:
```bash
# Pull latest images
docker-compose pull
# Restart with new images
docker-compose up -d
```
## 🛑 Stopping the Application
```bash
# Stop all services
docker-compose down
# Stop and remove volumes (⚠️ This will delete all data)
docker-compose down -v
```
## 📊 Monitoring
### Container Health
All containers include health checks:
- **Backend**: API endpoint health check
- **Database**: PostgreSQL connection check
- **Redis**: Redis ping check
- **Frontend**: Nginx status check
### Logs ### Logs
Logs are automatically rotated and can be viewed using Docker commands. ```bash
# View all logs
docker-compose -f docker-compose.prod.yml logs
## 🔐 Security Considerations # Follow specific service logs
docker-compose -f docker-compose.prod.yml logs -f backend
docker-compose -f docker-compose.prod.yml logs -f frontend
docker-compose -f docker-compose.prod.yml logs -f db
```
1. **Change default passwords** in `.env` ## 🔄 Updates and Maintenance
2. **Use HTTPS** in production
3. **Secure your server** with firewall rules
4. **Regular backups** of database volumes
5. **Keep Docker images updated**
## 📞 Support ### Updating the Application
If you encounter issues: ```bash
# Pull latest changes
git pull origin main
1. Check the troubleshooting section above # Rebuild and restart
2. Review container logs docker-compose -f docker-compose.prod.yml down
3. Verify your configuration docker-compose -f docker-compose.prod.yml up -d --build
4. Check GitHub issues for known problems ```
## 🎉 Success! ### Backup Database
Once deployed, you'll have a fully functional VIP Coordinator system with: ```bash
- ✅ Google OAuth authentication # Create database backup
- ✅ Mobile-friendly interface docker-compose -f docker-compose.prod.yml exec db pg_dump -U postgres vip_coordinator > backup.sql
- ✅ Real-time scheduling
- ✅ User management
- ✅ Automatic backups
- ✅ Health monitoring
The first user to log in will automatically become the system administrator. # Restore from backup
docker-compose -f docker-compose.prod.yml exec -T db psql -U postgres vip_coordinator < backup.sql
```
## 📚 Additional Resources
- **API Documentation**: Available at `/api-docs.html` when running
- **User Roles**: Administrator, Coordinator, Driver
- **Flight Tracking**: Configure AviationStack API key in admin panel
- **Support**: Check GitHub issues for common problems
## 🆘 Getting Help
1. Check this deployment guide
2. Review the troubleshooting section
3. Check Docker container logs
4. Verify environment configuration
5. Test with health check endpoints
---
**VIP Coordinator** - Streamlined VIP logistics management with modern containerized deployment.

View File

@@ -1,10 +1,74 @@
.PHONY: dev build deploy .PHONY: dev build deploy test test-backend test-frontend test-e2e test-coverage clean help
# Development
dev: dev:
docker-compose -f docker-compose.dev.yml up --build docker-compose -f docker-compose.dev.yml up --build
# Production build
build: build:
docker-compose -f docker-compose.prod.yml build docker-compose -f docker-compose.prod.yml build
# Deploy to production
deploy: deploy:
docker-compose -f docker-compose.prod.yml up -d docker-compose -f docker-compose.prod.yml up -d
# Run all tests
test:
@bash scripts/test-runner.sh all
# Run backend tests only
test-backend:
@bash scripts/test-runner.sh backend
# Run frontend tests only
test-frontend:
@bash scripts/test-runner.sh frontend
# Run E2E tests only
test-e2e:
@bash scripts/test-runner.sh e2e
# Generate test coverage reports
test-coverage:
@bash scripts/test-runner.sh coverage
# Database commands
db-setup:
docker-compose -f docker-compose.dev.yml run --rm backend npm run db:setup
db-migrate:
docker-compose -f docker-compose.dev.yml run --rm backend npm run db:migrate
db-seed:
docker-compose -f docker-compose.dev.yml run --rm backend npm run db:seed
# Clean up Docker resources
clean:
docker-compose -f docker-compose.dev.yml down -v
docker-compose -f docker-compose.test.yml down -v
docker-compose -f docker-compose.prod.yml down -v
# Show available commands
help:
@echo "VIP Coordinator - Available Commands:"
@echo ""
@echo "Development:"
@echo " make dev - Start development environment"
@echo " make build - Build production containers"
@echo " make deploy - Deploy to production"
@echo ""
@echo "Testing:"
@echo " make test - Run all tests"
@echo " make test-backend - Run backend tests only"
@echo " make test-frontend - Run frontend tests only"
@echo " make test-e2e - Run E2E tests only"
@echo " make test-coverage - Generate test coverage reports"
@echo ""
@echo "Database:"
@echo " make db-setup - Initialize database with schema and seed data"
@echo " make db-migrate - Run database migrations"
@echo " make db-seed - Seed database with test data"
@echo ""
@echo "Maintenance:"
@echo " make clean - Clean up all Docker resources"
@echo " make help - Show this help message"

View File

@@ -7,7 +7,14 @@
"start": "node dist/index.js", "start": "node dist/index.js",
"dev": "npx tsx src/index.ts", "dev": "npx tsx src/index.ts",
"build": "tsc", "build": "tsc",
"test": "echo \"Error: no test specified\" && exit 1" "test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"db:migrate": "tsx src/scripts/db-cli.ts migrate",
"db:migrate:create": "tsx src/scripts/db-cli.ts migrate:create",
"db:seed": "tsx src/scripts/db-cli.ts seed",
"db:seed:reset": "tsx src/scripts/db-cli.ts seed:reset",
"db:setup": "tsx src/scripts/db-cli.ts setup"
}, },
"keywords": [ "keywords": [
"vip", "vip",
@@ -21,18 +28,25 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"google-auth-library": "^10.1.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",
"pg": "^8.11.3", "pg": "^8.11.3",
"redis": "^4.6.8", "redis": "^4.6.8",
"uuid": "^9.0.0" "uuid": "^9.0.0",
"zod": "^3.22.4"
}, },
"devDependencies": { "devDependencies": {
"@types/cors": "^2.8.13", "@types/cors": "^2.8.13",
"@types/express": "^4.17.17", "@types/express": "^4.17.17",
"@types/jest": "^29.5.12",
"@types/jsonwebtoken": "^9.0.2", "@types/jsonwebtoken": "^9.0.2",
"@types/node": "^20.5.0", "@types/node": "^20.5.0",
"@types/pg": "^8.10.2", "@types/pg": "^8.10.2",
"@types/supertest": "^2.0.16",
"@types/uuid": "^9.0.2", "@types/uuid": "^9.0.2",
"jest": "^29.7.0",
"supertest": "^6.3.4",
"ts-jest": "^29.1.2",
"ts-node": "^10.9.1", "ts-node": "^10.9.1",
"ts-node-dev": "^2.0.0", "ts-node-dev": "^2.0.0",
"tsx": "^4.7.0", "tsx": "^4.7.0",

File diff suppressed because it is too large Load Diff

View File

@@ -12,7 +12,7 @@ import databaseService from '../services/databaseService';
const router = express.Router(); const router = express.Router();
// Enhanced logging for production debugging // Enhanced logging for production debugging
function logAuthEvent(event: string, details: any = {}) { function logAuthEvent(event: string, details: Record<string, unknown> = {}) {
const timestamp = new Date().toISOString(); const timestamp = new Date().toISOString();
console.log(`🔐 [AUTH ${timestamp}] ${event}:`, JSON.stringify(details, null, 2)); console.log(`🔐 [AUTH ${timestamp}] ${event}:`, JSON.stringify(details, null, 2));
} }
@@ -277,13 +277,13 @@ router.get('/google/callback', async (req: Request, res: Response) => {
if (!user) { if (!user) {
// Determine role - first user becomes admin, others need approval // Determine role - first user becomes admin, others need approval
const approvedUserCount = await databaseService.getApprovedUserCount(); const isFirstUser = await databaseService.isFirstUser();
const role = approvedUserCount === 0 ? 'administrator' : 'coordinator'; const role = isFirstUser ? 'administrator' : 'coordinator';
logAuthEvent('USER_CREATION', { logAuthEvent('USER_CREATION', {
email: googleUser.email, email: googleUser.email,
role, role,
is_first_user: approvedUserCount === 0 is_first_user: isFirstUser
}); });
user = await databaseService.createUser({ user = await databaseService.createUser({
@@ -292,13 +292,12 @@ router.get('/google/callback', async (req: Request, res: Response) => {
email: googleUser.email, email: googleUser.email,
name: googleUser.name, name: googleUser.name,
profile_picture_url: googleUser.picture, profile_picture_url: googleUser.picture,
role role,
status: isFirstUser ? 'active' : 'pending'
}); });
// Auto-approve first admin, others need approval // Log the user creation
if (approvedUserCount === 0) { if (isFirstUser) {
await databaseService.updateUserApprovalStatus(googleUser.email, 'approved');
user.approval_status = 'approved';
logAuthEvent('FIRST_ADMIN_CREATED', { email: googleUser.email }); logAuthEvent('FIRST_ADMIN_CREATED', { email: googleUser.email });
} else { } else {
logAuthEvent('USER_PENDING_APPROVAL', { email: googleUser.email }); logAuthEvent('USER_PENDING_APPROVAL', { email: googleUser.email });
@@ -314,9 +313,9 @@ router.get('/google/callback', async (req: Request, res: Response) => {
}); });
} }
// Check if user is approved // Check if user is approved (admins are always approved)
if (user.approval_status !== 'approved') { if (user.role !== 'administrator' && user.status === 'pending') {
logAuthEvent('USER_NOT_APPROVED', { email: user.email, status: user.approval_status }); logAuthEvent('USER_NOT_APPROVED', { email: user.email, status: user.status });
return res.redirect(`${frontendUrl}?error=pending_approval&message=Your account is pending administrator approval`); return res.redirect(`${frontendUrl}?error=pending_approval&message=Your account is pending administrator approval`);
} }
@@ -365,8 +364,8 @@ router.post('/google/exchange', async (req: Request, res: Response) => {
if (!user) { if (!user) {
// Determine role - first user becomes admin // Determine role - first user becomes admin
const userCount = await databaseService.getUserCount(); const isFirstUser = await databaseService.isFirstUser();
const role = userCount === 0 ? 'administrator' : 'coordinator'; const role = isFirstUser ? 'administrator' : 'coordinator';
user = await databaseService.createUser({ user = await databaseService.createUser({
id: googleUser.id, id: googleUser.id,
@@ -374,14 +373,30 @@ router.post('/google/exchange', async (req: Request, res: Response) => {
email: googleUser.email, email: googleUser.email,
name: googleUser.name, name: googleUser.name,
profile_picture_url: googleUser.picture, profile_picture_url: googleUser.picture,
role role,
status: isFirstUser ? 'active' : 'pending'
}); });
// Log the user creation
if (isFirstUser) {
console.log(`✅ First admin created and auto-approved: ${user.name} (${user.email})`);
} else {
console.log(`✅ User created (pending approval): ${user.name} (${user.email}) as ${user.role}`);
}
} else { } else {
// Update last sign in // Update last sign in
await databaseService.updateUserLastSignIn(googleUser.email); await databaseService.updateUserLastSignIn(googleUser.email);
console.log(`✅ User logged in: ${user.name} (${user.email})`); console.log(`✅ User logged in: ${user.name} (${user.email})`);
} }
// Check if user is approved (admins are always approved)
if (user.role !== 'administrator' && user.status === 'pending') {
return res.status(403).json({
error: 'pending_approval',
message: 'Your account is pending administrator approval'
});
}
// Generate JWT token // Generate JWT token
const token = generateToken(user); const token = generateToken(user);
@@ -393,7 +408,8 @@ router.post('/google/exchange', async (req: Request, res: Response) => {
email: user.email, email: user.email,
name: user.name, name: user.name,
picture: user.profile_picture_url, picture: user.profile_picture_url,
role: user.role role: user.role,
status: user.status
} }
}); });
@@ -420,6 +436,115 @@ router.post('/logout', (req: Request, res: Response) => {
res.json({ message: 'Logged out successfully' }); res.json({ message: 'Logged out successfully' });
}); });
// Verify Google credential (from Google Identity Services)
router.post('/google/verify', async (req: Request, res: Response) => {
const { credential } = req.body;
if (!credential) {
return res.status(400).json({ error: 'Credential is required' });
}
try {
// Decode the JWT credential from Google
const parts = credential.split('.');
if (parts.length !== 3) {
return res.status(400).json({ error: 'Invalid credential format' });
}
// Decode the payload (base64)
const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString());
if (!payload.email || !payload.email_verified) {
return res.status(400).json({ error: 'Invalid or unverified email' });
}
// Create Google user object
const googleUser = {
id: payload.sub,
email: payload.email,
name: payload.name || payload.email,
picture: payload.picture,
verified_email: payload.email_verified
};
logAuthEvent('GOOGLE_CREDENTIAL_VERIFIED', {
email: googleUser.email,
name: googleUser.name
});
// Check if user exists or create new user
let user = await databaseService.getUserByEmail(googleUser.email);
if (!user) {
// Determine role - first user becomes admin
const isFirstUser = await databaseService.isFirstUser();
const role = isFirstUser ? 'administrator' : 'coordinator';
user = await databaseService.createUser({
id: googleUser.id,
google_id: googleUser.id,
email: googleUser.email,
name: googleUser.name,
profile_picture_url: googleUser.picture,
role,
status: isFirstUser ? 'active' : 'pending'
});
// Log the user creation
if (isFirstUser) {
logAuthEvent('FIRST_ADMIN_CREATED', { email: googleUser.email });
} else {
logAuthEvent('USER_PENDING_APPROVAL', { email: googleUser.email });
}
} else {
// Update last sign in
await databaseService.updateUserLastSignIn(googleUser.email);
logAuthEvent('USER_LOGIN', {
email: user.email,
name: user.name,
role: user.role,
status: user.status
});
}
// Check if user is approved (admins are always approved)
if (user.role !== 'administrator' && user.status === 'pending') {
return res.status(403).json({
error: 'pending_approval',
message: 'Your account is pending administrator approval',
user: {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
status: user.status
},
token: generateToken(user) // Still give them a token so they can check status
});
}
// Generate JWT token
const token = generateToken(user);
// Return token to frontend
res.json({
token,
user: {
id: user.id,
email: user.email,
name: user.name,
picture: user.profile_picture_url,
role: user.role,
status: user.status
}
});
} catch (error) {
console.error('Error verifying Google credential:', error);
res.status(500).json({ error: 'Failed to verify credential' });
}
});
// Get auth status // Get auth status
router.get('/status', (req: Request, res: Response) => { router.get('/status', (req: Request, res: Response) => {
const authHeader = req.headers.authorization; const authHeader = req.headers.authorization;
@@ -610,4 +735,143 @@ router.patch('/users/:email/approval', requireAuth, requireRole(['administrator'
} }
}); });
// Complete user onboarding
router.post('/users/complete-onboarding', requireAuth, async (req: Request, res: Response) => {
try {
const userEmail = req.user?.email;
if (!userEmail) {
return res.status(401).json({ error: 'User not authenticated' });
}
const { onboardingData, phone, organization } = req.body;
const updatedUser = await databaseService.completeUserOnboarding(userEmail, {
...onboardingData,
phone,
organization
});
res.json({ message: 'Onboarding completed successfully', user: updatedUser });
} catch (error) {
console.error('Failed to complete onboarding:', error);
res.status(500).json({ error: 'Failed to complete onboarding' });
}
});
// Get current user with full details
router.get('/users/me', requireAuth, async (req: Request, res: Response) => {
try {
const userEmail = req.user?.email;
if (!userEmail) {
return res.status(401).json({ error: 'User not authenticated' });
}
const user = await databaseService.getUserByEmail(userEmail);
res.json(user);
} catch (error) {
console.error('Failed to get user details:', error);
res.status(500).json({ error: 'Failed to get user details' });
}
});
// Approve user (by email, not ID)
router.post('/users/:email/approve', requireAuth, requireRole(['administrator']), async (req: Request, res: Response) => {
try {
const { email } = req.params;
const { role } = req.body;
const approvedBy = req.user?.email || '';
const updatedUser = await databaseService.approveUser(email, approvedBy, role);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User approved successfully', user: updatedUser });
} catch (error) {
console.error('Failed to approve user:', error);
res.status(500).json({ error: 'Failed to approve user' });
}
});
// Reject user
router.post('/users/:email/reject', requireAuth, requireRole(['administrator']), async (req: Request, res: Response) => {
try {
const { email } = req.params;
const { reason } = req.body;
const rejectedBy = req.user?.email || '';
const updatedUser = await databaseService.rejectUser(email, rejectedBy, reason);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User rejected', user: updatedUser });
} catch (error) {
console.error('Failed to reject user:', error);
res.status(500).json({ error: 'Failed to reject user' });
}
});
// Deactivate user
router.post('/users/:email/deactivate', requireAuth, requireRole(['administrator']), async (req: Request, res: Response) => {
try {
const { email } = req.params;
const deactivatedBy = req.user?.email || '';
const updatedUser = await databaseService.deactivateUser(email, deactivatedBy);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User deactivated', user: updatedUser });
} catch (error) {
console.error('Failed to deactivate user:', error);
res.status(500).json({ error: 'Failed to deactivate user' });
}
});
// Reactivate user
router.post('/users/:email/reactivate', requireAuth, requireRole(['administrator']), async (req: Request, res: Response) => {
try {
const { email } = req.params;
const reactivatedBy = req.user?.email || '';
const updatedUser = await databaseService.reactivateUser(email, reactivatedBy);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ message: 'User reactivated', user: updatedUser });
} catch (error) {
console.error('Failed to reactivate user:', error);
res.status(500).json({ error: 'Failed to reactivate user' });
}
});
// Update user role
router.put('/users/:email/role', requireAuth, requireRole(['administrator']), async (req: Request, res: Response) => {
try {
const { email } = req.params;
const { role } = req.body;
const updatedUser = await databaseService.updateUserRole(email, role);
if (!updatedUser) {
return res.status(404).json({ error: 'User not found' });
}
// Log audit
await databaseService.createAuditLog('role_changed', email, req.user?.email || '', { newRole: role });
res.json({ message: 'User role updated', user: updatedUser });
} catch (error) {
console.error('Failed to update user role:', error);
res.status(500).json({ error: 'Failed to update user role' });
}
});
export default router; export default router;

View File

@@ -1,550 +1,332 @@
import { Pool, PoolClient } from 'pg'; import { Pool, PoolClient } from 'pg';
import { createClient, RedisClientType } from 'redis'; import { createClient, RedisClientType } from 'redis';
class DatabaseService { // Import the existing backup service
private pool: Pool; import backupDatabaseService from './backup-services/databaseService';
private redis: RedisClientType;
// Extend the backup service with new user management methods
class EnhancedDatabaseService {
private backupService: typeof backupDatabaseService;
constructor() { constructor() {
this.pool = new Pool({ this.backupService = backupDatabaseService;
connectionString: process.env.DATABASE_URL,
ssl: process.env.NODE_ENV === 'production' ? { rejectUnauthorized: false } : false
});
// Initialize Redis connection
this.redis = createClient({
socket: {
host: process.env.REDIS_HOST || 'redis',
port: parseInt(process.env.REDIS_PORT || '6379')
}
});
this.redis.on('error', (err) => {
console.error('❌ Redis connection error:', err);
});
// Test connections on startup
this.testConnection();
this.testRedisConnection();
}
private async testConnection(): Promise<void> {
try {
const client = await this.pool.connect();
console.log('✅ Connected to PostgreSQL database');
client.release();
} catch (error) {
console.error('❌ Failed to connect to PostgreSQL database:', error);
}
}
private async testRedisConnection(): Promise<void> {
try {
if (!this.redis.isOpen) {
await this.redis.connect();
}
await this.redis.ping();
console.log('✅ Connected to Redis');
} catch (error) {
console.error('❌ Failed to connect to Redis:', error);
}
} }
// Delegate all existing methods to backup service
async query(text: string, params?: any[]): Promise<any> { async query(text: string, params?: any[]): Promise<any> {
const client = await this.pool.connect(); return this.backupService.query(text, params);
try {
const result = await client.query(text, params);
return result;
} finally {
client.release();
}
} }
async getClient(): Promise<PoolClient> { async getClient(): Promise<PoolClient> {
return await this.pool.connect(); return this.backupService.getClient();
} }
async close(): Promise<void> { async close(): Promise<void> {
await this.pool.end(); return this.backupService.close();
if (this.redis.isOpen) {
await this.redis.disconnect();
}
} }
// Initialize database tables
async initializeTables(): Promise<void> { async initializeTables(): Promise<void> {
try { return this.backupService.initializeTables();
// Create users table (matching the actual schema)
await this.query(`
CREATE TABLE IF NOT EXISTS users (
id VARCHAR(255) PRIMARY KEY,
google_id VARCHAR(255) UNIQUE NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
name VARCHAR(255) NOT NULL,
role VARCHAR(50) NOT NULL CHECK (role IN ('driver', 'coordinator', 'administrator')),
profile_picture_url TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP,
is_active BOOLEAN DEFAULT true,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
approval_status VARCHAR(20) DEFAULT 'pending' CHECK (approval_status IN ('pending', 'approved', 'denied'))
)
`);
// Add approval_status column if it doesn't exist (migration for existing databases)
await this.query(`
ALTER TABLE users
ADD COLUMN IF NOT EXISTS approval_status VARCHAR(20) DEFAULT 'pending' CHECK (approval_status IN ('pending', 'approved', 'denied'))
`);
// Create indexes
await this.query(`
CREATE INDEX IF NOT EXISTS idx_users_google_id ON users(google_id)
`);
await this.query(`
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)
`);
await this.query(`
CREATE INDEX IF NOT EXISTS idx_users_role ON users(role)
`);
console.log('✅ Database tables initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize database tables:', error);
throw error;
}
} }
// User management methods // User methods from backup service
async createUser(user: { async createUser(user: any): Promise<any> {
id: string; return this.backupService.createUser(user);
google_id: string;
email: string;
name: string;
profile_picture_url?: string;
role: string;
}): Promise<any> {
const query = `
INSERT INTO users (id, google_id, email, name, profile_picture_url, role, last_login)
VALUES ($1, $2, $3, $4, $5, $6, CURRENT_TIMESTAMP)
RETURNING *
`;
const values = [
user.id,
user.google_id,
user.email,
user.name,
user.profile_picture_url || null,
user.role
];
const result = await this.query(query, values);
console.log(`👤 Created user: ${user.name} (${user.email}) as ${user.role}`);
return result.rows[0];
} }
async getUserByEmail(email: string): Promise<any> { async getUserByEmail(email: string): Promise<any> {
const query = 'SELECT * FROM users WHERE email = $1'; return this.backupService.getUserByEmail(email);
const result = await this.query(query, [email]);
return result.rows[0] || null;
} }
async getUserById(id: string): Promise<any> { async getUserById(id: string): Promise<any> {
const query = 'SELECT * FROM users WHERE id = $1'; return this.backupService.getUserById(id);
const result = await this.query(query, [id]);
return result.rows[0] || null;
}
async getAllUsers(): Promise<any[]> {
const query = 'SELECT * FROM users ORDER BY created_at ASC';
const result = await this.query(query);
return result.rows;
} }
async updateUserRole(email: string, role: string): Promise<any> { async updateUserRole(email: string, role: string): Promise<any> {
return this.backupService.updateUserRole(email, role);
}
async updateUserLastSignIn(email: string): Promise<any> {
return this.backupService.updateUserLastSignIn(email);
}
async getUserCount(): Promise<number> {
return this.backupService.getUserCount();
}
async updateUserApprovalStatus(email: string, status: 'pending' | 'approved' | 'denied'): Promise<any> {
return this.backupService.updateUserApprovalStatus(email, status);
}
async getApprovedUserCount(): Promise<number> {
return this.backupService.getApprovedUserCount();
}
async getAllUsers(): Promise<any[]> {
return this.backupService.getAllUsers();
}
async deleteUser(email: string): Promise<boolean> {
return this.backupService.deleteUser(email);
}
async getPendingUsers(): Promise<any[]> {
return this.backupService.getPendingUsers();
}
// NEW: Enhanced user management methods
async completeUserOnboarding(email: string, onboardingData: any): Promise<any> {
const query = ` const query = `
UPDATE users UPDATE users
SET role = $1, updated_at = CURRENT_TIMESTAMP SET phone = $1,
organization = $2,
onboarding_data = $3,
updated_at = CURRENT_TIMESTAMP
WHERE email = $4
RETURNING *
`;
const result = await this.query(query, [
onboardingData.phone,
onboardingData.organization,
JSON.stringify(onboardingData),
email
]);
return result.rows[0] || null;
}
async approveUser(userEmail: string, approvedBy: string, newRole?: string): Promise<any> {
const query = `
UPDATE users
SET status = 'active',
approval_status = 'approved',
approved_by = $1,
approved_at = CURRENT_TIMESTAMP,
role = COALESCE($2, role),
updated_at = CURRENT_TIMESTAMP
WHERE email = $3
RETURNING *
`;
const result = await this.query(query, [approvedBy, newRole, userEmail]);
// Log audit
if (result.rows[0]) {
await this.createAuditLog('user_approved', userEmail, approvedBy, { newRole });
}
return result.rows[0] || null;
}
async rejectUser(userEmail: string, rejectedBy: string, reason?: string): Promise<any> {
const query = `
UPDATE users
SET status = 'deactivated',
approval_status = 'denied',
rejected_by = $1,
rejected_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE email = $2 WHERE email = $2
RETURNING * RETURNING *
`; `;
const result = await this.query(query, [role, email]); const result = await this.query(query, [rejectedBy, userEmail]);
// Log audit
if (result.rows[0]) { if (result.rows[0]) {
console.log(`👤 Updated user role: ${result.rows[0].name} (${email}) -> ${role}`); await this.createAuditLog('user_rejected', userEmail, rejectedBy, { reason });
} }
return result.rows[0] || null; return result.rows[0] || null;
} }
async updateUserLastSignIn(email: string): Promise<any> { async deactivateUser(userEmail: string, deactivatedBy: string): Promise<any> {
const query = ` const query = `
UPDATE users UPDATE users
SET last_login = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP SET status = 'deactivated',
deactivated_by = $1,
deactivated_at = CURRENT_TIMESTAMP,
updated_at = CURRENT_TIMESTAMP
WHERE email = $2
RETURNING *
`;
const result = await this.query(query, [deactivatedBy, userEmail]);
// Log audit
if (result.rows[0]) {
await this.createAuditLog('user_deactivated', userEmail, deactivatedBy, {});
}
return result.rows[0] || null;
}
async reactivateUser(userEmail: string, reactivatedBy: string): Promise<any> {
const query = `
UPDATE users
SET status = 'active',
deactivated_by = NULL,
deactivated_at = NULL,
updated_at = CURRENT_TIMESTAMP
WHERE email = $1 WHERE email = $1
RETURNING * RETURNING *
`; `;
const result = await this.query(query, [email]); const result = await this.query(query, [userEmail]);
return result.rows[0] || null;
}
async deleteUser(email: string): Promise<any> { // Log audit
const query = 'DELETE FROM users WHERE email = $1 RETURNING *';
const result = await this.query(query, [email]);
if (result.rows[0]) { if (result.rows[0]) {
console.log(`👤 Deleted user: ${result.rows[0].name} (${email})`); await this.createAuditLog('user_reactivated', userEmail, reactivatedBy, {});
} }
return result.rows[0] || null; return result.rows[0] || null;
} }
async getUserCount(): Promise<number> { async createAuditLog(action: string, userEmail: string, performedBy: string, details: any): Promise<void> {
const query = 'SELECT COUNT(*) as count FROM users'; const query = `
INSERT INTO user_audit_log (action, user_email, performed_by, action_details)
VALUES ($1, $2, $3, $4)
`;
await this.query(query, [action, userEmail, performedBy, JSON.stringify(details)]);
}
async getUserAuditLog(userEmail: string): Promise<any[]> {
const query = `
SELECT * FROM user_audit_log
WHERE user_email = $1
ORDER BY created_at DESC
`;
const result = await this.query(query, [userEmail]);
return result.rows;
}
async getUsersWithFilters(filters: {
status?: string;
role?: string;
search?: string;
}): Promise<any[]> {
let query = 'SELECT * FROM users WHERE 1=1';
const params: any[] = [];
let paramIndex = 1;
if (filters.status) {
query += ` AND status = $${paramIndex}`;
params.push(filters.status);
paramIndex++;
}
if (filters.role) {
query += ` AND role = $${paramIndex}`;
params.push(filters.role);
paramIndex++;
}
if (filters.search) {
query += ` AND (LOWER(name) LIKE LOWER($${paramIndex}) OR LOWER(email) LIKE LOWER($${paramIndex}) OR LOWER(organization) LIKE LOWER($${paramIndex}))`;
params.push(`%${filters.search}%`);
paramIndex++;
}
query += ' ORDER BY created_at DESC';
const result = await this.query(query, params);
return result.rows;
}
// Fix for first user admin issue
async getActiveUserCount(): Promise<number> {
const query = "SELECT COUNT(*) as count FROM users WHERE status = 'active'";
const result = await this.query(query); const result = await this.query(query);
return parseInt(result.rows[0].count); return parseInt(result.rows[0].count);
} }
// User approval methods async isFirstUser(): Promise<boolean> {
async updateUserApprovalStatus(email: string, status: 'pending' | 'approved' | 'denied'): Promise<any> { return this.backupService.isFirstUser();
const query = `
UPDATE users
SET approval_status = $1, updated_at = CURRENT_TIMESTAMP
WHERE email = $2
RETURNING *
`;
const result = await this.query(query, [status, email]);
if (result.rows[0]) {
console.log(`👤 Updated user approval: ${result.rows[0].name} (${email}) -> ${status}`);
}
return result.rows[0] || null;
} }
async getPendingUsers(): Promise<any[]> { // VIP methods from backup service
const query = 'SELECT * FROM users WHERE approval_status = $1 ORDER BY created_at ASC'; async createVip(vip: any): Promise<any> {
const result = await this.query(query, ['pending']); return this.backupService.createVip(vip);
return result.rows;
} }
async getApprovedUserCount(): Promise<number> { async getVipById(id: string): Promise<any> {
const query = 'SELECT COUNT(*) as count FROM users WHERE approval_status = $1'; return this.backupService.getVipById(id);
const result = await this.query(query, ['approved']);
return parseInt(result.rows[0].count);
} }
// Initialize all database tables and schema async getAllVips(): Promise<any[]> {
async initializeDatabase(): Promise<void> { return this.backupService.getAllVips();
try { }
await this.initializeTables();
await this.initializeVipTables();
// Approve all existing users (migration for approval system) async updateVip(id: string, vip: any): Promise<any> {
await this.query(` return this.backupService.updateVip(id, vip);
UPDATE users }
SET approval_status = 'approved'
WHERE approval_status IS NULL OR approval_status = 'pending'
`);
console.log('✅ Approved all existing users');
console.log('✅ Database schema initialization completed'); async deleteVip(id: string): Promise<boolean> {
} catch (error) { return this.backupService.deleteVip(id);
console.error('❌ Failed to initialize database schema:', error); }
throw error;
async getVipsByDepartment(department: string): Promise<any[]> {
return this.backupService.getVipsByDepartment(department);
}
// Driver methods from backup service
async createDriver(driver: any): Promise<any> {
return this.backupService.createDriver(driver);
}
async getDriverById(id: string): Promise<any> {
return this.backupService.getDriverById(id);
}
async getAllDrivers(): Promise<any[]> {
return this.backupService.getAllDrivers();
}
async updateDriver(id: string, driver: any): Promise<any> {
return this.backupService.updateDriver(id, driver);
}
async deleteDriver(id: string): Promise<boolean> {
return this.backupService.deleteDriver(id);
}
async getDriversByDepartment(department: string): Promise<any[]> {
return this.backupService.getDriversByDepartment(department);
}
async updateDriverLocation(id: string, location: any): Promise<any> {
return this.backupService.updateDriverLocation(id, location);
}
// Schedule methods from backup service
async createScheduleEvent(vipId: string, event: any): Promise<any> {
return this.backupService.createScheduleEvent(vipId, event);
}
async getScheduleByVipId(vipId: string): Promise<any[]> {
return this.backupService.getScheduleByVipId(vipId);
}
async updateScheduleEvent(vipId: string, eventId: string, event: any): Promise<any> {
return this.backupService.updateScheduleEvent(vipId, eventId, event);
}
async deleteScheduleEvent(vipId: string, eventId: string): Promise<boolean> {
return this.backupService.deleteScheduleEvent(vipId, eventId);
}
async getAllScheduleEvents(): Promise<any[]> {
return this.backupService.getAllScheduleEvents();
}
async getScheduleEventsByDateRange(startDate: Date, endDate: Date): Promise<any[]> {
return this.backupService.getScheduleEventsByDateRange(startDate, endDate);
} }
} }
// VIP table initialization using the correct schema // Export singleton instance
async initializeVipTables(): Promise<void> { const databaseService = new EnhancedDatabaseService();
try { export default databaseService;
// Check if VIPs table exists and has the correct schema
const tableExists = await this.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'vips'
)
`);
if (tableExists.rows[0].exists) {
// Check if the table has the correct columns
const columnCheck = await this.query(`
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'vips'
AND column_name = 'organization'
`);
if (columnCheck.rows.length === 0) {
console.log('🔄 Migrating VIPs table to new schema...');
// Drop the old table and recreate with correct schema
await this.query(`DROP TABLE IF EXISTS vips CASCADE`);
}
}
// Create VIPs table with correct schema matching enhancedDataService expectations
await this.query(`
CREATE TABLE IF NOT EXISTS vips (
id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
organization VARCHAR(255) NOT NULL,
department VARCHAR(255) DEFAULT 'Office of Development',
transport_mode VARCHAR(50) NOT NULL CHECK (transport_mode IN ('flight', 'self-driving')),
expected_arrival TIMESTAMP,
needs_airport_pickup BOOLEAN DEFAULT false,
needs_venue_transport BOOLEAN DEFAULT true,
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create flights table (for VIPs with flight transport)
await this.query(`
CREATE TABLE IF NOT EXISTS flights (
id SERIAL PRIMARY KEY,
vip_id VARCHAR(255) REFERENCES vips(id) ON DELETE CASCADE,
flight_number VARCHAR(50) NOT NULL,
flight_date DATE NOT NULL,
segment INTEGER NOT NULL,
departure_airport VARCHAR(10),
arrival_airport VARCHAR(10),
scheduled_departure TIMESTAMP,
scheduled_arrival TIMESTAMP,
actual_departure TIMESTAMP,
actual_arrival TIMESTAMP,
status VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Check and migrate drivers table
const driversTableExists = await this.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'drivers'
)
`);
if (driversTableExists.rows[0].exists) {
// Check if drivers table has the correct schema (phone column and department column)
const driversSchemaCheck = await this.query(`
SELECT column_name
FROM information_schema.columns
WHERE table_name = 'drivers'
AND column_name IN ('phone', 'department')
`);
if (driversSchemaCheck.rows.length < 2) {
console.log('🔄 Migrating drivers table to new schema...');
await this.query(`DROP TABLE IF EXISTS drivers CASCADE`);
}
}
// Create drivers table with correct schema
await this.query(`
CREATE TABLE IF NOT EXISTS drivers (
id VARCHAR(255) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
phone VARCHAR(50) NOT NULL,
department VARCHAR(255) DEFAULT 'Office of Development',
user_id VARCHAR(255) REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Check and migrate schedule_events table
const scheduleTableExists = await this.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'schedule_events'
)
`);
if (!scheduleTableExists.rows[0].exists) {
// Check for old 'schedules' table and drop it
const oldScheduleExists = await this.query(`
SELECT EXISTS (
SELECT FROM information_schema.tables
WHERE table_schema = 'public'
AND table_name = 'schedules'
)
`);
if (oldScheduleExists.rows[0].exists) {
console.log('🔄 Migrating schedules table to schedule_events...');
await this.query(`DROP TABLE IF EXISTS schedules CASCADE`);
}
}
// Create schedule_events table
await this.query(`
CREATE TABLE IF NOT EXISTS schedule_events (
id VARCHAR(255) PRIMARY KEY,
vip_id VARCHAR(255) REFERENCES vips(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
location VARCHAR(255) NOT NULL,
start_time TIMESTAMP NOT NULL,
end_time TIMESTAMP NOT NULL,
description TEXT,
assigned_driver_id VARCHAR(255) REFERENCES drivers(id) ON DELETE SET NULL,
status VARCHAR(50) DEFAULT 'scheduled' CHECK (status IN ('scheduled', 'in-progress', 'completed', 'cancelled')),
event_type VARCHAR(50) NOT NULL CHECK (event_type IN ('transport', 'meeting', 'event', 'meal', 'accommodation')),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create system_setup table for tracking initial setup
await this.query(`
CREATE TABLE IF NOT EXISTS system_setup (
id SERIAL PRIMARY KEY,
setup_completed BOOLEAN DEFAULT false,
first_admin_created BOOLEAN DEFAULT false,
setup_date TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create admin_settings table
await this.query(`
CREATE TABLE IF NOT EXISTS admin_settings (
id SERIAL PRIMARY KEY,
setting_key VARCHAR(255) UNIQUE NOT NULL,
setting_value TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
`);
// Create indexes for better performance
await this.query(`CREATE INDEX IF NOT EXISTS idx_vips_transport_mode ON vips(transport_mode)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_flights_vip_id ON flights(vip_id)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_flights_date ON flights(flight_date)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_schedule_events_vip_id ON schedule_events(vip_id)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_schedule_events_driver_id ON schedule_events(assigned_driver_id)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_schedule_events_start_time ON schedule_events(start_time)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_schedule_events_status ON schedule_events(status)`);
await this.query(`CREATE INDEX IF NOT EXISTS idx_drivers_user_id ON drivers(user_id)`);
// Create updated_at trigger function
await this.query(`
CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = CURRENT_TIMESTAMP;
RETURN NEW;
END;
$$ language 'plpgsql'
`);
// Create triggers for updated_at (drop if exists first)
await this.query(`DROP TRIGGER IF EXISTS update_vips_updated_at ON vips`);
await this.query(`DROP TRIGGER IF EXISTS update_flights_updated_at ON flights`);
await this.query(`DROP TRIGGER IF EXISTS update_drivers_updated_at ON drivers`);
await this.query(`DROP TRIGGER IF EXISTS update_schedule_events_updated_at ON schedule_events`);
await this.query(`DROP TRIGGER IF EXISTS update_admin_settings_updated_at ON admin_settings`);
await this.query(`CREATE TRIGGER update_vips_updated_at BEFORE UPDATE ON vips FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()`);
await this.query(`CREATE TRIGGER update_flights_updated_at BEFORE UPDATE ON flights FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()`);
await this.query(`CREATE TRIGGER update_drivers_updated_at BEFORE UPDATE ON drivers FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()`);
await this.query(`CREATE TRIGGER update_schedule_events_updated_at BEFORE UPDATE ON schedule_events FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()`);
await this.query(`CREATE TRIGGER update_admin_settings_updated_at BEFORE UPDATE ON admin_settings FOR EACH ROW EXECUTE FUNCTION update_updated_at_column()`);
console.log('✅ VIP Coordinator database schema initialized successfully');
} catch (error) {
console.error('❌ Failed to initialize VIP tables:', error);
throw error;
}
}
// Redis-based driver location tracking
async getDriverLocation(driverId: string): Promise<{ lat: number; lng: number } | null> {
try {
if (!this.redis.isOpen) {
await this.redis.connect();
}
const location = await this.redis.hGetAll(`driver:${driverId}:location`);
if (location && location.lat && location.lng) {
return {
lat: parseFloat(location.lat),
lng: parseFloat(location.lng)
};
}
return null;
} catch (error) {
console.error('❌ Error getting driver location from Redis:', error);
return null;
}
}
async updateDriverLocation(driverId: string, location: { lat: number; lng: number }): Promise<void> {
try {
if (!this.redis.isOpen) {
await this.redis.connect();
}
const key = `driver:${driverId}:location`;
await this.redis.hSet(key, {
lat: location.lat.toString(),
lng: location.lng.toString(),
updated_at: new Date().toISOString()
});
// Set expiration to 24 hours
await this.redis.expire(key, 24 * 60 * 60);
} catch (error) {
console.error('❌ Error updating driver location in Redis:', error);
}
}
async getAllDriverLocations(): Promise<{ [driverId: string]: { lat: number; lng: number } }> {
try {
if (!this.redis.isOpen) {
await this.redis.connect();
}
const keys = await this.redis.keys('driver:*:location');
const locations: { [driverId: string]: { lat: number; lng: number } } = {};
for (const key of keys) {
const driverId = key.split(':')[1];
const location = await this.redis.hGetAll(key);
if (location && location.lat && location.lng) {
locations[driverId] = {
lat: parseFloat(location.lat),
lng: parseFloat(location.lng)
};
}
}
return locations;
} catch (error) {
console.error('❌ Error getting all driver locations from Redis:', error);
return {};
}
}
async removeDriverLocation(driverId: string): Promise<void> {
try {
if (!this.redis.isOpen) {
await this.redis.connect();
}
await this.redis.del(`driver:${driverId}:location`);
} catch (error) {
console.error('❌ Error removing driver location from Redis:', error);
}
}
}
export default new DatabaseService();

View File

@@ -8,10 +8,13 @@ export interface User {
name: string; name: string;
profile_picture_url?: string; profile_picture_url?: string;
role: 'driver' | 'coordinator' | 'administrator'; role: 'driver' | 'coordinator' | 'administrator';
status?: 'pending' | 'active' | 'deactivated';
created_at?: string; created_at?: string;
last_login?: string; last_login?: string;
is_active?: boolean; is_active?: boolean;
updated_at?: string; updated_at?: string;
approval_status?: string;
onboardingData?: any;
} }
class JWTKeyManager { class JWTKeyManager {
@@ -78,6 +81,9 @@ class JWTKeyManager {
name: user.name, name: user.name,
profile_picture_url: user.profile_picture_url, profile_picture_url: user.profile_picture_url,
role: user.role, role: user.role,
status: user.status,
approval_status: user.approval_status,
onboardingData: user.onboardingData,
iat: Math.floor(Date.now() / 1000) // Issued at time iat: Math.floor(Date.now() / 1000) // Issued at time
}; };
@@ -102,7 +108,10 @@ class JWTKeyManager {
email: decoded.email, email: decoded.email,
name: decoded.name, name: decoded.name,
profile_picture_url: decoded.profile_picture_url, profile_picture_url: decoded.profile_picture_url,
role: decoded.role role: decoded.role,
status: decoded.status,
approval_status: decoded.approval_status,
onboardingData: decoded.onboardingData
}; };
} catch (error) { } catch (error) {
// Try previous secret during grace period // Try previous secret during grace period
@@ -121,7 +130,10 @@ class JWTKeyManager {
email: decoded.email, email: decoded.email,
name: decoded.name, name: decoded.name,
profile_picture_url: decoded.profile_picture_url, profile_picture_url: decoded.profile_picture_url,
role: decoded.role role: decoded.role,
status: decoded.status,
approval_status: decoded.approval_status,
onboardingData: decoded.onboardingData
}; };
} catch (gracePeriodError) { } catch (gracePeriodError) {
console.log('❌ Token verification failed with both current and previous keys'); console.log('❌ Token verification failed with both current and previous keys');

View File

@@ -17,5 +17,5 @@
"moduleResolution": "node" "moduleResolution": "node"
}, },
"include": ["src/**/*"], "include": ["src/**/*"],
"exclude": ["node_modules", "dist"] "exclude": ["node_modules", "dist", "src/**/*.original.ts", "src/**/backup-services/**", "src/routes/simpleAuth.ts", "src/config/simpleAuth.ts"]
} }

149
deploy.sh
View File

@@ -1,130 +1,139 @@
#!/bin/bash #!/bin/bash
# VIP Coordinator - Quick Deployment Script # VIP Coordinator Quick Deploy Script
# This script helps you deploy VIP Coordinator with Docker # This script helps you deploy the VIP Coordinator application using Docker
set -e set -e
echo "🚀 VIP Coordinator - Quick Deployment Script" echo "🚀 VIP Coordinator Deployment Script"
echo "=============================================" echo "===================================="
# Check if Docker is installed # Check if Docker is installed
if ! command -v docker &> /dev/null; then if ! command -v docker &> /dev/null; then
echo "❌ Docker is not installed. Please install Docker first." echo "❌ Docker is not installed. Please install Docker first."
echo " Visit: https://docs.docker.com/get-docker/"
exit 1 exit 1
fi fi
# Check if Docker Compose is installed # Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then if ! command -v docker-compose &> /dev/null; then
echo "❌ Docker Compose is not installed. Please install Docker Compose first." echo "❌ Docker Compose is not installed. Please install Docker Compose first."
echo " Visit: https://docs.docker.com/compose/install/"
exit 1 exit 1
fi fi
echo "✅ Docker and Docker Compose are installed"
# Check if .env file exists # Check if .env file exists
if [ ! -f ".env" ]; then if [ ! -f ".env" ]; then
echo "⚠️ No .env file found. Creating one from .env.example..."
if [ -f ".env.example" ]; then if [ -f ".env.example" ]; then
echo "📝 Creating .env file from template..."
cp .env.example .env cp .env.example .env
echo "⚠️ IMPORTANT: Please edit .env file with your configuration before continuing!" echo "✅ Created .env file from .env.example"
echo " Required changes:"
echo " - DB_PASSWORD: Set a secure database password"
echo " - ADMIN_PASSWORD: Set a secure admin password"
echo " - GOOGLE_CLIENT_ID: Your Google OAuth Client ID"
echo " - GOOGLE_CLIENT_SECRET: Your Google OAuth Client Secret"
echo " - Update domain settings for production deployment"
echo "" echo ""
read -p "Press Enter after you've updated the .env file..." echo "🔧 IMPORTANT: Please edit the .env file and update the following:"
echo " - POSTGRES_PASSWORD (set a secure password)"
echo " - GOOGLE_CLIENT_ID (from Google Cloud Console)"
echo " - GOOGLE_CLIENT_SECRET (from Google Cloud Console)"
echo " - VITE_API_URL (your backend URL)"
echo " - VITE_FRONTEND_URL (your frontend URL)"
echo ""
echo "📖 For Google OAuth setup instructions, see:"
echo " https://console.cloud.google.com/"
echo ""
read -p "Press Enter after updating the .env file to continue..."
else else
echo "❌ .env.example file not found. Please ensure you have the deployment files." echo "❌ .env.example file not found. Please create a .env file manually."
exit 1 exit 1
fi fi
fi fi
# Validate required environment variables # Validate required environment variables
echo "🔍 Validating configuration..." echo "🔍 Validating environment configuration..."
# Source the .env file
set -a
source .env source .env
set +a
if [ -z "$DB_PASSWORD" ] || [ "$DB_PASSWORD" = "VipCoord2025SecureDB" ]; then # Check required variables
echo "⚠️ Warning: Please change DB_PASSWORD from the default value" REQUIRED_VARS=("POSTGRES_PASSWORD" "GOOGLE_CLIENT_ID" "GOOGLE_CLIENT_SECRET")
MISSING_VARS=()
for var in "${REQUIRED_VARS[@]}"; do
if [ -z "${!var}" ] || [ "${!var}" = "your_secure_password_here" ] || [ "${!var}" = "your_google_client_id_here" ] || [ "${!var}" = "your_google_client_secret_here" ]; then
MISSING_VARS+=("$var")
fi fi
done
if [ -z "$ADMIN_PASSWORD" ] || [ "$ADMIN_PASSWORD" = "ChangeThisSecurePassword" ]; then if [ ${#MISSING_VARS[@]} -ne 0 ]; then
echo "⚠️ Warning: Please change ADMIN_PASSWORD from the default value" echo "❌ The following required environment variables are missing or have default values:"
fi for var in "${MISSING_VARS[@]}"; do
echo " - $var"
if [ -z "$GOOGLE_CLIENT_ID" ] || [ "$GOOGLE_CLIENT_ID" = "your-google-client-id.apps.googleusercontent.com" ]; then done
echo "❌ Error: GOOGLE_CLIENT_ID must be configured" echo ""
echo " Please set up Google OAuth and update your .env file" echo "Please update your .env file with the correct values."
exit 1 exit 1
fi fi
if [ -z "$GOOGLE_CLIENT_SECRET" ] || [ "$GOOGLE_CLIENT_SECRET" = "your-google-client-secret" ]; then echo "✅ Environment configuration looks good!"
echo "❌ Error: GOOGLE_CLIENT_SECRET must be configured"
echo " Please set up Google OAuth and update your .env file"
exit 1
fi
echo "✅ Configuration validated" # Pull the latest images
echo ""
echo "📥 Pulling latest Docker images..."
docker pull t72chevy/vip-coordinator:backend-latest
docker pull t72chevy/vip-coordinator:frontend-latest
# Pull latest images # Stop existing containers if running
echo "📥 Pulling latest images from Docker Hub..." echo ""
docker-compose pull echo "🛑 Stopping existing containers (if any)..."
docker-compose down --remove-orphans || true
# Start the application # Start the application
echo "🚀 Starting VIP Coordinator..." echo ""
echo "🚀 Starting VIP Coordinator application..."
docker-compose up -d docker-compose up -d
# Wait for services to be ready # Wait for services to be healthy
echo ""
echo "⏳ Waiting for services to start..." echo "⏳ Waiting for services to start..."
sleep 10 sleep 10
# Check service status # Check service status
echo "🔍 Checking service status..." echo ""
echo "📊 Service Status:"
docker-compose ps docker-compose ps
# Check if backend is healthy # Check if services are healthy
echo "🏥 Checking backend health..." echo ""
for i in {1..30}; do echo "🏥 Health Checks:"
if curl -s http://localhost:3000/health > /dev/null 2>&1; then
echo "✅ Backend is healthy"
break
fi
if [ $i -eq 30 ]; then
echo "❌ Backend health check failed"
echo " Check logs with: docker-compose logs backend"
exit 1
fi
sleep 2
done
# Check if frontend is accessible # Check backend health
echo "🌐 Checking frontend..." if curl -f -s http://localhost:3000/health > /dev/null 2>&1; then
if curl -s http://localhost/ > /dev/null 2>&1; then echo "✅ Backend is healthy"
else
echo "⚠️ Backend health check failed (may still be starting up)"
fi
# Check frontend
if curl -f -s http://localhost > /dev/null 2>&1; then
echo "✅ Frontend is accessible" echo "✅ Frontend is accessible"
else else
echo "⚠️ Frontend check failed, but this might be normal during startup" echo "⚠️ Frontend health check failed (may still be starting up)"
fi fi
echo "" echo ""
echo "🎉 VIP Coordinator deployment completed!" echo "🎉 Deployment complete!"
echo "=============================================" echo ""
echo "📍 Access your application:" echo "📱 Access your application:"
echo " Frontend: http://localhost" echo " Frontend: http://localhost"
echo " Backend API: http://localhost:3000" echo " Backend API: http://localhost:3000"
echo " Health Check: http://localhost:3000/health"
echo "" echo ""
echo "📋 Next steps:" echo "📋 Useful commands:"
echo " 1. Open http://localhost in your browser" echo " View logs: docker-compose logs -f"
echo " 2. Click 'Continue with Google' to set up your admin account"
echo " 3. The first user to log in becomes the administrator"
echo ""
echo "🔧 Management commands:"
echo " View logs: docker-compose logs"
echo " Stop app: docker-compose down" echo " Stop app: docker-compose down"
echo " Update app: docker-compose pull && docker-compose up -d" echo " Restart: docker-compose restart"
echo " Update: docker-compose pull && docker-compose up -d"
echo "" echo ""
echo "📖 For production deployment, see DEPLOYMENT.md" echo "🆘 If you encounter issues:"
echo " 1. Check logs: docker-compose logs"
echo " 2. Verify .env configuration"
echo " 3. Ensure Google OAuth is properly configured"
echo " 4. Check that ports 80 and 3000 are available"

View File

@@ -5,8 +5,9 @@ services:
db: db:
image: postgres:15 image: postgres:15
environment: environment:
POSTGRES_DB: vip_coordinator POSTGRES_DB: ${POSTGRES_DB:-vip_coordinator}
POSTGRES_PASSWORD: changeme POSTGRES_USER: ${POSTGRES_USER:-postgres}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes: volumes:
- postgres-data:/var/lib/postgresql/data - postgres-data:/var/lib/postgresql/data
ports: ports:
@@ -22,8 +23,14 @@ services:
context: ./backend context: ./backend
target: development target: development
environment: environment:
DATABASE_URL: postgresql://postgres:changeme@db:5432/vip_coordinator DATABASE_URL: ${DATABASE_URL}
REDIS_URL: redis://redis:6379 REDIS_URL: ${REDIS_URL:-redis://redis:6379}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET}
GOOGLE_REDIRECT_URI: ${GOOGLE_REDIRECT_URI}
FRONTEND_URL: ${FRONTEND_URL}
JWT_SECRET: ${JWT_SECRET}
NODE_ENV: ${NODE_ENV:-development}
ports: ports:
- 3000:3000 - 3000:3000
depends_on: depends_on:
@@ -38,7 +45,8 @@ services:
context: ./frontend context: ./frontend
target: development target: development
environment: environment:
VITE_API_URL: http://localhost:3000/api VITE_API_URL: ${VITE_API_URL:-http://localhost:3000/api}
VITE_GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID}
ports: ports:
- 5173:5173 - 5173:5173
depends_on: depends_on:

View File

@@ -1,57 +1,88 @@
version: '3.8' version: '3.8'
services: services:
postgres:
db: image: postgres:15-alpine
image: postgres:15
environment: environment:
POSTGRES_DB: vip_coordinator POSTGRES_DB: ${POSTGRES_DB:-vip_coordinator}
POSTGRES_PASSWORD: ${DB_PASSWORD} POSTGRES_USER: ${POSTGRES_USER:-vip_user}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes: volumes:
- postgres-data:/var/lib/postgresql/data - postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped restart: unless-stopped
healthcheck: healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"] test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-vip_user} -d ${POSTGRES_DB:-vip_coordinator}"]
interval: 30s interval: 10s
timeout: 10s timeout: 5s
retries: 3 retries: 5
networks:
- vip-network
redis: redis:
image: redis:7 image: redis:7-alpine
ports:
- "6379:6379"
restart: unless-stopped restart: unless-stopped
healthcheck: healthcheck:
test: ["CMD", "redis-cli", "ping"] test: ["CMD", "redis-cli", "ping"]
interval: 30s interval: 10s
timeout: 10s timeout: 5s
retries: 3 retries: 5
networks:
- vip-network
backend: backend:
image: t72chevy/vip-coordinator:backend-latest image: t72chevy/vip-coordinator:backend-latest
environment: environment:
DATABASE_URL: postgresql://postgres:${DB_PASSWORD}@db:5432/vip_coordinator - DATABASE_URL=${DATABASE_URL}
REDIS_URL: redis://redis:6379 - NODE_ENV=${NODE_ENV:-production}
GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID} - PORT=${PORT:-3000}
GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET} - GOOGLE_CLIENT_ID=${GOOGLE_CLIENT_ID}
GOOGLE_REDIRECT_URI: ${GOOGLE_REDIRECT_URI} - GOOGLE_CLIENT_SECRET=${GOOGLE_CLIENT_SECRET}
FRONTEND_URL: ${FRONTEND_URL} - REDIS_URL=${REDIS_URL:-redis://redis:6379}
ADMIN_PASSWORD: ${ADMIN_PASSWORD} - JWT_SECRET=${JWT_SECRET:-auto-generated}
PORT: 3000
ports: ports:
- "3000:3000" - "3000:3000"
restart: unless-stopped
depends_on: depends_on:
db: postgres:
condition: service_healthy condition: service_healthy
redis: redis:
condition: service_healthy condition: service_healthy
restart: unless-stopped healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
networks:
- vip-network
frontend: frontend:
image: t72chevy/vip-coordinator:frontend-latest image: t72chevy/vip-coordinator:frontend-latest
environment:
- VITE_API_URL=${VITE_API_URL:-http://localhost:3001}
- VITE_FRONTEND_URL=${VITE_FRONTEND_URL:-http://localhost}
ports: ports:
- "80:80" - "80:80"
depends_on:
- backend
restart: unless-stopped restart: unless-stopped
depends_on:
backend:
condition: service_healthy
healthcheck:
test: ["CMD", "wget", "--no-verbose", "--tries=1", "--spider", "http://localhost:80"]
interval: 30s
timeout: 10s
retries: 3
networks:
- vip-network
volumes: volumes:
postgres-data: postgres_data:
driver: local
networks:
vip-network:
driver: bridge

View File

@@ -5,6 +5,8 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>VIP Coordinator Dashboard</title> <title>VIP Coordinator Dashboard</title>
<!-- Google Sign-In -->
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,10 @@
"dev": "node ./node_modules/vite/bin/vite.js", "dev": "node ./node_modules/vite/bin/vite.js",
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview" "preview": "vite preview",
"test": "vitest",
"test:ui": "vitest --ui",
"test:coverage": "vitest --coverage"
}, },
"dependencies": { "dependencies": {
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
@@ -21,20 +24,27 @@
"react-router-dom": "^6.15.0" "react-router-dom": "^6.15.0"
}, },
"devDependencies": { "devDependencies": {
"@testing-library/jest-dom": "^6.4.2",
"@testing-library/react": "^14.2.1",
"@testing-library/user-event": "^14.5.2",
"@types/leaflet": "^1.9.4", "@types/leaflet": "^1.9.4",
"@types/react": "^18.2.15", "@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7", "@types/react-dom": "^18.2.7",
"@typescript-eslint/eslint-plugin": "^8.15.0", "@typescript-eslint/eslint-plugin": "^8.15.0",
"@typescript-eslint/parser": "^8.15.0", "@typescript-eslint/parser": "^8.15.0",
"@vitejs/plugin-react": "^4.3.3", "@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.14", "@vitest/coverage-v8": "^1.3.1",
"@vitest/ui": "^1.3.1",
"autoprefixer": "^10.4.21",
"eslint": "^9.15.0", "eslint": "^9.15.0",
"eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.14", "eslint-plugin-react-refresh": "^0.4.14",
"@tailwindcss/postcss": "^4.1.8", "jsdom": "^24.0.0",
"postcss": "^8.5.4", "lightningcss": "^1.30.1",
"tailwindcss": "^4.1.8", "postcss": "^8.5.6",
"tailwindcss": "^3.4.17",
"typescript": "^5.6.0", "typescript": "^5.6.0",
"vite": "^5.4.10" "vite": "^5.4.10",
"vitest": "^1.3.1"
} }
} }

View File

@@ -1,6 +1,6 @@
export default { export default {
plugins: { plugins: {
'@tailwindcss/postcss': {}, tailwindcss: {},
autoprefixer: {}, autoprefixer: {},
} }
} }

View File

@@ -1,187 +1 @@
/* Modern App-specific styles using Tailwind utilities */ /* Modern App-specific styles - Component classes moved to inline Tailwind */
/* Enhanced button styles */
@layer components {
.btn-modern {
@apply px-6 py-3 rounded-xl font-semibold text-sm transition-all duration-200 shadow-lg hover:shadow-xl transform hover:-translate-y-0.5;
}
.btn-gradient-blue {
@apply bg-gradient-to-r from-blue-500 to-blue-600 hover:from-blue-600 hover:to-blue-700 text-white;
}
.btn-gradient-green {
@apply bg-gradient-to-r from-green-500 to-green-600 hover:from-green-600 hover:to-green-700 text-white;
}
.btn-gradient-purple {
@apply bg-gradient-to-r from-purple-500 to-purple-600 hover:from-purple-600 hover:to-purple-700 text-white;
}
.btn-gradient-amber {
@apply bg-gradient-to-r from-amber-500 to-amber-600 hover:from-amber-600 hover:to-amber-700 text-white;
}
}
/* Status badges */
@layer components {
.status-badge {
@apply inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold;
}
.status-scheduled {
@apply bg-blue-100 text-blue-800 border border-blue-200;
}
.status-in-progress {
@apply bg-amber-100 text-amber-800 border border-amber-200;
}
.status-completed {
@apply bg-green-100 text-green-800 border border-green-200;
}
.status-cancelled {
@apply bg-red-100 text-red-800 border border-red-200;
}
}
/* Card enhancements */
@layer components {
.card-modern {
@apply bg-white rounded-2xl shadow-lg border border-slate-200/60 overflow-hidden backdrop-blur-sm;
}
.card-header {
@apply bg-gradient-to-r from-slate-50 to-slate-100 px-6 py-4 border-b border-slate-200/60;
}
.card-content {
@apply p-6;
}
}
/* Loading states */
@layer components {
.loading-spinner {
@apply animate-spin rounded-full border-4 border-blue-600 border-t-transparent;
}
.loading-text {
@apply text-slate-600 animate-pulse;
}
.skeleton {
@apply animate-pulse bg-slate-200 rounded;
}
}
/* Form enhancements */
@layer components {
.form-modern {
@apply space-y-6;
}
.form-group-modern {
@apply space-y-2;
}
.form-label-modern {
@apply block text-sm font-semibold text-slate-700;
}
.form-input-modern {
@apply w-full px-4 py-3 border border-slate-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200;
}
.form-select-modern {
@apply w-full px-4 py-3 border border-slate-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 bg-white transition-all duration-200;
}
}
/* Animation utilities */
@layer utilities {
.animate-fade-in {
animation: fadeIn 0.5s ease-in-out;
}
.animate-slide-up {
animation: slideUp 0.3s ease-out;
}
.animate-scale-in {
animation: scaleIn 0.2s ease-out;
}
}
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideUp {
from {
transform: translateY(10px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
@keyframes scaleIn {
from {
transform: scale(0.95);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}
}
/* Responsive utilities */
@media (max-width: 768px) {
.mobile-stack {
@apply flex-col space-y-4 space-x-0;
}
.mobile-full {
@apply w-full;
}
.mobile-text-center {
@apply text-center;
}
}
/* Glass morphism effect */
@layer utilities {
.glass {
@apply bg-white/80 backdrop-blur-lg border border-white/20;
}
.glass-dark {
@apply bg-slate-900/80 backdrop-blur-lg border border-slate-700/20;
}
}
/* Hover effects */
@layer utilities {
.hover-lift {
@apply transition-transform duration-200 hover:-translate-y-1;
}
.hover-glow {
@apply transition-shadow duration-200 hover:shadow-2xl;
}
.hover-scale {
@apply transition-transform duration-200 hover:scale-105;
}
}

View File

@@ -1,57 +1,68 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom'; import { BrowserRouter as Router, Routes, Route, Link } from 'react-router-dom';
import { apiCall } from './config/api'; import { apiCall } from './utils/api';
import VipList from './pages/VipList'; import VipList from './pages/VipList';
import VipDetails from './pages/VipDetails'; import VipDetails from './pages/VipDetails';
import DriverList from './pages/DriverList'; import DriverList from './pages/DriverList';
import DriverDashboard from './pages/DriverDashboard'; import DriverDashboard from './pages/DriverDashboard';
import Dashboard from './pages/Dashboard'; import Dashboard from './pages/Dashboard';
import AdminDashboard from './pages/AdminDashboard'; import AdminDashboard from './pages/AdminDashboard';
import PendingApproval from './pages/PendingApproval';
import UserManagement from './components/UserManagement'; import UserManagement from './components/UserManagement';
import Login from './components/Login'; import Login from './components/Login';
import OAuthCallback from './components/OAuthCallback';
import './App.css'; import './App.css';
import { User } from './types';
function App() { function App() {
const [user, setUser] = useState<any>(null); const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
useEffect(() => { useEffect(() => {
// Check if user is already authenticated // Check if user is already authenticated
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
if (token) { const savedUser = localStorage.getItem('user');
if (token && savedUser) {
// Use saved user data for faster initial load
setUser(JSON.parse(savedUser));
setLoading(false);
// Then verify with server
apiCall('/auth/me', { apiCall('/auth/me', {
headers: { headers: {
'Authorization': `Bearer ${token}` 'Authorization': `Bearer ${token}`
} }
}) })
.then(res => { .then(({ data }) => {
if (res.ok) { if (data) {
return res.json(); setUser(data as User);
localStorage.setItem('user', JSON.stringify(data));
} else { } else {
// Token is invalid, remove it // Token is invalid, remove it
localStorage.removeItem('authToken'); localStorage.removeItem('authToken');
throw new Error('Invalid token'); localStorage.removeItem('user');
setUser(null);
} }
}) })
.then(userData => {
setUser(userData);
setLoading(false);
})
.catch(error => { .catch(error => {
console.error('Auth check failed:', error); console.error('Auth check failed:', error);
setLoading(false); localStorage.removeItem('authToken');
localStorage.removeItem('user');
setUser(null);
}); });
} else { } else {
setLoading(false); setLoading(false);
} }
}, []); }, []);
const handleLogin = (userData: any) => { const handleLogin = (userData: User) => {
setUser(userData); setUser(userData);
}; };
const handleLogout = () => { const handleLogout = () => {
localStorage.removeItem('authToken'); localStorage.removeItem('authToken');
localStorage.removeItem('user');
setUser(null); setUser(null);
// Optionally call logout endpoint // Optionally call logout endpoint
apiCall('/auth/logout', { method: 'POST' }) apiCall('/auth/logout', { method: 'POST' })
@@ -71,13 +82,52 @@ function App() {
// Handle OAuth callback route even when not logged in // Handle OAuth callback route even when not logged in
if (window.location.pathname === '/auth/callback' || window.location.pathname === '/auth/google/callback') { if (window.location.pathname === '/auth/callback' || window.location.pathname === '/auth/google/callback') {
return <Login onLogin={handleLogin} />; return (
<Router>
<Routes>
<Route path="*" element={<OAuthCallback />} />
</Routes>
</Router>
);
} }
if (!user) { if (!user) {
return <Login onLogin={handleLogin} />; return <Login onLogin={handleLogin} />;
} }
// Check if user is pending approval
if (user.role !== 'administrator' && (!user.status || user.status === 'pending')) {
return (
<Router>
<Routes>
<Route path="*" element={<PendingApproval />} />
</Routes>
</Router>
);
}
// Check if user is deactivated
if (user.status === 'deactivated') {
return (
<div className="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 flex items-center justify-center p-4">
<div className="bg-white rounded-2xl shadow-xl max-w-md w-full p-8 text-center">
<div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
<svg className="w-8 h-8 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
</div>
<h1 className="text-2xl font-bold text-slate-800 mb-2">Account Deactivated</h1>
<p className="text-slate-600 mb-6">
Your account has been deactivated. Please contact an administrator for assistance.
</p>
<button onClick={handleLogout} className="btn btn-secondary w-full">
Logout
</button>
</div>
</div>
);
}
return ( return (
<Router> <Router>
<div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50"> <div className="min-h-screen bg-gradient-to-br from-slate-50 via-blue-50 to-indigo-50">

View File

@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
interface DriverAvailability { interface DriverAvailability {
driverId: string; driverId: string;
@@ -60,7 +60,7 @@ const DriverSelector: React.FC<DriverSelectorProps> = ({
setLoading(true); setLoading(true);
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers/availability', { const { data } = await apiCall('/api/drivers/availability', {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
@@ -69,8 +69,7 @@ const DriverSelector: React.FC<DriverSelectorProps> = ({
body: JSON.stringify(eventTime), body: JSON.stringify(eventTime),
}); });
if (response.ok) { if (data) {
const data = await response.json();
setAvailability(data); setAvailability(data);
} }
} catch (error) { } catch (error) {

View File

@@ -1,115 +1,58 @@
import React, { useEffect, useState } from 'react'; import React, { useEffect, useState } from 'react';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import GoogleLogin from './GoogleLogin';
import './Login.css'; import './Login.css';
import { User } from '../types';
interface LoginProps { interface LoginProps {
onLogin: (user: any) => void; onLogin: (user: User) => void;
}
interface SetupStatus {
ready: boolean;
hasUsers: boolean;
missingEnvVars?: string[];
} }
const Login: React.FC<LoginProps> = ({ onLogin }) => { const Login: React.FC<LoginProps> = ({ onLogin }) => {
const [setupStatus, setSetupStatus] = useState<any>(null); const [setupStatus, setSetupStatus] = useState<SetupStatus | null>(null);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
// Check system setup status // Check system setup status
apiCall('/auth/setup') apiCall('/auth/setup')
.then(res => res.json()) .then(({ data }) => {
.then(data => {
setSetupStatus(data); setSetupStatus(data);
setLoading(false); setLoading(false);
}) })
.catch(error => { .catch(error => {
console.error('Error checking setup status:', error); console.error('Error checking setup status:', error);
setSetupStatus({ ready: true, hasUsers: false }); // Assume ready if can't check
setLoading(false); setLoading(false);
}); });
}, []);
// Check for OAuth callback code in URL const handleGoogleSuccess = (user: any, token: string) => {
const urlParams = new URLSearchParams(window.location.search); // Store the token and user data
const code = urlParams.get('code');
const error = urlParams.get('error');
const token = urlParams.get('token');
if (code && (window.location.pathname === '/auth/google/callback' || window.location.pathname === '/auth/callback')) {
// Exchange code for token
apiCall('/auth/google/exchange', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ code })
})
.then(res => {
if (!res.ok) {
throw new Error('Failed to exchange code for token');
}
return res.json();
})
.then(({ token, user }) => {
localStorage.setItem('authToken', token); localStorage.setItem('authToken', token);
localStorage.setItem('user', JSON.stringify(user));
// Call onLogin with the user data
onLogin(user); onLogin(user);
// Clean up URL and redirect to dashboard };
window.history.replaceState({}, document.title, '/');
})
.catch(error => {
console.error('OAuth exchange failed:', error);
alert('Login failed. Please try again.');
// Clean up URL
window.history.replaceState({}, document.title, '/');
});
} else if (token && (window.location.pathname === '/auth/callback' || window.location.pathname === '/auth/google/callback')) {
// Direct token from URL (from backend redirect)
localStorage.setItem('authToken', token);
apiCall('/auth/me', { const handleGoogleError = (errorMessage: string) => {
headers: { setError(errorMessage);
'Authorization': `Bearer ${token}` setTimeout(() => setError(null), 5000); // Clear error after 5 seconds
}
})
.then(res => {
if (!res.ok) {
throw new Error(`Failed to get user info: ${res.status} ${res.statusText}`);
}
return res.json();
})
.then(user => {
onLogin(user);
// Clean up URL and redirect to dashboard
window.history.replaceState({}, document.title, '/');
})
.catch(error => {
console.error('Error getting user info:', error);
alert('Login failed. Please try again.');
localStorage.removeItem('authToken');
// Clean up URL
window.history.replaceState({}, document.title, '/');
});
} else if (error) {
console.error('Authentication error:', error);
alert(`Login error: ${error}`);
// Clean up URL
window.history.replaceState({}, document.title, '/');
}
}, [onLogin]);
const handleGoogleLogin = async () => {
try {
// Get OAuth URL from backend
const response = await apiCall('/auth/google/url');
const { url } = await response.json();
// Redirect to Google OAuth
window.location.href = url;
} catch (error) {
console.error('Failed to get OAuth URL:', error);
alert('Login failed. Please try again.');
}
}; };
if (loading) { if (loading) {
return ( return (
<div className="login-container"> <div className="login-container">
<div className="login-card"> <div className="login-box">
<div className="loading">Loading...</div> <h1 className="login-title">VIP Coordinator</h1>
<p>Loading...</p>
</div> </div>
</div> </div>
); );
@@ -117,64 +60,29 @@ const Login: React.FC<LoginProps> = ({ onLogin }) => {
return ( return (
<div className="login-container"> <div className="login-container">
<div className="login-card"> <div className="login-box">
<div className="login-header"> <h1 className="login-title">VIP Coordinator</h1>
<h1>VIP Coordinator</h1> <p className="login-subtitle">Transportation Management System</p>
<p>Secure access required</p>
</div>
{!setupStatus?.firstAdminCreated && ( {error && (
<div className="setup-notice"> <div className="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded mb-4">
<h3>🚀 First Time Setup</h3> {error}
<p>The first person to log in will become the system administrator.</p>
</div> </div>
)} )}
<div className="login-content"> <div className="login-content">
<button <GoogleLogin
className="google-login-btn" onSuccess={handleGoogleSuccess}
onClick={handleGoogleLogin} onError={handleGoogleError}
disabled={false} />
>
<svg className="google-icon" viewBox="0 0 24 24">
<path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
<path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
<path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
<path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
</svg>
Continue with Google
</button>
<div className="login-info"> <div className="setup-info">
<p> {setupStatus && !setupStatus.hasUsers && (
{setupStatus?.firstAdminCreated <p className="text-sm text-amber-600 mt-4">
? "Sign in with your Google account to access the VIP Coordinator." First user to log in will become an administrator
: "Sign in with Google to set up your administrator account."
}
</p> </p>
</div>
{setupStatus && !setupStatus.setupCompleted && (
<div style={{
marginTop: '1rem',
padding: '1rem',
backgroundColor: '#fff3cd',
borderRadius: '6px',
border: '1px solid #ffeaa7',
fontSize: '0.9rem'
}}>
<strong> Setup Required:</strong>
<p style={{ margin: '0.5rem 0 0 0' }}>
Google OAuth credentials need to be configured. If the login doesn't work,
please follow the setup guide in <code>GOOGLE_OAUTH_SETUP.md</code> to configure
your Google Cloud Console credentials in the admin dashboard.
</p>
</div>
)} )}
</div> </div>
<div className="login-footer">
<p>Secure authentication powered by Google OAuth</p>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -1,5 +1,5 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import DriverSelector from './DriverSelector'; import DriverSelector from './DriverSelector';
interface ScheduleEvent { interface ScheduleEvent {
@@ -33,15 +33,14 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
const fetchSchedule = async () => { const fetchSchedule = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vipId}/schedule`, { const { data } = await apiCall(`/api/vips/${vipId}/schedule`, {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (data) {
const data = await response.json();
setSchedule(data); setSchedule(data);
} }
} catch (error) { } catch (error) {
@@ -52,15 +51,14 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
const fetchDrivers = async () => { const fetchDrivers = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers', { const { data } = await apiCall('/api/drivers', {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (data) {
const data = await response.json();
setDrivers(data); setDrivers(data);
} }
} catch (error) { } catch (error) {
@@ -305,7 +303,7 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
async function handleAddEvent(eventData: any) { async function handleAddEvent(eventData: any) {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vipId}/schedule`, { const { data } = await apiCall(`/api/vips/${vipId}/schedule`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
@@ -314,12 +312,11 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
body: JSON.stringify(eventData), body: JSON.stringify(eventData),
}); });
if (response.ok) { if (data) {
await fetchSchedule(); await fetchSchedule();
setShowAddForm(false); setShowAddForm(false);
} else { } else {
const errorData = await response.json(); throw new Error('Failed to add event');
throw errorData;
} }
} catch (error) { } catch (error) {
console.error('Error adding event:', error); console.error('Error adding event:', error);
@@ -330,7 +327,7 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
async function handleEditEvent(eventData: any) { async function handleEditEvent(eventData: any) {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vipId}/schedule/${eventData.id}`, { const { data } = await apiCall(`/api/vips/${vipId}/schedule/${eventData.id}`, {
method: 'PUT', method: 'PUT',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
@@ -339,12 +336,11 @@ const ScheduleManager: React.FC<ScheduleManagerProps> = ({ vipId, vipName }) =>
body: JSON.stringify(eventData), body: JSON.stringify(eventData),
}); });
if (response.ok) { if (data) {
await fetchSchedule(); await fetchSchedule();
setEditingEvent(null); setEditingEvent(null);
} else { } else {
const errorData = await response.json(); throw new Error('Failed to update event');
throw errorData;
} }
} catch (error) { } catch (error) {
console.error('Error updating event:', error); console.error('Error updating event:', error);

View File

@@ -1,487 +1,457 @@
import { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { API_BASE_URL } from '../config/api'; import { apiCall } from '../utils/api';
import { User } from '../types';
interface User { import { useToast } from '../contexts/ToastContext';
id: string; import { LoadingSpinner } from './LoadingSpinner';
email: string;
name: string;
picture: string;
role: string;
created_at: string;
last_sign_in_at?: string;
provider: string;
}
interface UserManagementProps { interface UserManagementProps {
currentUser: any; currentUserId: string;
} }
const UserManagement: React.FC<UserManagementProps> = ({ currentUser }) => { const UserManagement: React.FC<UserManagementProps> = ({ currentUserId }) => {
const { showToast } = useToast();
const [users, setUsers] = useState<User[]>([]); const [users, setUsers] = useState<User[]>([]);
const [pendingUsers, setPendingUsers] = useState<User[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null); const [searchTerm, setSearchTerm] = useState('');
const [activeTab, setActiveTab] = useState<'all' | 'pending'>('all'); const [filterRole, setFilterRole] = useState<string>('all');
const [updatingUser, setUpdatingUser] = useState<string | null>(null); const [filterStatus, setFilterStatus] = useState<string>('all');
const [selectedUser, setSelectedUser] = useState<User | null>(null);
const [showEditModal, setShowEditModal] = useState(false);
// Check if current user is admin useEffect(() => {
if (currentUser?.role !== 'administrator') { fetchUsers();
return ( }, []);
<div className="p-6 bg-red-50 border border-red-200 rounded-lg">
<h2 className="text-xl font-semibold text-red-800 mb-2">Access Denied</h2>
<p className="text-red-600">You need administrator privileges to access user management.</p>
</div>
);
}
const fetchUsers = async () => { const fetchUsers = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users`, { const { data } = await apiCall('/auth/users', {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' },
}
}); });
if (!response.ok) { if (data) {
throw new Error('Failed to fetch users'); setUsers(data);
} else {
showToast('Failed to load users', 'error');
} }
} catch (error) {
const userData = await response.json(); showToast('Error loading users', 'error');
setUsers(userData);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch users');
} finally { } finally {
setLoading(false); setLoading(false);
} }
}; };
const fetchPendingUsers = async () => { const handleApprove = async (userEmail: string, role: string) => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users/pending/list`, { const { data } = await apiCall(`/auth/users/${userEmail}/approve`, {
method: 'POST',
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json',
}
});
if (!response.ok) {
throw new Error('Failed to fetch pending users');
}
const pendingData = await response.json();
setPendingUsers(pendingData);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch pending users');
}
};
const updateUserRole = async (userEmail: string, newRole: string) => {
setUpdatingUser(userEmail);
try {
const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users/${userEmail}/role`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}, },
body: JSON.stringify({ role: newRole }) body: JSON.stringify({ role }),
}); });
if (!response.ok) { if (data) {
throw new Error('Failed to update user role'); showToast('User approved successfully!', 'success');
}
// Refresh users list
await fetchUsers();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to update user role');
} finally {
setUpdatingUser(null);
}
};
const deleteUser = async (userEmail: string, userName: string) => {
if (!confirm(`Are you sure you want to delete user "${userName}"? This action cannot be undone.`)) {
return;
}
try {
const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users/${userEmail}`, {
method: 'DELETE',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to delete user');
}
// Refresh users list
await fetchUsers();
await fetchPendingUsers();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to delete user');
}
};
const approveUser = async (userEmail: string) => {
setUpdatingUser(userEmail);
try {
const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users/${userEmail}/approval`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ status: 'approved' })
});
if (!response.ok) {
throw new Error('Failed to approve user');
}
// Refresh both lists
await fetchUsers();
await fetchPendingUsers();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to approve user');
} finally {
setUpdatingUser(null);
}
};
const denyUser = async (userEmail: string, userName: string) => {
if (!confirm(`Are you sure you want to deny access for "${userName}"?`)) {
return;
}
setUpdatingUser(userEmail);
try {
const token = localStorage.getItem('authToken');
const response = await fetch(`${API_BASE_URL}/auth/users/${userEmail}/approval`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({ status: 'denied' })
});
if (!response.ok) {
throw new Error('Failed to deny user');
}
// Refresh both lists
await fetchUsers();
await fetchPendingUsers();
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to deny user');
} finally {
setUpdatingUser(null);
}
};
useEffect(() => {
fetchUsers(); fetchUsers();
fetchPendingUsers(); } else {
}, []); showToast('Failed to approve user', 'error');
useEffect(() => {
if (activeTab === 'pending') {
fetchPendingUsers();
} }
}, [activeTab]); } catch (error) {
showToast('Error approving user', 'error');
}
};
const formatDate = (dateString: string) => { const handleReject = async (userEmail: string) => {
return new Date(dateString).toLocaleDateString('en-US', { if (!confirm('Are you sure you want to reject this user?')) return;
year: 'numeric',
month: 'short', try {
day: 'numeric', const token = localStorage.getItem('authToken');
hour: '2-digit', const { data } = await apiCall(`/auth/users/${userEmail}/reject`, {
minute: '2-digit' method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
}); });
};
const getRoleBadgeColor = (role: string) => { if (data) {
switch (role) { showToast('User rejected', 'success');
case 'administrator': fetchUsers();
return 'bg-red-100 text-red-800 border-red-200'; } else {
case 'coordinator': showToast('Failed to reject user', 'error');
return 'bg-blue-100 text-blue-800 border-blue-200'; }
case 'driver': } catch (error) {
return 'bg-green-100 text-green-800 border-green-200'; showToast('Error rejecting user', 'error');
default:
return 'bg-gray-100 text-gray-800 border-gray-200';
} }
}; };
const handleDeactivate = async (userEmail: string) => {
if (!confirm('Are you sure you want to deactivate this user?')) return;
try {
const token = localStorage.getItem('authToken');
const { data } = await apiCall(`/auth/users/${userEmail}/deactivate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (data) {
showToast('User deactivated', 'success');
fetchUsers();
} else {
showToast('Failed to deactivate user', 'error');
}
} catch (error) {
showToast('Error deactivating user', 'error');
}
};
const handleReactivate = async (userEmail: string) => {
try {
const token = localStorage.getItem('authToken');
const { data } = await apiCall(`/auth/users/${userEmail}/reactivate`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (data) {
showToast('User reactivated', 'success');
fetchUsers();
} else {
showToast('Failed to reactivate user', 'error');
}
} catch (error) {
showToast('Error reactivating user', 'error');
}
};
const handleRoleChange = async (userEmail: string, newRole: string) => {
try {
const token = localStorage.getItem('authToken');
const { data } = await apiCall(`/auth/users/${userEmail}/role`, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ role: newRole }),
});
if (data) {
showToast('Role updated successfully', 'success');
fetchUsers();
setShowEditModal(false);
} else {
showToast('Failed to update role', 'error');
}
} catch (error) {
showToast('Error updating role', 'error');
}
};
// Filter users
const filteredUsers = users.filter(user => {
const matchesSearch = searchTerm === '' ||
user.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.email.toLowerCase().includes(searchTerm.toLowerCase()) ||
user.organization?.toLowerCase().includes(searchTerm.toLowerCase());
const matchesRole = filterRole === 'all' || user.role === filterRole;
const matchesStatus = filterStatus === 'all' || user.status === filterStatus;
return matchesSearch && matchesRole && matchesStatus;
});
// Separate pending users
const pendingUsers = filteredUsers.filter(u => u.status === 'pending');
const activeUsers = filteredUsers.filter(u => u.status !== 'pending');
if (loading) { if (loading) {
return ( return (
<div className="p-6"> <div className="flex justify-center items-center h-64">
<div className="animate-pulse"> <LoadingSpinner size="lg" message="Loading users..." />
<div className="h-8 bg-gray-200 rounded-lg w-1/4 mb-6"></div>
<div className="space-y-4">
{[1, 2, 3].map(i => (
<div key={i} className="h-20 bg-gray-200 rounded-lg"></div>
))}
</div>
</div>
</div> </div>
); );
} }
return ( return (
<div className="p-6"> <div className="space-y-6">
<div className="mb-6"> {/* Filters */}
<h2 className="text-2xl font-bold text-gray-900 mb-2">User Management</h2> <div className="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
<p className="text-gray-600">Manage user accounts and permissions (PostgreSQL Database)</p> <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
<div className="md:col-span-2">
<input
type="text"
placeholder="Search users by name, email, or organization..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="form-input w-full"
/>
</div>
<div>
<select
value={filterRole}
onChange={(e) => setFilterRole(e.target.value)}
className="form-select w-full"
>
<option value="all">All Roles</option>
<option value="administrator">Administrator</option>
<option value="coordinator">Coordinator</option>
<option value="driver">Driver</option>
<option value="viewer">Viewer</option>
</select>
</div>
<div>
<select
value={filterStatus}
onChange={(e) => setFilterStatus(e.target.value)}
className="form-select w-full"
>
<option value="all">All Status</option>
<option value="pending">Pending</option>
<option value="active">Active</option>
<option value="deactivated">Deactivated</option>
</select>
</div>
</div>
</div> </div>
{error && ( {/* Pending Users */}
<div className="mb-6 p-4 bg-red-50 border border-red-200 rounded-lg">
<p className="text-red-600">{error}</p>
<button
onClick={() => setError(null)}
className="mt-2 text-sm text-red-500 hover:text-red-700"
>
Dismiss
</button>
</div>
)}
{/* Tab Navigation */}
<div className="mb-6">
<div className="border-b border-gray-200">
<nav className="-mb-px flex space-x-8">
<button
onClick={() => setActiveTab('all')}
className={`py-2 px-1 border-b-2 font-medium text-sm ${
activeTab === 'all'
? 'border-blue-500 text-blue-600'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
}`}
>
👥 All Users ({users.length})
</button>
<button
onClick={() => setActiveTab('pending')}
className={`py-2 px-1 border-b-2 font-medium text-sm ${
activeTab === 'pending'
? 'border-orange-500 text-orange-600'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
}`}
>
Pending Approval ({pendingUsers.length})
{pendingUsers.length > 0 && ( {pendingUsers.length > 0 && (
<span className="ml-2 inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-orange-100 text-orange-800"> <div className="bg-white rounded-xl shadow-sm border border-slate-200">
{pendingUsers.length} <div className="p-6 border-b border-slate-200">
</span> <h3 className="text-lg font-semibold text-slate-800">
)} Pending Approval ({pendingUsers.length})
</button>
</nav>
</div>
</div>
{/* Content based on active tab */}
{activeTab === 'all' && (
<div className="bg-white shadow-sm border border-gray-200 rounded-lg overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 bg-gray-50">
<h3 className="text-lg font-medium text-gray-900">
All Users ({users.length})
</h3> </h3>
</div> </div>
<div className="divide-y divide-slate-200">
<div className="divide-y divide-gray-200"> {pendingUsers.map(user => (
{users.map((user) => ( <div key={user.id} className="p-6 hover:bg-slate-50">
<div key={user.email} className="p-6 hover:bg-gray-50"> <div className="flex items-start justify-between">
<div className="flex items-center justify-between"> <div className="flex items-start space-x-4">
<div className="flex items-center space-x-4"> <div className="w-12 h-12 bg-amber-100 rounded-full flex items-center justify-center">
{user.picture ? ( <span className="text-lg font-semibold text-amber-700">
<img
src={user.picture}
alt={user.name}
className="w-12 h-12 rounded-full"
/>
) : (
<div className="w-12 h-12 rounded-full bg-gray-300 flex items-center justify-center">
<span className="text-gray-600 font-medium">
{user.name.charAt(0).toUpperCase()} {user.name.charAt(0).toUpperCase()}
</span> </span>
</div> </div>
)}
<div> <div>
<h4 className="text-lg font-medium text-gray-900">{user.name}</h4> <h4 className="font-semibold text-slate-800">{user.name}</h4>
<p className="text-gray-600">{user.email}</p> <p className="text-sm text-slate-600">{user.email}</p>
<div className="flex items-center space-x-4 mt-1 text-sm text-gray-500"> <div className="mt-2 space-y-1 text-sm">
<span>Joined: {formatDate(user.created_at)}</span> <p><span className="text-slate-500">Organization:</span> {user.organization || 'Not provided'}</p>
{user.last_sign_in_at && ( <p><span className="text-slate-500">Phone:</span> {user.phone || 'Not provided'}</p>
<span>Last login: {formatDate(user.last_sign_in_at)}</span> <p><span className="text-slate-500">Requested Role:</span>
)} <span className="ml-1 font-medium capitalize">{user.onboardingData?.requestedRole}</span>
<span className="capitalize">via {user.provider}</span> </p>
<p className="mt-2 p-2 bg-slate-50 rounded text-slate-700">
<span className="font-medium">Reason:</span> {user.onboardingData?.reason}
</p>
{user.onboardingData?.vehicleType && (
<div className="mt-2 p-2 bg-blue-50 rounded">
<p className="font-medium text-blue-900 mb-1">Driver Details:</p>
<p className="text-sm text-blue-800">
Vehicle: {user.onboardingData.vehicleType}
({user.onboardingData.vehicleCapacity} passengers) -
{user.onboardingData.licensePlate}
</p>
</div> </div>
)}
</div>
</div>
</div>
<div className="flex space-x-2">
<select
className="form-select text-sm"
defaultValue={user.onboardingData?.requestedRole}
onChange={(e) => {
const role = e.target.value;
if (confirm(`Approve ${user.name} as ${role}?`)) {
handleApprove(user.email, role);
}
}}
>
<option value="">Select role to approve</option>
<option value="administrator">Approve as Administrator</option>
<option value="coordinator">Approve as Coordinator</option>
<option value="driver">Approve as Driver</option>
<option value="viewer">Approve as Viewer</option>
</select>
<button
onClick={() => handleReject(user.email)}
className="btn btn-danger btn-sm"
>
Reject
</button>
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Active/All Users */}
<div className="bg-white rounded-xl shadow-sm border border-slate-200">
<div className="p-6 border-b border-slate-200">
<h3 className="text-lg font-semibold text-slate-800">
Users ({activeUsers.length})
</h3>
</div>
<div className="overflow-x-auto">
<table className="w-full">
<thead className="bg-slate-50 border-b border-slate-200">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
User
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Role
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Organization
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Status
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Approved By
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-slate-500 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-200">
{activeUsers.map(user => (
<tr key={user.id} className="hover:bg-slate-50">
<td className="px-6 py-4 whitespace-nowrap">
<div className="flex items-center">
<div className="w-10 h-10 bg-slate-200 rounded-full flex items-center justify-center">
<span className="text-sm font-semibold text-slate-700">
{user.name.charAt(0).toUpperCase()}
</span>
</div>
<div className="ml-4">
<div className="text-sm font-medium text-slate-900">{user.name}</div>
<div className="text-sm text-slate-500">{user.email}</div>
</div>
</div>
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className="px-2 inline-flex text-xs leading-5 font-semibold rounded-full bg-blue-100 text-blue-800 capitalize">
{user.role}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
{user.organization || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${
user.status === 'active'
? 'bg-green-100 text-green-800'
: 'bg-red-100 text-red-800'
}`}>
{user.status}
</span>
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm text-slate-500">
{user.approvedBy || '-'}
</td>
<td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
<button
onClick={() => {
setSelectedUser(user);
setShowEditModal(true);
}}
className="text-amber-600 hover:text-amber-900 mr-3"
disabled={user.id === currentUserId}
>
Edit
</button>
{user.status === 'active' ? (
<button
onClick={() => handleDeactivate(user.email)}
className="text-red-600 hover:text-red-900"
disabled={user.id === currentUserId}
>
Deactivate
</button>
) : (
<button
onClick={() => handleReactivate(user.email)}
className="text-green-600 hover:text-green-900"
>
Reactivate
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div> </div>
</div> </div>
<div className="flex items-center space-x-4"> {/* Edit Modal */}
<div className="flex items-center space-x-2"> {showEditModal && selectedUser && (
<span className="text-sm text-gray-600">Role:</span> <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-xl max-w-md w-full p-6">
<h3 className="text-lg font-semibold text-slate-800 mb-4">
Edit User: {selectedUser.name}
</h3>
<div className="space-y-4">
<div>
<label className="block text-sm font-medium text-slate-700 mb-2">
Role
</label>
<select <select
value={user.role} value={selectedUser.role}
onChange={(e) => updateUserRole(user.email, e.target.value)} onChange={(e) => handleRoleChange(selectedUser.id, e.target.value)}
disabled={updatingUser === user.email || user.email === currentUser.email} className="form-select w-full"
className={`px-3 py-1 border rounded-md text-sm font-medium ${getRoleBadgeColor(user.role)} ${ disabled={selectedUser.id === currentUserId}
updatingUser === user.email ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer hover:bg-opacity-80'
}`}
> >
<option value="coordinator">Coordinator</option>
<option value="administrator">Administrator</option> <option value="administrator">Administrator</option>
<option value="coordinator">Coordinator</option>
<option value="driver">Driver</option> <option value="driver">Driver</option>
<option value="viewer">Viewer</option>
</select> </select>
</div> </div>
{user.email !== currentUser.email && ( <div className="bg-slate-50 rounded-lg p-4 text-sm">
<h4 className="font-medium text-slate-800 mb-2">Audit Information:</h4>
<p className="text-slate-600">Created: {new Date(selectedUser.createdAt || '').toLocaleString()}</p>
{selectedUser.approvedBy && (
<p className="text-slate-600">Approved by: {selectedUser.approvedBy}</p>
)}
{selectedUser.approvedAt && (
<p className="text-slate-600">Approved at: {new Date(selectedUser.approvedAt).toLocaleString()}</p>
)}
{selectedUser.lastLogin && (
<p className="text-slate-600">Last login: {new Date(selectedUser.lastLogin).toLocaleString()}</p>
)}
</div>
</div>
<div className="flex justify-end space-x-3 mt-6">
<button <button
onClick={() => deleteUser(user.email, user.name)} onClick={() => setShowEditModal(false)}
className="px-3 py-1 text-sm text-red-600 hover:text-red-800 hover:bg-red-50 rounded-md border border-red-200 transition-colors" className="btn btn-secondary"
> >
🗑 Delete Close
</button>
)}
{user.email === currentUser.email && (
<span className="px-3 py-1 text-sm text-blue-600 bg-blue-50 rounded-md border border-blue-200">
👤 You
</span>
)}
</div>
</div>
</div>
))}
</div>
{users.length === 0 && (
<div className="p-6 text-center text-gray-500">
No users found.
</div>
)}
</div>
)}
{/* Pending Users Tab */}
{activeTab === 'pending' && (
<div className="bg-white shadow-sm border border-gray-200 rounded-lg overflow-hidden">
<div className="px-6 py-4 border-b border-gray-200 bg-orange-50">
<h3 className="text-lg font-medium text-gray-900">
Pending Approval ({pendingUsers.length})
</h3>
<p className="text-sm text-gray-600 mt-1">
Users waiting for administrator approval to access the system
</p>
</div>
<div className="divide-y divide-gray-200">
{pendingUsers.map((user) => (
<div key={user.email} className="p-6 hover:bg-gray-50">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
{user.picture ? (
<img
src={user.picture}
alt={user.name}
className="w-12 h-12 rounded-full"
/>
) : (
<div className="w-12 h-12 rounded-full bg-gray-300 flex items-center justify-center">
<span className="text-gray-600 font-medium">
{user.name.charAt(0).toUpperCase()}
</span>
</div>
)}
<div>
<h4 className="text-lg font-medium text-gray-900">{user.name}</h4>
<p className="text-gray-600">{user.email}</p>
<div className="flex items-center space-x-4 mt-1 text-sm text-gray-500">
<span>Requested: {formatDate(user.created_at)}</span>
<span className="capitalize">via {user.provider}</span>
<span className={`px-2 py-1 rounded-full text-xs font-medium ${
getRoleBadgeColor(user.role)
}`}>
{user.role}
</span>
</div>
</div>
</div>
<div className="flex items-center space-x-3">
<button
onClick={() => approveUser(user.email)}
disabled={updatingUser === user.email}
className={`px-4 py-2 text-sm font-medium text-white bg-green-600 hover:bg-green-700 rounded-md transition-colors ${
updatingUser === user.email ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{updatingUser === user.email ? '⏳ Approving...' : '✅ Approve'}
</button>
<button
onClick={() => denyUser(user.email, user.name)}
disabled={updatingUser === user.email}
className={`px-4 py-2 text-sm font-medium text-white bg-red-600 hover:bg-red-700 rounded-md transition-colors ${
updatingUser === user.email ? 'opacity-50 cursor-not-allowed' : ''
}`}
>
{updatingUser === user.email ? '⏳ Denying...' : '❌ Deny'}
</button> </button>
</div> </div>
</div> </div>
</div> </div>
))}
</div>
{pendingUsers.length === 0 && (
<div className="p-6 text-center text-gray-500">
<div className="text-6xl mb-4"></div>
<p className="text-lg font-medium mb-2">No pending approvals</p>
<p className="text-sm">All users have been processed.</p>
</div>
)} )}
</div> </div>
)}
<div className="mt-6 p-4 bg-blue-50 border border-blue-200 rounded-lg">
<h4 className="font-medium text-blue-900 mb-2">Role Descriptions:</h4>
<ul className="text-sm text-blue-800 space-y-1">
<li><strong>Administrator:</strong> Full access to all features including user management</li>
<li><strong>Coordinator:</strong> Can manage VIPs, drivers, and schedules</li>
<li><strong>Driver:</strong> Can view assigned schedules and update status</li>
</ul>
</div>
<div className="mt-4 p-4 bg-orange-50 border border-orange-200 rounded-lg">
<h4 className="font-medium text-orange-900 mb-2">🔐 User Approval System:</h4>
<p className="text-sm text-orange-800">
New users (except the first administrator) require approval before accessing the system.
Users with pending approval will see a "pending approval" message when they try to sign in.
</p>
</div>
<div className="mt-4 p-4 bg-green-50 border border-green-200 rounded-lg">
<h4 className="font-medium text-green-900 mb-2"> PostgreSQL Database:</h4>
<p className="text-sm text-green-800">
User data is stored in your PostgreSQL database with proper indexing and relationships.
All user management operations are transactional and fully persistent across server restarts.
</p>
</div>
</div>
); );
}; };

View File

@@ -1,23 +1,13 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { VipFormData } from '../types';
import { useToast } from '../contexts/ToastContext';
interface Flight { interface Flight {
flightNumber: string; flightNumber: string;
flightDate: string; flightDate: string;
segment: number; segment: number;
validated?: boolean; validated?: boolean;
validationData?: any; validationData?: Record<string, unknown>;
}
interface VipFormData {
name: string;
organization: string;
department: 'Office of Development' | 'Admin';
transportMode: 'flight' | 'self-driving';
flights?: Flight[];
expectedArrival?: string;
needsAirportPickup?: boolean;
needsVenueTransport: boolean;
notes: string;
} }
interface VipFormProps { interface VipFormProps {
@@ -26,6 +16,7 @@ interface VipFormProps {
} }
const VipForm: React.FC<VipFormProps> = ({ onSubmit, onCancel }) => { const VipForm: React.FC<VipFormProps> = ({ onSubmit, onCancel }) => {
const { showToast } = useToast();
const [formData, setFormData] = useState<VipFormData>({ const [formData, setFormData] = useState<VipFormData>({
name: '', name: '',
organization: '', organization: '',

View File

@@ -1,13 +1,79 @@
// API Configuration // API Configuration
// VITE_API_URL must be set at build time - no fallback to prevent production issues // Use relative URLs by default so it works with any domain/reverse proxy
export const API_BASE_URL = (import.meta as any).env.VITE_API_URL; export const API_BASE_URL = (import.meta as any).env.VITE_API_URL || '';
if (!API_BASE_URL) { // API Error class
throw new Error('VITE_API_URL environment variable is required'); export class ApiError extends Error {
constructor(
message: string,
public status?: number,
public code?: string,
public details?: unknown
) {
super(message);
this.name = 'ApiError';
}
} }
// Helper function for API calls // Helper function for API calls with error handling
export const apiCall = (endpoint: string, options?: RequestInit) => { export const apiCall = async (endpoint: string, options?: RequestInit) => {
const url = endpoint.startsWith('/') ? `${API_BASE_URL}${endpoint}` : endpoint; const url = endpoint.startsWith('/') ? `${API_BASE_URL}${endpoint}` : endpoint;
return fetch(url, options);
// Get auth token from localStorage
const authToken = localStorage.getItem('authToken');
// Build headers
const headers: HeadersInit = {
'Content-Type': 'application/json',
...options?.headers,
};
// Add authorization header if token exists
if (authToken) {
headers['Authorization'] = `Bearer ${authToken}`;
}
try {
const response = await fetch(url, {
...options,
headers,
});
// Handle non-2xx responses
if (!response.ok) {
let errorData;
try {
errorData = await response.json();
} catch {
errorData = { error: { message: response.statusText } };
}
throw new ApiError(
errorData.error?.message || `Request failed with status ${response.status}`,
response.status,
errorData.error?.code,
errorData.error?.details
);
}
// Try to parse JSON response
const contentType = response.headers.get('content-type');
if (contentType && contentType.includes('application/json')) {
const data = await response.json();
return { response, data };
}
return { response, data: null };
} catch (error) {
// Network errors or other issues
if (error instanceof ApiError) {
throw error;
}
throw new ApiError(
error instanceof Error ? error.message : 'Network request failed',
undefined,
'NETWORK_ERROR'
);
}
}; };

View File

@@ -1,4 +1,6 @@
@import "tailwindcss"; @tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom base styles */ /* Custom base styles */
@layer base { @layer base {
@@ -10,25 +12,59 @@
text-rendering: optimizeLegibility; text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale; -moz-osx-font-smoothing: grayscale;
-webkit-text-size-adjust: 100%;
/* Color scheme variables */
color-scheme: light dark;
--color-primary: #2563eb;
--color-primary-hover: #1d4ed8;
--color-secondary: #10b981;
--color-secondary-hover: #059669;
--color-danger: #ef4444;
--color-danger-hover: #dc2626;
--color-text: #1f2937;
--color-text-secondary: #6b7280;
--color-bg: #ffffff;
--color-bg-secondary: #f9fafb;
--color-border: #e5e7eb;
}
@media (prefers-color-scheme: dark) {
:root {
--color-text: #f9fafb;
--color-text-secondary: #d1d5db;
--color-bg: #111827;
--color-bg-secondary: #1f2937;
--color-border: #374151;
}
} }
* { * {
margin: 0;
padding: 0;
box-sizing: border-box; box-sizing: border-box;
} }
body { body {
margin: 0; color: var(--color-text);
min-width: 320px; background-color: var(--color-bg);
min-height: 100vh; min-height: 100vh;
background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
color: #1e293b;
} }
#root { h1, h2, h3, h4, h5, h6 {
width: 100%; font-weight: 600;
margin: 0 auto; line-height: 1.3;
text-align: left; margin-bottom: 0.5em;
}
a {
color: var(--color-primary);
text-decoration: none;
transition: color 0.2s;
}
a:hover {
color: var(--color-primary-hover);
}
} }
/* Smooth scrolling */ /* Smooth scrolling */
@@ -36,315 +72,21 @@
scroll-behavior: smooth; scroll-behavior: smooth;
} }
/* Focus styles */ /* Custom scrollbar */
*:focus { ::-webkit-scrollbar {
outline: 2px solid #3b82f6; width: 10px;
outline-offset: 2px; height: 10px;
}
} }
/* Custom component styles */ ::-webkit-scrollbar-track {
@layer components { background: var(--color-bg-secondary);
/* Modern Button Styles */
.btn {
padding-left: 1.5rem;
padding-right: 1.5rem;
padding-top: 0.75rem;
padding-bottom: 0.75rem;
border-radius: 0.75rem;
font-weight: 600;
font-size: 0.875rem;
transition: all 0.2s;
outline: none;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
transform: translateY(0);
} }
.btn:focus { ::-webkit-scrollbar-thumb {
ring: 2px; background: var(--color-text-secondary);
ring-offset: 2px; border-radius: 5px;
} }
.btn:hover { ::-webkit-scrollbar-thumb:hover {
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); background: var(--color-text);
transform: translateY(-0.125rem);
}
.btn-primary {
background: linear-gradient(to right, #3b82f6, #2563eb);
color: white;
}
.btn-primary:hover {
background: linear-gradient(to right, #2563eb, #1d4ed8);
}
.btn-primary:focus {
ring-color: #3b82f6;
}
.btn-secondary {
background: linear-gradient(to right, #64748b, #475569);
color: white;
}
.btn-secondary:hover {
background: linear-gradient(to right, #475569, #334155);
}
.btn-secondary:focus {
ring-color: #64748b;
}
.btn-danger {
background: linear-gradient(to right, #ef4444, #dc2626);
color: white;
}
.btn-danger:hover {
background: linear-gradient(to right, #dc2626, #b91c1c);
}
.btn-danger:focus {
ring-color: #ef4444;
}
.btn-success {
background: linear-gradient(to right, #22c55e, #16a34a);
color: white;
}
.btn-success:hover {
background: linear-gradient(to right, #16a34a, #15803d);
}
.btn-success:focus {
ring-color: #22c55e;
}
/* Modern Card Styles */
.card {
background-color: white;
border-radius: 1rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
border: 1px solid rgba(226, 232, 240, 0.6);
overflow: hidden;
backdrop-filter: blur(4px);
}
/* Modern Form Styles */
.form-group {
margin-bottom: 1.5rem;
}
.form-label {
display: block;
font-size: 0.875rem;
font-weight: 600;
color: #334155;
margin-bottom: 0.75rem;
}
.form-input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
background-color: white;
transition: all 0.2s;
}
.form-input:focus {
outline: none;
ring: 2px;
ring-color: #3b82f6;
border-color: #3b82f6;
}
.form-select {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
background-color: white;
transition: all 0.2s;
}
.form-select:focus {
outline: none;
ring: 2px;
ring-color: #3b82f6;
border-color: #3b82f6;
}
.form-textarea {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
background-color: white;
transition: all 0.2s;
resize: none;
}
.form-textarea:focus {
outline: none;
ring: 2px;
ring-color: #3b82f6;
border-color: #3b82f6;
}
.form-checkbox {
width: 1.25rem;
height: 1.25rem;
color: #2563eb;
border: 1px solid #cbd5e1;
border-radius: 0.25rem;
}
.form-checkbox:focus {
ring: 2px;
ring-color: #3b82f6;
}
.form-radio {
width: 1rem;
height: 1rem;
color: #2563eb;
border: 1px solid #cbd5e1;
}
.form-radio:focus {
ring: 2px;
ring-color: #3b82f6;
}
/* Modal Styles */
.modal-overlay {
position: fixed;
inset: 0;
background-color: rgba(0, 0, 0, 0.5);
backdrop-filter: blur(4px);
display: flex;
justify-content: center;
align-items: center;
z-index: 50;
padding: 1rem;
}
.modal-content {
background-color: white;
border-radius: 1rem;
box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
max-width: 56rem;
width: 100%;
max-height: 90vh;
overflow-y: auto;
}
.modal-header {
background: linear-gradient(to right, #eff6ff, #eef2ff);
padding: 1.5rem 2rem;
border-bottom: 1px solid rgba(226, 232, 240, 0.6);
}
.modal-body {
padding: 2rem;
}
.modal-footer {
background-color: #f8fafc;
padding: 1.5rem 2rem;
border-top: 1px solid rgba(226, 232, 240, 0.6);
display: flex;
justify-content: flex-end;
gap: 1rem;
}
/* Form Actions */
.form-actions {
display: flex;
justify-content: flex-end;
gap: 1rem;
padding-top: 1.5rem;
border-top: 1px solid rgba(226, 232, 240, 0.6);
margin-top: 2rem;
}
/* Form Sections */
.form-section {
background-color: #f8fafc;
border-radius: 0.75rem;
padding: 1.5rem;
margin-bottom: 1.5rem;
border: 1px solid rgba(226, 232, 240, 0.6);
}
.form-section-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1rem;
}
.form-section-title {
font-size: 1.125rem;
font-weight: 700;
color: #1e293b;
}
/* Radio Group */
.radio-group {
display: flex;
gap: 1.5rem;
margin-top: 0.75rem;
}
.radio-option {
display: flex;
align-items: center;
cursor: pointer;
background-color: white;
border-radius: 0.5rem;
padding: 0.75rem 1rem;
border: 1px solid #e2e8f0;
transition: all 0.2s;
}
.radio-option:hover {
border-color: #93c5fd;
background-color: #eff6ff;
}
.radio-option.selected {
border-color: #3b82f6;
background-color: #eff6ff;
ring: 2px;
ring-color: #bfdbfe;
}
/* Checkbox Group */
.checkbox-option {
display: flex;
align-items: center;
cursor: pointer;
background-color: white;
border-radius: 0.5rem;
padding: 0.75rem 1rem;
border: 1px solid #e2e8f0;
transition: all 0.2s;
}
.checkbox-option:hover {
border-color: #93c5fd;
background-color: #eff6ff;
}
.checkbox-option.checked {
border-color: #3b82f6;
background-color: #eff6ff;
}
} }

View File

@@ -2,9 +2,15 @@ import React from 'react'
import ReactDOM from 'react-dom/client' import ReactDOM from 'react-dom/client'
import App from './App.tsx' import App from './App.tsx'
import './index.css' import './index.css'
import { ErrorBoundary } from './components/ErrorBoundary'
import { ToastProvider } from './contexts/ToastContext'
ReactDOM.createRoot(document.getElementById('root')!).render( ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode> <React.StrictMode>
<ErrorBoundary>
<ToastProvider>
<App /> <App />
</ToastProvider>
</ErrorBoundary>
</React.StrictMode>, </React.StrictMode>,
) )

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
interface ScheduleEvent { interface ScheduleEvent {
id: string; id: string;
@@ -83,28 +83,27 @@ const Dashboard: React.FC = () => {
'Content-Type': 'application/json' 'Content-Type': 'application/json'
}; };
const [vipsResponse, driversResponse] = await Promise.all([ const [vipsResult, driversResult] = await Promise.all([
apiCall('/api/vips', { headers: authHeaders }), apiCall('/api/vips', { headers: authHeaders }),
apiCall('/api/drivers', { headers: authHeaders }) apiCall('/api/drivers', { headers: authHeaders })
]); ]);
if (!vipsResponse.ok || !driversResponse.ok) { const vipsData = vipsResult.data;
const driversData = driversResult.data;
if (!vipsData || !driversData) {
throw new Error('Failed to fetch data'); 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 // Fetch schedule for each VIP and determine current/next events
const vipsWithSchedules = await Promise.all( const vipsWithSchedules = await Promise.all(
vipsData.map(async (vip: Vip) => { vipsData.map(async (vip: Vip) => {
try { try {
const scheduleResponse = await apiCall(`/api/vips/${vip.id}/schedule`, { const { data: scheduleData } = await apiCall(`/api/vips/${vip.id}/schedule`, {
headers: authHeaders headers: authHeaders
}); });
if (scheduleResponse.ok) { if (scheduleData) {
const scheduleData = await scheduleResponse.json();
const currentEvent = getCurrentEvent(scheduleData); const currentEvent = getCurrentEvent(scheduleData);
const nextEvent = getNextEvent(scheduleData); const nextEvent = getNextEvent(scheduleData);

View File

@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom'; import { useParams, Link } from 'react-router-dom';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import GanttChart from '../components/GanttChart'; import GanttChart from '../components/GanttChart';
interface DriverScheduleEvent { interface DriverScheduleEvent {
@@ -42,15 +42,14 @@ const DriverDashboard: React.FC = () => {
const fetchDriverSchedule = async () => { const fetchDriverSchedule = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/drivers/${driverId}/schedule`, { const { data } = await apiCall(`/api/drivers/${driverId}/schedule`, {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (data) {
const data = await response.json();
setScheduleData(data); setScheduleData(data);
} else { } else {
setError('Driver not found'); setError('Driver not found');

View File

@@ -1,23 +1,19 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import DriverForm from '../components/DriverForm'; import DriverForm from '../components/DriverForm';
import EditDriverForm from '../components/EditDriverForm'; import EditDriverForm from '../components/EditDriverForm';
import { Driver, DriverFormData } from '../types';
interface Driver { import { useToast } from '../contexts/ToastContext';
id: string; import { LoadingSpinner } from '../components/LoadingSpinner';
name: string;
phone: string;
currentLocation: { lat: number; lng: number };
assignedVipIds: string[];
vehicleCapacity?: number;
}
const DriverList: React.FC = () => { const DriverList: React.FC = () => {
const { showToast } = useToast();
const [drivers, setDrivers] = useState<Driver[]>([]); const [drivers, setDrivers] = useState<Driver[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [showForm, setShowForm] = useState(false); const [showForm, setShowForm] = useState(false);
const [editingDriver, setEditingDriver] = useState<Driver | null>(null); const [editingDriver, setEditingDriver] = useState<Driver | null>(null);
const [searchTerm, setSearchTerm] = useState('');
// Function to extract last name for sorting // Function to extract last name for sorting
const getLastName = (fullName: string) => { const getLastName = (fullName: string) => {
@@ -38,19 +34,18 @@ const DriverList: React.FC = () => {
const fetchDrivers = async () => { const fetchDrivers = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers', { const { data } = await apiCall('/api/drivers', {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (data) {
const data = await response.json();
const sortedDrivers = sortDriversByLastName(data); const sortedDrivers = sortDriversByLastName(data);
setDrivers(sortedDrivers); setDrivers(sortedDrivers);
} else { } else {
console.error('Failed to fetch drivers:', response.status); console.error('Failed to fetch drivers');
} }
} catch (error) { } catch (error) {
console.error('Error fetching drivers:', error); console.error('Error fetching drivers:', error);
@@ -62,7 +57,7 @@ const DriverList: React.FC = () => {
fetchDrivers(); fetchDrivers();
}, []); }, []);
const handleAddDriver = async (driverData: any) => { const handleAddDriver = async (driverData: DriverFormData) => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/drivers', { const response = await apiCall('/api/drivers', {
@@ -78,15 +73,18 @@ const DriverList: React.FC = () => {
const newDriver = await response.json(); const newDriver = await response.json();
setDrivers(prev => sortDriversByLastName([...prev, newDriver])); setDrivers(prev => sortDriversByLastName([...prev, newDriver]));
setShowForm(false); setShowForm(false);
showToast('Driver added successfully!', 'success');
} else { } else {
console.error('Failed to add driver:', response.status); console.error('Failed to add driver:', response.status);
showToast('Failed to add driver. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error adding driver:', error); console.error('Error adding driver:', error);
showToast('An error occurred while adding the driver.', 'error');
} }
}; };
const handleEditDriver = async (driverData: any) => { const handleEditDriver = async (driverData: DriverFormData) => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/drivers/${driverData.id}`, { const response = await apiCall(`/api/drivers/${driverData.id}`, {
@@ -104,11 +102,14 @@ const DriverList: React.FC = () => {
driver.id === updatedDriver.id ? updatedDriver : driver driver.id === updatedDriver.id ? updatedDriver : driver
))); )));
setEditingDriver(null); setEditingDriver(null);
showToast('Driver updated successfully!', 'success');
} else { } else {
console.error('Failed to update driver:', response.status); console.error('Failed to update driver:', response.status);
showToast('Failed to update driver. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error updating driver:', error); console.error('Error updating driver:', error);
showToast('An error occurred while updating the driver.', 'error');
} }
}; };
@@ -129,30 +130,39 @@ const DriverList: React.FC = () => {
if (response.ok) { if (response.ok) {
setDrivers(prev => prev.filter(driver => driver.id !== driverId)); setDrivers(prev => prev.filter(driver => driver.id !== driverId));
showToast('Driver deleted successfully!', 'success');
} else { } else {
console.error('Failed to delete driver:', response.status); console.error('Failed to delete driver:', response.status);
showToast('Failed to delete driver. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error deleting driver:', error); console.error('Error deleting driver:', error);
showToast('An error occurred while deleting the driver.', 'error');
} }
}; };
if (loading) { if (loading) {
return ( return (
<div className="flex justify-center items-center min-h-64"> <div className="flex justify-center items-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4"> <LoadingSpinner size="lg" message="Loading drivers..." />
<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> </div>
); );
} }
// Filter drivers based on search term
const filteredDrivers = drivers.filter(driver => {
const searchLower = searchTerm.toLowerCase();
return (
driver.name.toLowerCase().includes(searchLower) ||
driver.phone.toLowerCase().includes(searchLower)
);
});
return ( return (
<div className="space-y-8"> <div className="space-y-8">
{/* Header */} {/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60"> <div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center mb-6">
<div> <div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent"> <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
Driver Management Driver Management
@@ -171,16 +181,53 @@ const DriverList: React.FC = () => {
</button> </button>
</div> </div>
</div> </div>
{/* Search Bar */}
<div className="relative">
<input
type="text"
placeholder="Search by name or phone number..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-4 py-3 pl-12 border border-slate-200 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent transition-all"
/>
<svg className="absolute left-4 top-3.5 h-5 w-5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
{searchTerm && (
<button
onClick={() => setSearchTerm('')}
className="absolute right-4 top-3.5 text-slate-400 hover:text-slate-600"
>
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div> </div>
{/* Search Results */}
{searchTerm && (
<div className="bg-amber-50 border border-amber-200 rounded-lg px-4 py-2 mb-4">
<p className="text-sm text-amber-800">
Found {filteredDrivers.length} result{filteredDrivers.length !== 1 ? 's' : ''} for "{searchTerm}"
</p>
</div>
)}
{/* Driver Grid */} {/* Driver Grid */}
{drivers.length === 0 ? ( {filteredDrivers.length === 0 ? (
<div className="bg-white rounded-2xl shadow-lg p-12 border border-slate-200/60 text-center"> <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-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 className="w-8 h-8 bg-slate-300 rounded-full"></div>
</div> </div>
<h3 className="text-lg font-semibold text-slate-800 mb-2">No Drivers Found</h3> <h3 className="text-lg font-semibold text-slate-800 mb-2">
<p className="text-slate-600 mb-6">Get started by adding your first driver</p> {searchTerm ? 'No Drivers Found' : 'No Drivers Added Yet'}
</h3>
<p className="text-slate-600 mb-6">
{searchTerm ? `No drivers match your search for "${searchTerm}"` : 'Get started by adding your first driver'}
</p>
<button <button
className="btn btn-primary" className="btn btn-primary"
onClick={() => setShowForm(true)} onClick={() => setShowForm(true)}
@@ -190,7 +237,7 @@ const DriverList: React.FC = () => {
</div> </div>
) : ( ) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{drivers.map((driver) => ( {filteredDrivers.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 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"> <div className="p-6">
{/* Driver Header */} {/* Driver Header */}

View File

@@ -1,6 +1,6 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { useParams, Link } from 'react-router-dom'; import { useParams, Link } from 'react-router-dom';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import FlightStatus from '../components/FlightStatus'; import FlightStatus from '../components/FlightStatus';
import ScheduleManager from '../components/ScheduleManager'; import ScheduleManager from '../components/ScheduleManager';
@@ -37,15 +37,14 @@ const VipDetails: React.FC = () => {
const fetchVip = async () => { const fetchVip = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', { const { data: vips } = await apiCall('/api/vips', {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (vips) {
const vips = await response.json();
const foundVip = vips.find((v: Vip) => v.id === id); const foundVip = vips.find((v: Vip) => v.id === id);
if (foundVip) { if (foundVip) {
@@ -74,15 +73,14 @@ const VipDetails: React.FC = () => {
if (vip) { if (vip) {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall(`/api/vips/${vip.id}/schedule`, { const { data: scheduleData } = await apiCall(`/api/vips/${vip.id}/schedule`, {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (scheduleData) {
const scheduleData = await response.json();
setSchedule(scheduleData); setSchedule(scheduleData);
} }
} catch (error) { } catch (error) {

View File

@@ -1,9 +1,11 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom'; import { Link } from 'react-router-dom';
import { apiCall } from '../config/api'; import { apiCall } from '../utils/api';
import VipForm from '../components/VipForm'; import VipForm from '../components/VipForm';
import EditVipForm from '../components/EditVipForm'; import EditVipForm from '../components/EditVipForm';
import FlightStatus from '../components/FlightStatus'; import FlightStatus from '../components/FlightStatus';
import { useToast } from '../contexts/ToastContext';
import { LoadingSpinner } from '../components/LoadingSpinner';
interface Vip { interface Vip {
id: string; id: string;
@@ -26,10 +28,13 @@ interface Vip {
} }
const VipList: React.FC = () => { const VipList: React.FC = () => {
const { showToast } = useToast();
const [vips, setVips] = useState<Vip[]>([]); const [vips, setVips] = useState<Vip[]>([]);
const [loading, setLoading] = useState(true); const [loading, setLoading] = useState(true);
const [showForm, setShowForm] = useState(false); const [showForm, setShowForm] = useState(false);
const [editingVip, setEditingVip] = useState<Vip | null>(null); const [editingVip, setEditingVip] = useState<Vip | null>(null);
const [submitting, setSubmitting] = useState(false);
const [searchTerm, setSearchTerm] = useState('');
// Function to extract last name for sorting // Function to extract last name for sorting
const getLastName = (fullName: string) => { const getLastName = (fullName: string) => {
@@ -50,19 +55,18 @@ const VipList: React.FC = () => {
const fetchVips = async () => { const fetchVips = async () => {
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', { const { data } = await apiCall('/api/vips', {
headers: { headers: {
'Authorization': `Bearer ${token}`, 'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json' 'Content-Type': 'application/json'
} }
}); });
if (response.ok) { if (data) {
const data = await response.json();
const sortedVips = sortVipsByLastName(data); const sortedVips = sortVipsByLastName(data);
setVips(sortedVips); setVips(sortedVips);
} else { } else {
console.error('Failed to fetch VIPs:', response.status); console.error('Failed to fetch VIPs');
} }
} catch (error) { } catch (error) {
console.error('Error fetching VIPs:', error); console.error('Error fetching VIPs:', error);
@@ -75,6 +79,7 @@ const VipList: React.FC = () => {
}, []); }, []);
const handleAddVip = async (vipData: any) => { const handleAddVip = async (vipData: any) => {
setSubmitting(true);
try { try {
const token = localStorage.getItem('authToken'); const token = localStorage.getItem('authToken');
const response = await apiCall('/api/vips', { const response = await apiCall('/api/vips', {
@@ -90,11 +95,15 @@ const VipList: React.FC = () => {
const newVip = await response.json(); const newVip = await response.json();
setVips(prev => sortVipsByLastName([...prev, newVip])); setVips(prev => sortVipsByLastName([...prev, newVip]));
setShowForm(false); setShowForm(false);
showToast('VIP added successfully!', 'success');
} else { } else {
console.error('Failed to add VIP:', response.status); showToast('Failed to add VIP. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error adding VIP:', error); console.error('Error adding VIP:', error);
showToast('An error occurred while adding the VIP.', 'error');
} finally {
setSubmitting(false);
} }
}; };
@@ -114,11 +123,13 @@ const VipList: React.FC = () => {
const updatedVip = await response.json(); const updatedVip = await response.json();
setVips(prev => sortVipsByLastName(prev.map(vip => vip.id === updatedVip.id ? updatedVip : vip))); setVips(prev => sortVipsByLastName(prev.map(vip => vip.id === updatedVip.id ? updatedVip : vip)));
setEditingVip(null); setEditingVip(null);
showToast('VIP updated successfully!', 'success');
} else { } else {
console.error('Failed to update VIP:', response.status); showToast('Failed to update VIP. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error updating VIP:', error); console.error('Error updating VIP:', error);
showToast('An error occurred while updating the VIP.', 'error');
} }
}; };
@@ -139,30 +150,42 @@ const VipList: React.FC = () => {
if (response.ok) { if (response.ok) {
setVips(prev => prev.filter(vip => vip.id !== vipId)); setVips(prev => prev.filter(vip => vip.id !== vipId));
showToast('VIP deleted successfully!', 'success');
} else { } else {
console.error('Failed to delete VIP:', response.status); showToast('Failed to delete VIP. Please try again.', 'error');
} }
} catch (error) { } catch (error) {
console.error('Error deleting VIP:', error); console.error('Error deleting VIP:', error);
showToast('An error occurred while deleting the VIP.', 'error');
} }
}; };
if (loading) { if (loading) {
return ( return (
<div className="flex justify-center items-center min-h-64"> <div className="flex justify-center items-center min-h-screen bg-gradient-to-br from-slate-50 to-slate-100">
<div className="bg-white rounded-2xl shadow-lg p-8 flex items-center space-x-4"> <LoadingSpinner size="lg" message="Loading VIPs..." />
<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> </div>
); );
} }
// Filter VIPs based on search term
const filteredVips = vips.filter(vip => {
const searchLower = searchTerm.toLowerCase();
return (
vip.name.toLowerCase().includes(searchLower) ||
vip.organization.toLowerCase().includes(searchLower) ||
vip.department.toLowerCase().includes(searchLower) ||
(vip.transportMode === 'flight' && vip.flights?.some(flight =>
flight.flightNumber.toLowerCase().includes(searchLower)
))
);
});
return ( return (
<div className="space-y-8"> <div className="space-y-8">
{/* Header */} {/* Header */}
<div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60"> <div className="bg-white rounded-2xl shadow-lg p-8 border border-slate-200/60">
<div className="flex justify-between items-center"> <div className="flex justify-between items-center mb-6">
<div> <div>
<h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent"> <h1 className="text-3xl font-bold bg-gradient-to-r from-slate-800 to-slate-600 bg-clip-text text-transparent">
VIP Management VIP Management
@@ -176,16 +199,52 @@ const VipList: React.FC = () => {
Add New VIP Add New VIP
</button> </button>
</div> </div>
{/* Search Bar */}
<div className="relative">
<input
type="text"
placeholder="Search by name, organization, department, or flight number..."
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className="w-full px-4 py-3 pl-12 border border-slate-200 rounded-lg focus:ring-2 focus:ring-amber-500 focus:border-transparent transition-all"
/>
<svg className="absolute left-4 top-3.5 h-5 w-5 text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
{searchTerm && (
<button
onClick={() => setSearchTerm('')}
className="absolute right-4 top-3.5 text-slate-400 hover:text-slate-600"
>
<svg className="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
</div> </div>
{/* VIP List */} {/* VIP List */}
{vips.length === 0 ? ( {searchTerm && (
<div className="bg-amber-50 border border-amber-200 rounded-lg px-4 py-2 mb-4">
<p className="text-sm text-amber-800">
Found {filteredVips.length} result{filteredVips.length !== 1 ? 's' : ''} for "{searchTerm}"
</p>
</div>
)}
{filteredVips.length === 0 ? (
<div className="bg-white rounded-2xl shadow-lg p-12 border border-slate-200/60 text-center"> <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-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 className="w-8 h-8 bg-slate-300 rounded-full"></div>
</div> </div>
<h3 className="text-lg font-semibold text-slate-800 mb-2">No VIPs Found</h3> <h3 className="text-lg font-semibold text-slate-800 mb-2">
<p className="text-slate-600 mb-6">Get started by adding your first VIP</p> {searchTerm ? 'No VIPs Found' : 'No VIPs Added Yet'}
</h3>
<p className="text-slate-600 mb-6">
{searchTerm ? `No VIPs match your search for "${searchTerm}"` : 'Get started by adding your first VIP'}
</p>
<button <button
className="btn btn-primary" className="btn btn-primary"
onClick={() => setShowForm(true)} onClick={() => setShowForm(true)}
@@ -195,7 +254,7 @@ const VipList: React.FC = () => {
</div> </div>
) : ( ) : (
<div className="space-y-4"> <div className="space-y-4">
{vips.map((vip) => ( {filteredVips.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 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="p-6">
<div className="flex justify-between items-start"> <div className="flex justify-between items-start">

View File

@@ -14,36 +14,45 @@ export default defineConfig({
port: 5173, port: 5173,
allowedHosts: [ allowedHosts: [
'localhost', 'localhost',
'127.0.0.1' '127.0.0.1',
'bsa.madeamess.online',
'.madeamess.online' // Allow all subdomains
], ],
headers: {
'Cross-Origin-Opener-Policy': 'same-origin-allow-popups'
},
proxy: { proxy: {
'/api': { '/api': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
// Only proxy specific auth endpoints, not the callback route // Only proxy specific auth endpoints, not the callback route
'/auth/setup': { '/auth/setup': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/auth/google/url': { '/auth/google/url': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/auth/google/exchange': { '/auth/google/exchange': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true,
},
'/auth/google/verify': {
target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/auth/me': { '/auth/me': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/auth/logout': { '/auth/logout': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
'/auth/status': { '/auth/status': {
target: 'http://backend:3000', target: 'http://127.0.0.1:3000',
changeOrigin: true, changeOrigin: true,
}, },
}, },