26 Commits

Author SHA1 Message Date
139cb4aebe refactor: simplify GPS page, lean into Traccar for live map and trips
Remove ~2,300 lines of code that duplicated Traccar's native capabilities:
- Remove Leaflet live map, trip stats/playback, and OSRM route matching from frontend
- Delete osrm.service.ts entirely (415 lines)
- Remove 6 dead backend endpoints and unused service methods
- Clean up unused hooks and TypeScript types
- Keep device enrollment, QR codes, settings, and CommandCenter integration

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 19:53:57 +01:00
14c6c9506f fix: optimize Traccar Client QR code with iOS background GPS settings
QR enrollment was only setting id and interval, causing iOS to default
to medium accuracy with stop_detection enabled — which pauses GPS
updates when the phone appears stationary, causing 5-30 min gaps.

Now sets accuracy=highest, stop_detection=false, distance=0, angle=30,
heartbeat=300, buffer=true. Also updates driver instructions with
required iPhone settings (Always location, Background App Refresh).

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-09 18:51:42 +01:00
53eb82c4d2 refactor: use Traccar trip API instead of custom detection (#23)
Replace custom trip detection (overlapping/micro-trip prone) with
Traccar's built-in trip report API. Remove merge/backfill UI and
endpoints. Add geocoded address display to trip cards.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 19:38:08 +01:00
b80ffd3ca1 fix: trip detection creating overlapping/micro trips (#23)
- Increase idle threshold from 5 to 10 minutes for sparse GPS data
- Only start new trips from positions AFTER the previous trip ended
- Prevent duplicate trips at same timestamp with existence check
- Auto-delete micro-trips (< 0.1 mi or < 60 seconds)
- Use GPS timestamps for idle detection instead of wall clock

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:57:11 +01:00
cc3375ef85 feat: add GPS trip detection, history panel, and playback (#23)
Auto-detect trips from GPS data (5-min idle threshold), pre-compute
OSRM routes on trip completion, add trip history side panel with
toggleable trips, and animated trip playback with speed controls.

- Add GpsTrip model with TripStatus enum and migration
- Trip detection in syncPositions cron (start on movement, end on idle)
- Trip finalization with OSRM route matching and stats computation
- API endpoints: list/detail/active/merge/backfill trips
- Stats tab overhaul: trip list panel + map with colored polylines
- Trip playback: animated marker, progressive trail, 1x-16x speed
- Live map shows active trip trail instead of full day history
- Historical backfill from existing GPS location data

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 18:08:48 +01:00
cb4a070ad9 fix: OSRM sparse data handling, frontend type mismatch, map jumping
- Rewrite OsrmService with smart dense/sparse segmentation:
  dense GPS traces use Match API, sparse gaps use Route API
  (turn-by-turn directions between waypoints)
- Filter stationary points before OSRM processing
- Fix critical frontend bug: LocationHistoryResponse type didn't
  match backend response shape (matchedRoute vs matched), so OSRM
  routes were never actually displaying
- Fix double distance conversion (backend sends miles, frontend
  was dividing by 1609.34 again)
- Fix map jumping: disable popup autoPan on marker data refresh
- Extend default history window from 4h to 12h

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 17:39:00 +01:00
12b9361ae0 chore: add OSRM-related type definitions for GPS routes
Adds distanceMethod to DriverStatsDto and LocationHistoryResponse interface
to support the OSRM road-snapping feature.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 17:05:43 +01:00
33fda57cc6 feat: add OSRM road-snapping for GPS routes and mileage (#21)
Routes now follow actual roads instead of cutting through buildings:
- New OsrmService calls free OSRM Match API to snap GPS points to roads
- Position history endpoint accepts ?matched=true for road-snapped geometry
- Stats use OSRM road distance instead of Haversine crow-flies distance
- Frontend shows solid blue polylines for matched routes, dashed for raw
- Handles chunking (100 coord limit), rate limiting, graceful fallback
- Distance badge shows accurate road miles on route trails

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 17:03:47 +01:00
d93919910b fix: rewrite GPS stats to calculate from stored history (#22)
- Replace Traccar summary API dependency with local Haversine distance calculation
- Calculate mileage from GpsLocationHistory table (sum consecutive positions)
- Filter out GPS jitter (<0.01mi), gaps (>10min), and unrealistic speeds (>100mph)
- Calculate trips, driving time, average/top speed from position history
- Add detailed stats logging for debugging

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:48:41 +01:00
4dbb899409 fix: improve GPS position sync reliability and add route trails (#21)
Backend:
- Increase sync overlap buffer from 5s to 30s to catch late-arriving positions
- Add position history endpoint GET /gps/locations/:driverId/history
- Add logging for position sync counts (returned vs inserted)

Frontend:
- Add useDriverLocationHistory hook for fetching position trails
- Draw Polyline route trails on GPS map for each tracked driver
- Historical positions shown as semi-transparent paths behind live markers

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:42:41 +01:00
3bc9cd0bca refactor: complete code efficiency pass (Issues #10, #14, #16)
Backend:
- Add Prisma soft-delete middleware for automatic deletedAt filtering (#10)
- Split 2758-line copilot.service.ts into focused sub-services (#14):
  - copilot-schedule.service.ts (schedule/event tools)
  - copilot-reports.service.ts (reporting/analytics tools)
  - copilot-fleet.service.ts (vehicle/driver tools)
  - copilot-vip.service.ts (VIP management tools)
  - copilot.service.ts now thin orchestrator
- Remove manual deletedAt: null from 50+ queries

Frontend:
- Create SortableHeader component for reusable table sorting (#16)
- Create useListPage hook for shared search/filter/sort state (#16)
- Update VipList, DriverList, EventList to use shared infrastructure

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:34:18 +01:00
f2b3f34a72 refactor: code efficiency improvements (Issues #9-13, #15, #17-20)
Backend:
- Extract shared hard-delete authorization utility (#9)
- Extract Prisma include constants per entity (#11)
- Fix N+1 query pattern in events findAll (#12)
- Extract shared date utility functions (#13)
- Move vehicle utilization filtering to DB query (#15)
- Add ParseBooleanPipe for query params
- Add CurrentDriver decorator + ResolveDriverInterceptor (#20)

Frontend:
- Extract shared form utilities (toDatetimeLocal) and enum labels (#17)
- Replace browser confirm() with styled ConfirmModal (#18)
- Add centralized query-keys.ts constants (#19)
- Clean up unused imports, add useMemo where needed (#19)
- Standardize filter button styling across list pages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 16:07:19 +01:00
806b67954e feat: modernize login page with dark theme and breathing logo animation
- Dark gradient background (slate-950/blue-950) with ambient blur effects
- Circular logo centered with dual-ring frosted glass design
- Heartbeat breathing animation (3s cycle) with glow pulse on outer ring
- Gradient sign-in button with hover shadow effects
- Removed "first user" warning, replaced with subtle "authorized personnel" note
- Closes #5 and #6

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 07:58:04 +01:00
a4d360aae9 feat: add PDF reports, timezone management, GPS QR codes, and fix GPS tracking gaps
Issue #1: QR button on GPS Devices tab for re-enrollment
Issue #2: App-wide timezone setting with TimezoneContext, useFormattedDate hook,
  and admin timezone selector. All date displays now respect the configured timezone.
Issue #3: PDF export for Accountability Roster using @react-pdf/renderer with
  professional styling matching VIPSchedulePDF. Added Signal send button.
Issue #4: Fixed GPS "teleporting" gaps - syncPositions now fetches position history
  per device instead of only latest position. Changed cron to every 30s, added
  unique constraint on deviceId+timestamp for deduplication, lowered min interval to 10s.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-08 07:36:51 +01:00
0f0f1cbf38 feat: add smart flight tracking with AviationStack API + visual progress
- Add 20+ flight fields (terminal, gate, delays, estimated times, etc.)
- Smart polling cron with budget-aware priority queue (100 req/month)
- Tracking phases: FAR_OUT → PRE_DEPARTURE → ACTIVE → LANDED
- Visual FlightProgressBar with animated airplane between airports
- FlightCard with status dots, delay badges, expandable details
- FlightList rewrite: card-based, grouped by status, search/filter
- Dashboard: enriched flight status widget with compact progress bars
- CommandCenter: flight alerts + enriched arrivals with gate/terminal

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 19:42:52 +01:00
74a292ea93 feat: add Help page with search, streamline copilot, misc UI fixes
Adds searchable Help/User Guide page, trims copilot tool bloat,
adds OTHER department option, and various form/layout improvements.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-07 19:42:39 +01:00
b35c14fddc feat: add VIP roster tracking and accountability reports
- Add isRosterOnly flag for VIPs who attend but don't need transportation
- Add VIP contact fields (phone, email) and emergency contact info
- Create Reports page under Admin menu with Accountability Roster
- Report shows all VIPs (active + roster-only) with contact/emergency info
- Export to CSV functionality for emergency preparedness
- VIP list filters roster-only by default with toggle to show
- VIP form includes collapsible contact/emergency section
- Fix first-user race condition with Serializable transaction
- Remove Traccar hardcoded default credentials
- Add feature flags endpoint for optional services

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-07 09:16:32 +01:00
934464bf8e security: add helmet, rate limiting, webhook auth, fix token storage, restrict hard deletes
- Add helmet for HTTP security headers (CSP, HSTS, X-Frame-Options, etc.)
- Add @nestjs/throttler for rate limiting (100 req/60s per IP)
- Add shared secret validation on Signal webhook endpoint
- Remove JWT token from localStorage, use Auth0 SDK memory cache
  with async getAccessTokenSilently() in API interceptor
- Restrict hard delete (?hard=true) to ADMINISTRATOR role in service layer
- Replace exposed Anthropic API key with placeholder in .env

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 18:30:14 +01:00
8e88880838 chore: remove unused packages, imports, and stale type definitions
- Remove @casl/prisma (unused) from backend
- Remove @heroicons/react (unused, using lucide-react) from frontend
- Remove unused InferSubjects import from ability.factory.ts
- Remove unused Calendar import from Dashboard.tsx
- Delete stale frontend/src/lib/types.ts (duplicate of src/types/index.ts)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 17:33:57 +01:00
5f4c474e37 feat: improve VIP table display and rewrite seed service for new paradigm
- EventList VIP column: compact layout with max 2 names shown, party
  size badges, "+N more" indicator, and total passenger count
- Seed service: 20 VIPs with party sizes, 8 drivers, 8 vehicles,
  13 master events over 3 days with linked transport legs, realistic
  capacity planning and conflict-free driver/vehicle assignments

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 00:22:59 +01:00
a6b639d5f4 feat: update seed data with BSA Jamboree scenario
Replaces generic test data with a realistic BSA Jamboree scenario that
demonstrates party sizes, shared itinerary items, and linked transport
legs. Includes 6 VIPs with varying party sizes, 7 shared events, 15
transport legs, 6 vehicles, and 4 drivers.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-04 00:03:49 +01:00
8e8bbad3fc feat: add party size tracking and master event linking
Add partySize field to VIP model (default 1) to track total people
traveling with each VIP including entourage/handlers/spouses. Vehicle
capacity checks now sum party sizes instead of just counting VIPs.

Add masterEventId self-reference to ScheduleEvent for linking transport
legs to shared itinerary items (events, meetings, meals). When creating
a transport event, users can link it to a shared activity and VIPs
auto-populate from the linked event.

Changes:
- Schema: partySize on VIP, masterEventId on ScheduleEvent
- Backend: party-size-aware capacity checks, master/child event includes
- VIP Form: party size input with helper text
- Event Form: party-size capacity display, master event selector
- Event List: party size in capacity and VIP names, master event badges
- Command Center: all VIP names shown with party size indicators

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 23:40:44 +01:00
714cac5d10 feat: add GPS location indicators and driver map modal to War Room
Add real-time GPS status dots on driver names throughout the Command Center:
- Green pulsing dot for drivers seen within 10 minutes, gray for inactive
- Clickable dots open a satellite map modal centered on the driver's position
- GPS dots appear in Active NOW cards, Upcoming cards, and In Use vehicles
- Replace Quick Actions panel with Active Drivers panel showing GPS-active
  drivers with speed and last seen time, with compact quick-link icons below
- New DriverLocationModal shows Leaflet satellite map at zoom 16 with
  speed, heading, battery, and last seen info grid

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 22:50:24 +01:00
ca2b341f01 fix: prevent GPS map from resetting zoom/position on data refresh
The MapFitBounds component was calling fitBounds on every 30-second
location refresh, overriding the user's current view. Now only fits
bounds on the initial load so users can pan and zoom freely without
interruption.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 22:16:03 +01:00
0d7306e0aa feat: switch GPS map to Esri satellite imagery layer
Replace OpenStreetMap tiles with Esri World Imagery for high-resolution
satellite view on the GPS Tracking live map.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 22:11:17 +01:00
21fb193d01 fix: restore soft-deleted driver record when re-enabling driver toggle
When a coordinator's driver status was toggled off (soft-delete) and
then back on, the create failed because the soft-deleted record still
existed. Now checks for active vs soft-deleted driver records and
restores the existing record instead of trying to create a duplicate.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-02-03 21:49:58 +01:00
127 changed files with 12507 additions and 5077 deletions

View File

@@ -1,40 +0,0 @@
# ============================================
# Application Configuration
# ============================================
PORT=3000
NODE_ENV=development
FRONTEND_URL=http://localhost:5173
# ============================================
# Database Configuration
# ============================================
DATABASE_URL="postgresql://postgres:changeme@localhost:5433/vip_coordinator"
# ============================================
# Redis Configuration (Optional)
# ============================================
REDIS_URL="redis://localhost:6379"
# ============================================
# Auth0 Configuration
# ============================================
# Get these from your Auth0 dashboard:
# 1. Create Application (Single Page Application)
# 2. Create API
# 3. Configure callback URLs: http://localhost:5173/callback
AUTH0_DOMAIN="dev-s855cy3bvjjbkljt.us.auth0.com"
AUTH0_AUDIENCE="https://vip-coordinator-api"
AUTH0_ISSUER="https://dev-s855cy3bvjjbkljt.us.auth0.com/"
# ============================================
# Flight Tracking API (Optional)
# ============================================
# Get API key from: https://aviationstack.com/
AVIATIONSTACK_API_KEY="your-aviationstack-api-key"
# ============================================
# AI Copilot Configuration (Optional)
# ============================================
# Get API key from: https://console.anthropic.com/
# Cost: ~$3 per million tokens
ANTHROPIC_API_KEY="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"

View File

@@ -6,19 +6,19 @@ NODE_ENV=development
FRONTEND_URL=http://localhost:5173 FRONTEND_URL=http://localhost:5173
# ============================================ # ============================================
# Database Configuration # Database Configuration (required)
# ============================================ # ============================================
# Port 5433 is used to avoid conflicts with local PostgreSQL # Port 5433 is used to avoid conflicts with local PostgreSQL
DATABASE_URL="postgresql://postgres:changeme@localhost:5433/vip_coordinator" DATABASE_URL="postgresql://postgres:changeme@localhost:5433/vip_coordinator"
# ============================================ # ============================================
# Redis Configuration (Optional) # Redis Configuration (required)
# ============================================ # ============================================
# Port 6380 is used to avoid conflicts with local Redis # Port 6380 is used to avoid conflicts with local Redis
REDIS_URL="redis://localhost:6380" REDIS_URL="redis://localhost:6380"
# ============================================ # ============================================
# Auth0 Configuration # Auth0 Configuration (required)
# ============================================ # ============================================
# Get these from your Auth0 dashboard: # Get these from your Auth0 dashboard:
# 1. Create Application (Single Page Application) # 1. Create Application (Single Page Application)
@@ -29,6 +29,16 @@ AUTH0_AUDIENCE="https://your-api-identifier"
AUTH0_ISSUER="https://your-tenant.us.auth0.com/" AUTH0_ISSUER="https://your-tenant.us.auth0.com/"
# ============================================ # ============================================
# Flight Tracking API (Optional) # Optional Services
# ============================================ # ============================================
AVIATIONSTACK_API_KEY="your-aviationstack-api-key" # Leave empty or remove to disable the feature.
# The app auto-detects which features are available.
# Flight tracking API (https://aviationstack.com/)
AVIATIONSTACK_API_KEY=
# AI Copilot (https://console.anthropic.com/)
ANTHROPIC_API_KEY=
# Signal webhook authentication (recommended in production)
SIGNAL_WEBHOOK_SECRET=

View File

@@ -11,7 +11,6 @@
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.72.1", "@anthropic-ai/sdk": "^0.72.1",
"@casl/ability": "^6.8.0", "@casl/ability": "^6.8.0",
"@casl/prisma": "^1.6.1",
"@nestjs/axios": "^4.0.1", "@nestjs/axios": "^4.0.1",
"@nestjs/common": "^10.3.0", "@nestjs/common": "^10.3.0",
"@nestjs/config": "^3.1.1", "@nestjs/config": "^3.1.1",
@@ -21,11 +20,13 @@
"@nestjs/passport": "^10.0.3", "@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.0", "@nestjs/platform-express": "^10.3.0",
"@nestjs/schedule": "^4.1.2", "@nestjs/schedule": "^4.1.2",
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.8.1", "@prisma/client": "^5.8.1",
"@types/pdfkit": "^0.17.4", "@types/pdfkit": "^0.17.4",
"axios": "^1.6.5", "axios": "^1.6.5",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.0", "class-validator": "^0.14.0",
"helmet": "^8.1.0",
"ics": "^3.8.1", "ics": "^3.8.1",
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"jwks-rsa": "^3.1.0", "jwks-rsa": "^3.1.0",
@@ -783,7 +784,6 @@
"resolved": "https://registry.npmjs.org/@casl/ability/-/ability-6.8.0.tgz", "resolved": "https://registry.npmjs.org/@casl/ability/-/ability-6.8.0.tgz",
"integrity": "sha512-Ipt4mzI4gSgnomFdaPjaLgY2MWuXqAEZLrU6qqWBB7khGiBBuuEp6ytYDnq09bRXqcjaeeHiaCvCGFbBA2SpvA==", "integrity": "sha512-Ipt4mzI4gSgnomFdaPjaLgY2MWuXqAEZLrU6qqWBB7khGiBBuuEp6ytYDnq09bRXqcjaeeHiaCvCGFbBA2SpvA==",
"license": "MIT", "license": "MIT",
"peer": true,
"dependencies": { "dependencies": {
"@ucast/mongo2js": "^1.3.0" "@ucast/mongo2js": "^1.3.0"
}, },
@@ -791,20 +791,6 @@
"url": "https://github.com/stalniy/casl/blob/master/BACKERS.md" "url": "https://github.com/stalniy/casl/blob/master/BACKERS.md"
} }
}, },
"node_modules/@casl/prisma": {
"version": "1.6.1",
"resolved": "https://registry.npmjs.org/@casl/prisma/-/prisma-1.6.1.tgz",
"integrity": "sha512-VSAzfTMOZvP3Atj3F0qwJItOm1ixIiumjbBz21PL/gLUIDwoktyAx2dB7dPwjH9AQvzZPE629ee7fVU5K2hpzg==",
"license": "MIT",
"dependencies": {
"@ucast/core": "^1.10.0",
"@ucast/js": "^3.0.1"
},
"peerDependencies": {
"@casl/ability": "^5.3.0 || ^6.0.0",
"@prisma/client": "^2.14.0 || ^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0"
}
},
"node_modules/@colors/colors": { "node_modules/@colors/colors": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
@@ -2025,6 +2011,17 @@
} }
} }
}, },
"node_modules/@nestjs/throttler": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/@nestjs/throttler/-/throttler-6.5.0.tgz",
"integrity": "sha512-9j0ZRfH0QE1qyrj9JjIRDz5gQLPqq9yVC2nHsrosDVAfI5HHw08/aUAWx9DZLSdQf4HDkmhTTEGLrRFHENvchQ==",
"license": "MIT",
"peerDependencies": {
"@nestjs/common": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
"@nestjs/core": "^7.0.0 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
"reflect-metadata": "^0.1.13 || ^0.2.0"
}
},
"node_modules/@noble/hashes": { "node_modules/@noble/hashes": {
"version": "1.8.0", "version": "1.8.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
@@ -2134,7 +2131,6 @@
"integrity": "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA==", "integrity": "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA==",
"hasInstallScript": true, "hasInstallScript": true,
"license": "Apache-2.0", "license": "Apache-2.0",
"peer": true,
"engines": { "engines": {
"node": ">=16.13" "node": ">=16.13"
}, },
@@ -5866,6 +5862,15 @@
"node": ">= 0.4" "node": ">= 0.4"
} }
}, },
"node_modules/helmet": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz",
"integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/html-escaper": { "node_modules/html-escaper": {
"version": "2.0.2", "version": "2.0.2",
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",

View File

@@ -26,7 +26,6 @@
"dependencies": { "dependencies": {
"@anthropic-ai/sdk": "^0.72.1", "@anthropic-ai/sdk": "^0.72.1",
"@casl/ability": "^6.8.0", "@casl/ability": "^6.8.0",
"@casl/prisma": "^1.6.1",
"@nestjs/axios": "^4.0.1", "@nestjs/axios": "^4.0.1",
"@nestjs/common": "^10.3.0", "@nestjs/common": "^10.3.0",
"@nestjs/config": "^3.1.1", "@nestjs/config": "^3.1.1",
@@ -36,11 +35,13 @@
"@nestjs/passport": "^10.0.3", "@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.0", "@nestjs/platform-express": "^10.3.0",
"@nestjs/schedule": "^4.1.2", "@nestjs/schedule": "^4.1.2",
"@nestjs/throttler": "^6.5.0",
"@prisma/client": "^5.8.1", "@prisma/client": "^5.8.1",
"@types/pdfkit": "^0.17.4", "@types/pdfkit": "^0.17.4",
"axios": "^1.6.5", "axios": "^1.6.5",
"class-transformer": "^0.5.1", "class-transformer": "^0.5.1",
"class-validator": "^0.14.0", "class-validator": "^0.14.0",
"helmet": "^8.1.0",
"ics": "^3.8.1", "ics": "^3.8.1",
"ioredis": "^5.3.2", "ioredis": "^5.3.2",
"jwks-rsa": "^3.1.0", "jwks-rsa": "^3.1.0",

View File

@@ -0,0 +1,8 @@
-- AlterTable
ALTER TABLE "vips" ADD COLUMN "partySize" INTEGER NOT NULL DEFAULT 1;
-- AlterTable
ALTER TABLE "schedule_events" ADD COLUMN "masterEventId" TEXT;
-- AddForeignKey
ALTER TABLE "schedule_events" ADD CONSTRAINT "schedule_events_masterEventId_fkey" FOREIGN KEY ("masterEventId") REFERENCES "schedule_events"("id") ON DELETE SET NULL ON UPDATE CASCADE;

View File

@@ -0,0 +1,6 @@
-- AlterTable
ALTER TABLE "vips" ADD COLUMN "email" TEXT,
ADD COLUMN "emergencyContactName" TEXT,
ADD COLUMN "emergencyContactPhone" TEXT,
ADD COLUMN "isRosterOnly" BOOLEAN NOT NULL DEFAULT false,
ADD COLUMN "phone" TEXT;

View File

@@ -0,0 +1,2 @@
-- AlterEnum
ALTER TYPE "Department" ADD VALUE 'OTHER';

View File

@@ -0,0 +1,47 @@
-- AlterTable
ALTER TABLE "flights" ADD COLUMN "aircraftType" TEXT,
ADD COLUMN "airlineIata" TEXT,
ADD COLUMN "airlineName" TEXT,
ADD COLUMN "arrivalBaggage" TEXT,
ADD COLUMN "arrivalDelay" INTEGER,
ADD COLUMN "arrivalGate" TEXT,
ADD COLUMN "arrivalTerminal" TEXT,
ADD COLUMN "autoTrackEnabled" BOOLEAN NOT NULL DEFAULT true,
ADD COLUMN "departureDelay" INTEGER,
ADD COLUMN "departureGate" TEXT,
ADD COLUMN "departureTerminal" TEXT,
ADD COLUMN "estimatedArrival" TIMESTAMP(3),
ADD COLUMN "estimatedDeparture" TIMESTAMP(3),
ADD COLUMN "lastApiResponse" JSONB,
ADD COLUMN "lastPolledAt" TIMESTAMP(3),
ADD COLUMN "liveAltitude" DOUBLE PRECISION,
ADD COLUMN "liveDirection" DOUBLE PRECISION,
ADD COLUMN "liveIsGround" BOOLEAN,
ADD COLUMN "liveLatitude" DOUBLE PRECISION,
ADD COLUMN "liveLongitude" DOUBLE PRECISION,
ADD COLUMN "liveSpeed" DOUBLE PRECISION,
ADD COLUMN "liveUpdatedAt" TIMESTAMP(3),
ADD COLUMN "pollCount" INTEGER NOT NULL DEFAULT 0,
ADD COLUMN "trackingPhase" TEXT NOT NULL DEFAULT 'FAR_OUT';
-- CreateTable
CREATE TABLE "flight_api_budget" (
"id" TEXT NOT NULL,
"monthYear" TEXT NOT NULL,
"requestsUsed" INTEGER NOT NULL DEFAULT 0,
"requestLimit" INTEGER NOT NULL DEFAULT 100,
"lastRequestAt" TIMESTAMP(3),
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "flight_api_budget_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE UNIQUE INDEX "flight_api_budget_monthYear_key" ON "flight_api_budget"("monthYear");
-- CreateIndex
CREATE INDEX "flights_trackingPhase_idx" ON "flights"("trackingPhase");
-- CreateIndex
CREATE INDEX "flights_scheduledDeparture_idx" ON "flights"("scheduledDeparture");

View File

@@ -0,0 +1,12 @@
-- Delete duplicate rows keeping the first entry (by id) for each deviceId+timestamp pair
DELETE FROM "gps_location_history" a
USING "gps_location_history" b
WHERE a."id" > b."id"
AND a."deviceId" = b."deviceId"
AND a."timestamp" = b."timestamp";
-- Drop the existing index that covered deviceId+timestamp (non-unique)
DROP INDEX IF EXISTS "gps_location_history_deviceId_timestamp_idx";
-- CreateIndex (unique constraint replaces the old non-unique index)
CREATE UNIQUE INDEX "gps_location_history_deviceId_timestamp_key" ON "gps_location_history"("deviceId", "timestamp");

View File

@@ -0,0 +1,34 @@
-- CreateEnum
CREATE TYPE "TripStatus" AS ENUM ('ACTIVE', 'COMPLETED', 'PROCESSING', 'FAILED');
-- CreateTable
CREATE TABLE "gps_trips" (
"id" TEXT NOT NULL,
"deviceId" TEXT NOT NULL,
"status" "TripStatus" NOT NULL DEFAULT 'ACTIVE',
"startTime" TIMESTAMP(3) NOT NULL,
"endTime" TIMESTAMP(3),
"startLatitude" DOUBLE PRECISION NOT NULL,
"startLongitude" DOUBLE PRECISION NOT NULL,
"endLatitude" DOUBLE PRECISION,
"endLongitude" DOUBLE PRECISION,
"distanceMiles" DOUBLE PRECISION,
"durationSeconds" INTEGER,
"topSpeedMph" DOUBLE PRECISION,
"averageSpeedMph" DOUBLE PRECISION,
"pointCount" INTEGER NOT NULL DEFAULT 0,
"matchedRoute" JSONB,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL,
CONSTRAINT "gps_trips_pkey" PRIMARY KEY ("id")
);
-- CreateIndex
CREATE INDEX "gps_trips_deviceId_startTime_idx" ON "gps_trips"("deviceId", "startTime");
-- CreateIndex
CREATE INDEX "gps_trips_status_idx" ON "gps_trips"("status");
-- AddForeignKey
ALTER TABLE "gps_trips" ADD CONSTRAINT "gps_trips_deviceId_fkey" FOREIGN KEY ("deviceId") REFERENCES "gps_devices"("id") ON DELETE CASCADE ON UPDATE CASCADE;

View File

@@ -50,7 +50,18 @@ model VIP {
expectedArrival DateTime? // For self-driving arrivals expectedArrival DateTime? // For self-driving arrivals
airportPickup Boolean @default(false) airportPickup Boolean @default(false)
venueTransport Boolean @default(false) venueTransport Boolean @default(false)
partySize Int @default(1) // Total people: VIP + entourage
notes String? @db.Text notes String? @db.Text
// Roster-only flag: true = just tracking for accountability, not active coordination
isRosterOnly Boolean @default(false)
// Emergency contact info (for accountability reports)
phone String?
email String?
emergencyContactName String?
emergencyContactPhone String?
flights Flight[] flights Flight[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -62,6 +73,7 @@ model VIP {
enum Department { enum Department {
OFFICE_OF_DEVELOPMENT OFFICE_OF_DEVELOPMENT
ADMIN ADMIN
OTHER
} }
enum ArrivalMode { enum ArrivalMode {
@@ -86,13 +98,70 @@ model Flight {
scheduledArrival DateTime? scheduledArrival DateTime?
actualDeparture DateTime? actualDeparture DateTime?
actualArrival DateTime? actualArrival DateTime?
status String? // scheduled, delayed, landed, etc. status String? // scheduled, active, landed, cancelled, incident, diverted
// Airline info (from AviationStack API)
airlineName String?
airlineIata String? // "AA", "UA", "DL"
// Terminal/gate/baggage (critical for driver dispatch)
departureTerminal String?
departureGate String?
arrivalTerminal String?
arrivalGate String?
arrivalBaggage String?
// Estimated times (updated by API, distinct from scheduled)
estimatedDeparture DateTime?
estimatedArrival DateTime?
// Delay in minutes (from API)
departureDelay Int?
arrivalDelay Int?
// Aircraft info
aircraftType String? // IATA type code e.g. "A321", "B738"
// Live position data (may not be available on free tier)
liveLatitude Float?
liveLongitude Float?
liveAltitude Float?
liveSpeed Float? // horizontal speed
liveDirection Float? // heading in degrees
liveIsGround Boolean?
liveUpdatedAt DateTime?
// Polling metadata
lastPolledAt DateTime?
pollCount Int @default(0)
trackingPhase String @default("FAR_OUT") // FAR_OUT, PRE_DEPARTURE, DEPARTURE_WINDOW, ACTIVE, ARRIVAL_WINDOW, LANDED, TERMINAL
autoTrackEnabled Boolean @default(true)
lastApiResponse Json? // Full AviationStack response for debugging
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@map("flights") @@map("flights")
@@index([vipId]) @@index([vipId])
@@index([flightNumber, flightDate]) @@index([flightNumber, flightDate])
@@index([trackingPhase])
@@index([scheduledDeparture])
}
// ============================================
// Flight API Budget Tracking
// ============================================
model FlightApiBudget {
id String @id @default(uuid())
monthYear String @unique // "2026-02" format
requestsUsed Int @default(0)
requestLimit Int @default(100)
lastRequestAt DateTime?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("flight_api_budget")
} }
// ============================================ // ============================================
@@ -197,6 +266,11 @@ model ScheduleEvent {
vehicleId String? vehicleId String?
vehicle Vehicle? @relation(fields: [vehicleId], references: [id], onDelete: SetNull) vehicle Vehicle? @relation(fields: [vehicleId], references: [id], onDelete: SetNull)
// Master/child event hierarchy (shared activity → transport legs)
masterEventId String?
masterEvent ScheduleEvent? @relation("EventHierarchy", fields: [masterEventId], references: [id], onDelete: SetNull)
childEvents ScheduleEvent[] @relation("EventHierarchy")
// Metadata // Metadata
notes String? @db.Text notes String? @db.Text
@@ -331,6 +405,7 @@ model GpsDevice {
// Location history // Location history
locationHistory GpsLocationHistory[] locationHistory GpsLocationHistory[]
trips GpsTrip[]
createdAt DateTime @default(now()) createdAt DateTime @default(now())
updatedAt DateTime @updatedAt updatedAt DateTime @updatedAt
@@ -346,7 +421,7 @@ model GpsLocationHistory {
latitude Float latitude Float
longitude Float longitude Float
altitude Float? altitude Float?
speed Float? // km/h speed Float? // mph (converted from knots during sync)
course Float? // Bearing in degrees course Float? // Bearing in degrees
accuracy Float? // Meters accuracy Float? // Meters
battery Float? // Battery percentage (0-100) battery Float? // Battery percentage (0-100)
@@ -356,10 +431,49 @@ model GpsLocationHistory {
createdAt DateTime @default(now()) createdAt DateTime @default(now())
@@map("gps_location_history") @@map("gps_location_history")
@@index([deviceId, timestamp]) @@unique([deviceId, timestamp]) // Prevent duplicate position records
@@index([timestamp]) // For cleanup job @@index([timestamp]) // For cleanup job
} }
enum TripStatus {
ACTIVE // Currently in progress
COMPLETED // Finished, OSRM route computed
PROCESSING // OSRM computation in progress
FAILED // OSRM computation failed
}
model GpsTrip {
id String @id @default(uuid())
deviceId String
device GpsDevice @relation(fields: [deviceId], references: [id], onDelete: Cascade)
status TripStatus @default(ACTIVE)
startTime DateTime
endTime DateTime?
startLatitude Float
startLongitude Float
endLatitude Float?
endLongitude Float?
// Pre-computed stats (filled on completion)
distanceMiles Float?
durationSeconds Int?
topSpeedMph Float?
averageSpeedMph Float?
pointCount Int @default(0)
// Pre-computed OSRM route (stored as JSON for instant display)
matchedRoute Json? // { coordinates: [lat,lng][], distance, duration, confidence }
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
@@map("gps_trips")
@@index([deviceId, startTime])
@@index([status])
}
model GpsSettings { model GpsSettings {
id String @id @default(uuid()) id String @id @default(uuid())

View File

@@ -3,145 +3,157 @@ import { PrismaClient, Role, Department, ArrivalMode, EventType, EventStatus, Ve
const prisma = new PrismaClient(); const prisma = new PrismaClient();
async function main() { async function main() {
console.log('🌱 Seeding database...'); console.log('🌱 Seeding database with BSA Jamboree scenario...');
// Clean up existing data (careful in production!) // Clean up existing data (preserves users/auth accounts)
await prisma.scheduleEvent.deleteMany({}); await prisma.scheduleEvent.deleteMany({});
await prisma.flight.deleteMany({}); await prisma.flight.deleteMany({});
await prisma.vehicle.deleteMany({}); await prisma.vehicle.deleteMany({});
await prisma.driver.deleteMany({}); // Don't delete drivers linked to users — only standalone test drivers
await prisma.driver.deleteMany({ where: { userId: null } });
await prisma.vIP.deleteMany({}); await prisma.vIP.deleteMany({});
await prisma.user.deleteMany({});
console.log('✅ Cleared existing data'); console.log('✅ Cleared existing test data (preserved user accounts)');
// Create sample users // =============================================
const admin = await prisma.user.create({ // VEHICLES — BSA Jamboree fleet
// =============================================
const suburban1 = await prisma.vehicle.create({
data: { data: {
auth0Id: 'auth0|admin-sample-id', name: 'Black Suburban #1',
email: 'admin@example.com',
name: 'Admin User',
role: Role.ADMINISTRATOR,
isApproved: true,
},
});
const coordinator = await prisma.user.create({
data: {
auth0Id: 'auth0|coordinator-sample-id',
email: 'coordinator@example.com',
name: 'Coordinator User',
role: Role.COORDINATOR,
isApproved: true,
},
});
// Note: test@test.com user is auto-created and auto-approved on first login (see auth.service.ts)
console.log('✅ Created sample users');
// Create sample vehicles with capacity
const blackSUV = await prisma.vehicle.create({
data: {
name: 'Black Suburban',
type: VehicleType.SUV, type: VehicleType.SUV,
licensePlate: 'ABC-1234', licensePlate: 'BSA-001',
seatCapacity: 6, seatCapacity: 6,
status: VehicleStatus.AVAILABLE, status: VehicleStatus.AVAILABLE,
notes: 'Leather interior, tinted windows', notes: 'Primary VIP vehicle, leather interior',
},
});
const suburban2 = await prisma.vehicle.create({
data: {
name: 'Black Suburban #2',
type: VehicleType.SUV,
licensePlate: 'BSA-002',
seatCapacity: 6,
status: VehicleStatus.AVAILABLE,
notes: 'Secondary VIP vehicle',
}, },
}); });
const whiteVan = await prisma.vehicle.create({ const whiteVan = await prisma.vehicle.create({
data: { data: {
name: 'White Sprinter Van', name: 'White 15-Passenger Van',
type: VehicleType.VAN, type: VehicleType.VAN,
licensePlate: 'XYZ-5678', licensePlate: 'BSA-003',
seatCapacity: 12, seatCapacity: 14,
status: VehicleStatus.AVAILABLE, status: VehicleStatus.AVAILABLE,
notes: 'High roof, wheelchair accessible', notes: 'Large group transport',
}, },
}); });
const blueSedan = await prisma.vehicle.create({ const golfCart1 = await prisma.vehicle.create({
data: { data: {
name: 'Blue Camry', name: 'Golf Cart A',
type: VehicleType.SEDAN, type: VehicleType.GOLF_CART,
licensePlate: 'DEF-9012', licensePlate: 'GC-A',
seatCapacity: 4, seatCapacity: 4,
status: VehicleStatus.AVAILABLE, status: VehicleStatus.AVAILABLE,
notes: 'Fuel efficient, good for short trips', notes: 'On-site shuttle between venues',
}, },
}); });
const grayBus = await prisma.vehicle.create({ const golfCart2 = await prisma.vehicle.create({
data: { data: {
name: 'Gray Charter Bus', name: 'Golf Cart B',
type: VehicleType.BUS, type: VehicleType.GOLF_CART,
licensePlate: 'BUS-0001', licensePlate: 'GC-B',
seatCapacity: 40, seatCapacity: 4,
status: VehicleStatus.AVAILABLE, status: VehicleStatus.AVAILABLE,
notes: 'Full size charter bus, A/C, luggage compartment', notes: 'On-site shuttle between venues',
}, },
}); });
console.log('✅ Created sample vehicles with capacities'); const charterBus = await prisma.vehicle.create({
// Create sample drivers
const driver1 = await prisma.driver.create({
data: { data: {
name: 'John Smith', name: 'Charter Bus',
phone: '+1 (555) 123-4567', type: VehicleType.BUS,
department: Department.OFFICE_OF_DEVELOPMENT, licensePlate: 'BSA-BUS',
seatCapacity: 45,
status: VehicleStatus.AVAILABLE,
notes: 'Full-size charter for large group moves',
}, },
}); });
const driver2 = await prisma.driver.create({ console.log('✅ Created 6 vehicles');
// =============================================
// DRIVERS
// =============================================
const driverTom = await prisma.driver.create({
data: { data: {
name: 'Jane Doe', name: 'Tom Bradley',
phone: '+1 (555) 987-6543', phone: '+1 (555) 100-0001',
department: Department.ADMIN, department: Department.ADMIN,
}, },
}); });
const driver3 = await prisma.driver.create({ const driverMaria = await prisma.driver.create({
data: { data: {
name: 'Amanda Washington', name: 'Maria Gonzalez',
phone: '+1 (555) 234-5678', phone: '+1 (555) 100-0002',
department: Department.OFFICE_OF_DEVELOPMENT,
},
});
const driver4 = await prisma.driver.create({
data: {
name: 'Michael Thompson',
phone: '+1 (555) 876-5432',
department: Department.ADMIN, department: Department.ADMIN,
}, },
}); });
console.log('✅ Created sample drivers'); const driverKevin = await prisma.driver.create({
// Create sample VIPs
const vip1 = await prisma.vIP.create({
data: { data: {
name: 'Dr. Robert Johnson', name: 'Kevin Park',
organization: 'Tech Corporation', phone: '+1 (555) 100-0003',
department: Department.OFFICE_OF_DEVELOPMENT,
},
});
const driverLisa = await prisma.driver.create({
data: {
name: 'Lisa Chen',
phone: '+1 (555) 100-0004',
department: Department.OFFICE_OF_DEVELOPMENT,
},
});
console.log('✅ Created 4 drivers');
// =============================================
// VIPs — BSA Jamboree dignitaries WITH PARTY SIZES
// =============================================
// Chief Scout Executive — travels with 2 handlers
const vipRoger = await prisma.vIP.create({
data: {
name: 'Roger Mosby',
organization: 'Boy Scouts of America',
department: Department.OFFICE_OF_DEVELOPMENT, department: Department.OFFICE_OF_DEVELOPMENT,
arrivalMode: ArrivalMode.FLIGHT, arrivalMode: ArrivalMode.FLIGHT,
airportPickup: true, airportPickup: true,
venueTransport: true, venueTransport: true,
notes: 'Prefers window seat, dietary restriction: vegetarian', partySize: 3, // Roger + 2 handlers
phone: '+1 (202) 555-0140',
email: 'roger.mosby@scouting.org',
emergencyContactName: 'Linda Mosby',
emergencyContactPhone: '+1 (202) 555-0141',
notes: 'Chief Scout Executive. Travels with 2 staff handlers. Requires accessible vehicle.',
flights: { flights: {
create: [ create: [
{ {
flightNumber: 'AA123', flightNumber: 'UA1142',
flightDate: new Date('2026-02-15'), flightDate: new Date('2026-02-05'),
segment: 1, segment: 1,
departureAirport: 'JFK', departureAirport: 'IAD',
arrivalAirport: 'LAX', arrivalAirport: 'DEN',
scheduledDeparture: new Date('2026-02-15T08:00:00'), scheduledDeparture: new Date('2026-02-05T07:00:00'),
scheduledArrival: new Date('2026-02-15T11:30:00'), scheduledArrival: new Date('2026-02-05T09:15:00'),
status: 'scheduled', status: 'scheduled',
}, },
], ],
@@ -149,199 +161,536 @@ async function main() {
}, },
}); });
const vip2 = await prisma.vIP.create({ // National Board Chair — travels with spouse
const vipPatricia = await prisma.vIP.create({
data: { data: {
name: 'Ms. Sarah Williams', name: 'Patricia Hawkins',
organization: 'Global Foundation', organization: 'BSA National Board',
department: Department.OFFICE_OF_DEVELOPMENT,
arrivalMode: ArrivalMode.FLIGHT,
airportPickup: true,
venueTransport: true,
partySize: 2, // Patricia + spouse
phone: '+1 (404) 555-0230',
email: 'patricia.hawkins@bsaboard.org',
emergencyContactName: 'Richard Hawkins',
emergencyContactPhone: '+1 (404) 555-0231',
notes: 'National Board Chair. Traveling with husband (Richard). Both attend all events.',
flights: {
create: [
{
flightNumber: 'DL783',
flightDate: new Date('2026-02-05'),
segment: 1,
departureAirport: 'ATL',
arrivalAirport: 'DEN',
scheduledDeparture: new Date('2026-02-05T06:30:00'),
scheduledArrival: new Date('2026-02-05T08:45:00'),
status: 'scheduled',
},
],
},
},
});
// Major Donor — solo
const vipJames = await prisma.vIP.create({
data: {
name: 'James Whitfield III',
organization: 'Whitfield Foundation',
department: Department.OFFICE_OF_DEVELOPMENT,
arrivalMode: ArrivalMode.FLIGHT,
airportPickup: true,
venueTransport: true,
partySize: 1, // Solo
phone: '+1 (214) 555-0375',
email: 'jwhitfield@whitfieldfoundation.org',
emergencyContactName: 'Catherine Whitfield',
emergencyContactPhone: '+1 (214) 555-0376',
notes: 'Major donor ($2M+). Eagle Scout class of 1978. Very punctual — do not be late.',
flights: {
create: [
{
flightNumber: 'AA456',
flightDate: new Date('2026-02-05'),
segment: 1,
departureAirport: 'DFW',
arrivalAirport: 'DEN',
scheduledDeparture: new Date('2026-02-05T10:00:00'),
scheduledArrival: new Date('2026-02-05T11:30:00'),
status: 'scheduled',
},
],
},
},
});
// Keynote Speaker — travels with assistant
const vipDrBaker = await prisma.vIP.create({
data: {
name: 'Dr. Angela Baker',
organization: 'National Geographic Society',
department: Department.OFFICE_OF_DEVELOPMENT,
arrivalMode: ArrivalMode.FLIGHT,
airportPickup: true,
venueTransport: true,
partySize: 2, // Dr. Baker + assistant
phone: '+1 (301) 555-0488',
email: 'abaker@natgeo.com',
emergencyContactName: 'Marcus Webb',
emergencyContactPhone: '+1 (301) 555-0489',
notes: 'Keynote speaker, Day 1. Traveling with assistant (Marcus). Needs quiet space before keynote.',
flights: {
create: [
{
flightNumber: 'SW221',
flightDate: new Date('2026-02-05'),
segment: 1,
departureAirport: 'BWI',
arrivalAirport: 'DEN',
scheduledDeparture: new Date('2026-02-05T08:15:00'),
scheduledArrival: new Date('2026-02-05T10:40:00'),
status: 'scheduled',
},
],
},
},
});
// Governor — travels with 3 (security detail + aide)
const vipGovMartinez = await prisma.vIP.create({
data: {
name: 'Gov. Carlos Martinez',
organization: 'State of Colorado',
department: Department.ADMIN, department: Department.ADMIN,
arrivalMode: ArrivalMode.SELF_DRIVING, arrivalMode: ArrivalMode.SELF_DRIVING,
expectedArrival: new Date('2026-02-16T14:00:00'), expectedArrival: new Date('2026-02-05T13:00:00'),
airportPickup: false, airportPickup: false,
venueTransport: true, venueTransport: true,
notes: 'Bringing assistant', partySize: 4, // Governor + security officer + aide + driver (their own driver stays)
phone: '+1 (303) 555-0100',
email: 'gov.martinez@state.co.us',
emergencyContactName: 'Elena Martinez',
emergencyContactPhone: '+1 (303) 555-0101',
notes: 'Governor arriving by motorcade. Party of 4: Gov, 1 state trooper, 1 aide, 1 advance staff. Their driver does NOT need a seat.',
}, },
}); });
const vip3 = await prisma.vIP.create({ // Local Council President — solo, self-driving
const vipSusan = await prisma.vIP.create({
data: { data: {
name: 'Emily Richardson (Harvard University)', name: 'Susan O\'Malley',
organization: 'Harvard University', organization: 'Denver Area Council BSA',
department: Department.OFFICE_OF_DEVELOPMENT, department: Department.ADMIN,
arrivalMode: ArrivalMode.FLIGHT, arrivalMode: ArrivalMode.SELF_DRIVING,
airportPickup: true, expectedArrival: new Date('2026-02-05T08:00:00'),
airportPickup: false,
venueTransport: true, venueTransport: true,
notes: 'Board member, requires accessible vehicle', partySize: 1,
phone: '+1 (720) 555-0550',
email: 'somalley@denvercouncil.org',
emergencyContactName: 'Patrick O\'Malley',
emergencyContactPhone: '+1 (720) 555-0551',
notes: 'Local council president. Knows the venue well. Can help with directions if needed.',
}, },
}); });
const vip4 = await prisma.vIP.create({ console.log('✅ Created 6 VIPs with party sizes');
console.log(' Roger Mosby (party: 3), Patricia Hawkins (party: 2)');
console.log(' James Whitfield III (party: 1), Dr. Angela Baker (party: 2)');
console.log(' Gov. Martinez (party: 4), Susan O\'Malley (party: 1)');
// =============================================
// SHARED ITINERARY ITEMS (master events)
// These are the actual activities everyone attends
// =============================================
// Use dates relative to "today + 2 days" so they show up in the War Room
const jamboreeDay1 = new Date();
jamboreeDay1.setDate(jamboreeDay1.getDate() + 2);
jamboreeDay1.setHours(0, 0, 0, 0);
const jamboreeDay2 = new Date(jamboreeDay1);
jamboreeDay2.setDate(jamboreeDay2.getDate() + 1);
// Day 1 shared events
const openingCeremony = await prisma.scheduleEvent.create({
data: { data: {
name: 'David Chen (Stanford)', vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipGovMartinez.id, vipSusan.id],
organization: 'Stanford University',
department: Department.OFFICE_OF_DEVELOPMENT,
arrivalMode: ArrivalMode.FLIGHT,
airportPickup: true,
venueTransport: true,
notes: 'Keynote speaker',
},
});
console.log('✅ Created sample VIPs');
// Create sample schedule events (unified activities) - NOW WITH MULTIPLE VIPS!
// Multi-VIP rideshare to Campfire Night (3 VIPs in one SUV)
await prisma.scheduleEvent.create({
data: {
vipIds: [vip3.id, vip4.id, vip1.id], // 3 VIPs sharing a ride
title: 'Transport to Campfire Night',
pickupLocation: 'Grand Hotel Lobby',
dropoffLocation: 'Camp Amphitheater',
startTime: new Date('2026-02-15T19:45:00'),
endTime: new Date('2026-02-15T20:00:00'),
description: 'Rideshare: Emily, David, and Dr. Johnson to campfire',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driver3.id,
vehicleId: blackSUV.id, // 3 VIPs in 6-seat SUV (3/6 seats used)
},
});
// Single VIP transport
await prisma.scheduleEvent.create({
data: {
vipIds: [vip1.id],
title: 'Airport Pickup - Dr. Johnson',
pickupLocation: 'LAX Terminal 4',
dropoffLocation: 'Grand Hotel',
startTime: new Date('2026-02-15T11:30:00'),
endTime: new Date('2026-02-15T12:30:00'),
description: 'Pick up Dr. Johnson from LAX',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driver1.id,
vehicleId: blueSedan.id, // 1 VIP in 4-seat sedan (1/4 seats used)
},
});
// Two VIPs sharing lunch transport
await prisma.scheduleEvent.create({
data: {
vipIds: [vip1.id, vip2.id],
title: 'Transport to Lunch - Day 1',
pickupLocation: 'Grand Hotel Lobby',
dropoffLocation: 'Main Dining Hall',
startTime: new Date('2026-02-15T11:45:00'),
endTime: new Date('2026-02-15T12:00:00'),
description: 'Rideshare: Dr. Johnson and Ms. Williams to lunch',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driver2.id,
vehicleId: blueSedan.id, // 2 VIPs in 4-seat sedan (2/4 seats used)
},
});
// Large group transport in van
await prisma.scheduleEvent.create({
data: {
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id],
title: 'Morning Shuttle to Conference',
pickupLocation: 'Grand Hotel Lobby',
dropoffLocation: 'Conference Center',
startTime: new Date('2026-02-15T08:00:00'),
endTime: new Date('2026-02-15T08:30:00'),
description: 'All VIPs to morning conference session',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driver4.id,
vehicleId: whiteVan.id, // 4 VIPs in 12-seat van (4/12 seats used)
},
});
// Non-transport activities (unified system)
// Opening Ceremony - all VIPs attending
await prisma.scheduleEvent.create({
data: {
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id],
title: 'Opening Ceremony', title: 'Opening Ceremony',
location: 'Main Stage', location: 'Main Arena',
startTime: new Date('2026-02-15T10:00:00'), startTime: new Date(jamboreeDay1.getTime() + 10 * 60 * 60 * 1000), // 10:00 AM
endTime: new Date('2026-02-15T11:30:00'), endTime: new Date(jamboreeDay1.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
description: 'Welcome and opening remarks', description: 'National anthem, color guard, welcome remarks by Chief Scout Executive. All VIPs seated in reserved section.',
type: EventType.EVENT, type: EventType.EVENT,
status: EventStatus.SCHEDULED, status: EventStatus.SCHEDULED,
}, },
}); });
// Lunch - Day 1 (all VIPs) const vipLuncheon = await prisma.scheduleEvent.create({
await prisma.scheduleEvent.create({
data: { data: {
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id], vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipGovMartinez.id, vipSusan.id],
title: 'Lunch - Day 1', title: 'VIP Luncheon',
location: 'Main Dining Hall', location: 'Eagle Lodge Private Dining',
startTime: new Date('2026-02-15T12:00:00'), startTime: new Date(jamboreeDay1.getTime() + 12 * 60 * 60 * 1000), // 12:00 PM
endTime: new Date('2026-02-15T13:30:00'), endTime: new Date(jamboreeDay1.getTime() + 13.5 * 60 * 60 * 1000), // 1:30 PM
description: 'Day 1 lunch for all attendees', description: 'Private luncheon for VIP guests and BSA leadership. Seated service.',
type: EventType.MEAL, type: EventType.MEAL,
status: EventStatus.SCHEDULED, status: EventStatus.SCHEDULED,
}, },
}); });
// Campfire Night (all VIPs) const keynoteAddress = await prisma.scheduleEvent.create({
await prisma.scheduleEvent.create({
data: { data: {
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id], vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Campfire Night', title: 'Keynote Address — Dr. Baker',
location: 'Camp Amphitheater', location: 'Main Arena',
startTime: new Date('2026-02-15T20:00:00'), startTime: new Date(jamboreeDay1.getTime() + 14 * 60 * 60 * 1000), // 2:00 PM
endTime: new Date('2026-02-15T22:00:00'), endTime: new Date(jamboreeDay1.getTime() + 15.5 * 60 * 60 * 1000), // 3:30 PM
description: 'Evening campfire and networking', description: 'Dr. Angela Baker delivers keynote on "Adventure and Discovery." VIPs in reserved front section.',
type: EventType.EVENT, type: EventType.EVENT,
status: EventStatus.SCHEDULED, status: EventStatus.SCHEDULED,
notes: 'Gov. Martinez departs before keynote — not attending this one.',
}, },
}); });
// Private meeting - just Dr. Johnson and Ms. Williams const donorMeeting = await prisma.scheduleEvent.create({
await prisma.scheduleEvent.create({
data: { data: {
vipIds: [vip1.id, vip2.id], vipIds: [vipJames.id, vipPatricia.id, vipRoger.id],
title: 'Donor Meeting', title: 'Donor Strategy Meeting',
location: 'Conference Room A', location: 'Eagle Lodge Conference Room',
startTime: new Date('2026-02-15T14:00:00'), startTime: new Date(jamboreeDay1.getTime() + 16 * 60 * 60 * 1000), // 4:00 PM
endTime: new Date('2026-02-15T15:00:00'), endTime: new Date(jamboreeDay1.getTime() + 17 * 60 * 60 * 1000), // 5:00 PM
description: 'Private meeting with development team', description: 'Private meeting: Whitfield Foundation partnership discussion with BSA leadership.',
type: EventType.MEETING, type: EventType.MEETING,
status: EventStatus.SCHEDULED, status: EventStatus.SCHEDULED,
}, },
}); });
console.log('✅ Created sample schedule events with multi-VIP rideshares and activities'); const campfireNight = await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Campfire Night',
location: 'Campfire Bowl',
startTime: new Date(jamboreeDay1.getTime() + 20 * 60 * 60 * 1000), // 8:00 PM
endTime: new Date(jamboreeDay1.getTime() + 22 * 60 * 60 * 1000), // 10:00 PM
description: 'Traditional Jamboree campfire with skits, songs, and awards. VIP seating near stage.',
type: EventType.EVENT,
status: EventStatus.SCHEDULED,
},
});
console.log('\n🎉 Database seeded successfully!'); // Day 2 shared events
console.log('\nSample Users:'); const eagleScoutCeremony = await prisma.scheduleEvent.create({
console.log('- Admin: admin@example.com'); data: {
console.log('- Coordinator: coordinator@example.com'); vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipSusan.id],
console.log('\nSample VIPs:'); title: 'Eagle Scout Recognition Ceremony',
console.log('- Dr. Robert Johnson (Flight arrival)'); location: 'Main Arena',
console.log('- Ms. Sarah Williams (Self-driving)'); startTime: new Date(jamboreeDay2.getTime() + 9 * 60 * 60 * 1000), // 9:00 AM
console.log('- Emily Richardson (Harvard University)'); endTime: new Date(jamboreeDay2.getTime() + 11 * 60 * 60 * 1000), // 11:00 AM
console.log('- David Chen (Stanford)'); description: 'Honoring 200+ new Eagle Scouts. James Whitfield giving remarks as Eagle Scout alumnus.',
console.log('\nSample Drivers:'); type: EventType.EVENT,
console.log('- John Smith'); status: EventStatus.SCHEDULED,
console.log('- Jane Doe'); },
console.log('- Amanda Washington'); });
console.log('- Michael Thompson');
console.log('\nSample Vehicles:'); const farewellBrunch = await prisma.scheduleEvent.create({
console.log('- Black Suburban (SUV, 6 seats)'); data: {
console.log('- White Sprinter Van (Van, 12 seats)'); vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
console.log('- Blue Camry (Sedan, 4 seats)'); title: 'Farewell Brunch',
console.log('- Gray Charter Bus (Bus, 40 seats)'); location: 'Eagle Lodge Private Dining',
console.log('\nSchedule Tasks (Multi-VIP Examples):'); startTime: new Date(jamboreeDay2.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
console.log('- 3 VIPs sharing SUV to Campfire (3/6 seats)'); endTime: new Date(jamboreeDay2.getTime() + 13 * 60 * 60 * 1000), // 1:00 PM
console.log('- 2 VIPs sharing sedan to Lunch (2/4 seats)'); description: 'Final meal together before departures. Thank-you gifts distributed.',
console.log('- 4 VIPs in van to Conference (4/12 seats)'); type: EventType.MEAL,
console.log('- 1 VIP solo in sedan from Airport (1/4 seats)'); status: EventStatus.SCHEDULED,
},
});
console.log('✅ Created 7 shared itinerary items (master events)');
// =============================================
// TRANSPORT LEGS — linked to master events
// These are the rides TO and FROM the shared events
// =============================================
// --- AIRPORT PICKUPS (Day 1 morning) ---
// Roger Mosby (party of 3) — airport pickup
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id],
title: 'Airport Pickup — Roger Mosby',
pickupLocation: 'DEN Terminal West, Door 507',
dropoffLocation: 'Jamboree Camp — VIP Lodge',
startTime: new Date('2026-02-05T09:15:00'),
endTime: new Date('2026-02-05T10:00:00'),
description: 'Party of 3 (Roger + 2 handlers). UA1142 lands 9:15 AM.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: suburban1.id, // 3 people in 6-seat SUV
},
});
// Patricia Hawkins (party of 2) — airport pickup
await prisma.scheduleEvent.create({
data: {
vipIds: [vipPatricia.id],
title: 'Airport Pickup — Patricia Hawkins',
pickupLocation: 'DEN Terminal South, Door 610',
dropoffLocation: 'Jamboree Camp — VIP Lodge',
startTime: new Date('2026-02-05T08:45:00'),
endTime: new Date('2026-02-05T09:30:00'),
description: 'Party of 2 (Patricia + husband Richard). DL783 lands 8:45 AM.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverMaria.id,
vehicleId: suburban2.id, // 2 people in 6-seat SUV
},
});
// Dr. Baker (party of 2) + James Whitfield (party of 1) — shared airport pickup
await prisma.scheduleEvent.create({
data: {
vipIds: [vipDrBaker.id, vipJames.id],
title: 'Airport Pickup — Dr. Baker & Whitfield',
pickupLocation: 'DEN Terminal East, Arrivals Curb',
dropoffLocation: 'Jamboree Camp — VIP Lodge',
startTime: new Date('2026-02-05T11:30:00'),
endTime: new Date('2026-02-05T12:15:00'),
description: 'Shared pickup. Dr. Baker (party 2: + assistant Marcus) lands 10:40 AM. Whitfield (solo) lands 11:30 AM. Wait for both.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverKevin.id,
vehicleId: suburban1.id, // 3 people total in 6-seat SUV
notes: 'Whitfield lands later — coordinate timing. Baker party can wait in VIP lounge.',
},
});
// --- DAY 1: TRANSPORT TO OPENING CEREMONY ---
// Group shuttle: all VIPs to Opening Ceremony (linked to master event)
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Transport to Opening Ceremony',
pickupLocation: 'VIP Lodge',
dropoffLocation: 'Main Arena — VIP Entrance',
startTime: new Date(jamboreeDay1.getTime() + 9.5 * 60 * 60 * 1000), // 9:30 AM
endTime: new Date(jamboreeDay1.getTime() + 9.75 * 60 * 60 * 1000), // 9:45 AM
description: 'All VIPs to Opening Ceremony. Total party: 9 people (5 VIPs + entourage).',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: whiteVan.id, // 9 people in 14-seat van
masterEventId: openingCeremony.id,
notes: 'Gov. Martinez arriving separately by motorcade.',
},
});
// --- DAY 1: TRANSPORT TO VIP LUNCHEON ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipGovMartinez.id, vipSusan.id],
title: 'Transport to VIP Luncheon',
pickupLocation: 'Main Arena — VIP Entrance',
dropoffLocation: 'Eagle Lodge',
startTime: new Date(jamboreeDay1.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
endTime: new Date(jamboreeDay1.getTime() + 11.75 * 60 * 60 * 1000), // 11:45 AM
description: 'All VIPs + entourage to lunch. Total: 13 people.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: whiteVan.id, // 13 people in 14-seat van — tight!
masterEventId: vipLuncheon.id,
},
});
// --- DAY 1: TRANSPORT TO KEYNOTE ---
// Two vehicles needed — Gov. Martinez departed, but still 9 people
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id],
title: 'Transport to Keynote (Group A)',
pickupLocation: 'Eagle Lodge',
dropoffLocation: 'Main Arena — VIP Entrance',
startTime: new Date(jamboreeDay1.getTime() + 13.75 * 60 * 60 * 1000), // 1:45 PM
endTime: new Date(jamboreeDay1.getTime() + 14 * 60 * 60 * 1000), // 2:00 PM
description: 'Group A: Roger (3), Patricia (2), James (1) = 6 people',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverMaria.id,
vehicleId: suburban1.id, // 6 people in 6-seat SUV — exactly full
masterEventId: keynoteAddress.id,
},
});
await prisma.scheduleEvent.create({
data: {
vipIds: [vipDrBaker.id, vipSusan.id],
title: 'Transport to Keynote (Group B)',
pickupLocation: 'Eagle Lodge',
dropoffLocation: 'Main Arena — Backstage',
startTime: new Date(jamboreeDay1.getTime() + 13.5 * 60 * 60 * 1000), // 1:30 PM
endTime: new Date(jamboreeDay1.getTime() + 13.75 * 60 * 60 * 1000), // 1:45 PM
description: 'Group B: Dr. Baker (2) + Susan (1) = 3 people. Baker goes backstage early for prep.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverLisa.id,
vehicleId: golfCart1.id, // 3 people in 4-seat golf cart
masterEventId: keynoteAddress.id,
},
});
// --- DAY 1: TRANSPORT TO DONOR MEETING ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipJames.id, vipPatricia.id, vipRoger.id],
title: 'Transport to Donor Meeting',
pickupLocation: 'Main Arena — VIP Entrance',
dropoffLocation: 'Eagle Lodge Conference Room',
startTime: new Date(jamboreeDay1.getTime() + 15.75 * 60 * 60 * 1000), // 3:45 PM
endTime: new Date(jamboreeDay1.getTime() + 16 * 60 * 60 * 1000), // 4:00 PM
description: 'Roger (3) + Patricia (2) + James (1) = 6 people to donor meeting',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverKevin.id,
vehicleId: suburban2.id,
masterEventId: donorMeeting.id,
},
});
// --- DAY 1: TRANSPORT TO CAMPFIRE ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Transport to Campfire Night',
pickupLocation: 'VIP Lodge',
dropoffLocation: 'Campfire Bowl — VIP Section',
startTime: new Date(jamboreeDay1.getTime() + 19.5 * 60 * 60 * 1000), // 7:30 PM
endTime: new Date(jamboreeDay1.getTime() + 19.75 * 60 * 60 * 1000), // 7:45 PM
description: 'All VIPs to campfire. 9 people total.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: whiteVan.id,
masterEventId: campfireNight.id,
},
});
// Return from campfire
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Return from Campfire Night',
pickupLocation: 'Campfire Bowl — VIP Section',
dropoffLocation: 'VIP Lodge',
startTime: new Date(jamboreeDay1.getTime() + 22 * 60 * 60 * 1000), // 10:00 PM
endTime: new Date(jamboreeDay1.getTime() + 22.25 * 60 * 60 * 1000), // 10:15 PM
description: 'Return all VIPs to lodge after campfire.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: whiteVan.id,
masterEventId: campfireNight.id,
},
});
// --- DAY 2: TRANSPORT TO EAGLE SCOUT CEREMONY ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipSusan.id],
title: 'Transport to Eagle Scout Ceremony',
pickupLocation: 'VIP Lodge',
dropoffLocation: 'Main Arena — VIP Entrance',
startTime: new Date(jamboreeDay2.getTime() + 8.5 * 60 * 60 * 1000), // 8:30 AM
endTime: new Date(jamboreeDay2.getTime() + 8.75 * 60 * 60 * 1000), // 8:45 AM
description: 'Roger (3) + Patricia (2) + James (1) + Susan (1) = 7 people. Dr. Baker not attending.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverMaria.id,
vehicleId: whiteVan.id,
masterEventId: eagleScoutCeremony.id,
},
});
// --- DAY 2: TRANSPORT TO FAREWELL BRUNCH ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
title: 'Transport to Farewell Brunch',
pickupLocation: 'Main Arena / VIP Lodge',
dropoffLocation: 'Eagle Lodge',
startTime: new Date(jamboreeDay2.getTime() + 11.25 * 60 * 60 * 1000), // 11:15 AM
endTime: new Date(jamboreeDay2.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
description: 'Final group transport. 9 people total.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverTom.id,
vehicleId: whiteVan.id,
masterEventId: farewellBrunch.id,
},
});
// --- DAY 2: AIRPORT DEPARTURES ---
await prisma.scheduleEvent.create({
data: {
vipIds: [vipRoger.id],
title: 'Airport Drop-off — Roger Mosby',
pickupLocation: 'VIP Lodge',
dropoffLocation: 'DEN Terminal West',
startTime: new Date(jamboreeDay2.getTime() + 14 * 60 * 60 * 1000), // 2:00 PM
endTime: new Date(jamboreeDay2.getTime() + 15 * 60 * 60 * 1000), // 3:00 PM
description: 'Roger + 2 handlers (3 people) to airport.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverKevin.id,
vehicleId: suburban1.id,
},
});
await prisma.scheduleEvent.create({
data: {
vipIds: [vipPatricia.id, vipJames.id, vipDrBaker.id],
title: 'Airport Drop-off — Hawkins, Whitfield, Baker',
pickupLocation: 'VIP Lodge',
dropoffLocation: 'DEN Terminal East',
startTime: new Date(jamboreeDay2.getTime() + 14.5 * 60 * 60 * 1000), // 2:30 PM
endTime: new Date(jamboreeDay2.getTime() + 15.5 * 60 * 60 * 1000), // 3:30 PM
description: 'Patricia (2) + James (1) + Dr. Baker (2) = 5 people to airport.',
type: EventType.TRANSPORT,
status: EventStatus.SCHEDULED,
driverId: driverMaria.id,
vehicleId: suburban2.id, // 5 people in 6-seat SUV
},
});
console.log('✅ Created 15 transport legs linked to master events');
// =============================================
// SUMMARY
// =============================================
console.log('\n🎉 BSA Jamboree seed data created successfully!\n');
console.log('VIPs (6):');
console.log(' Roger Mosby — Chief Scout Exec (party: 3 = VIP + 2 handlers)');
console.log(' Patricia Hawkins — Board Chair (party: 2 = VIP + spouse)');
console.log(' James Whitfield III — Major Donor (party: 1 = solo)');
console.log(' Dr. Angela Baker — Keynote Speaker (party: 2 = VIP + assistant)');
console.log(' Gov. Carlos Martinez — Governor (party: 4 = VIP + security/aide/advance)');
console.log(' Susan O\'Malley — Council President (party: 1 = solo)');
console.log('\nShared Events (7): Opening Ceremony, VIP Luncheon, Keynote, Donor Meeting, Campfire Night, Eagle Scout Ceremony, Farewell Brunch');
console.log('Transport Legs (15): Airport pickups/dropoffs + shuttles to/from each event');
console.log('Vehicles (6): 2 Suburbans, 1 Van, 2 Golf Carts, 1 Charter Bus');
console.log('Drivers (4): Tom Bradley, Maria Gonzalez, Kevin Park, Lisa Chen');
} }
main() main()

View File

@@ -1,6 +1,7 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config'; import { ConfigModule } from '@nestjs/config';
import { APP_GUARD } from '@nestjs/core'; import { APP_GUARD } from '@nestjs/core';
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
import { AppController } from './app.controller'; import { AppController } from './app.controller';
import { AppService } from './app.service'; import { AppService } from './app.service';
import { PrismaModule } from './prisma/prisma.module'; import { PrismaModule } from './prisma/prisma.module';
@@ -26,6 +27,12 @@ import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
envFilePath: '.env', envFilePath: '.env',
}), }),
// Rate limiting: 100 requests per 60 seconds per IP
ThrottlerModule.forRoot([{
ttl: 60000,
limit: 100,
}]),
// Core modules // Core modules
PrismaModule, PrismaModule,
AuthModule, AuthModule,
@@ -51,6 +58,11 @@ import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
provide: APP_GUARD, provide: APP_GUARD,
useClass: JwtAuthGuard, useClass: JwtAuthGuard,
}, },
// Apply rate limiting globally
{
provide: APP_GUARD,
useClass: ThrottlerGuard,
},
], ],
}) })
export class AppModule {} export class AppModule {}

View File

@@ -1,4 +1,4 @@
import { AbilityBuilder, PureAbility, AbilityClass, ExtractSubjectType, InferSubjects } from '@casl/ability'; import { AbilityBuilder, PureAbility, AbilityClass, ExtractSubjectType } from '@casl/ability';
import { Injectable } from '@nestjs/common'; import { Injectable } from '@nestjs/common';
import { Role, User, VIP, Driver, ScheduleEvent, Flight, Vehicle } from '@prisma/client'; import { Role, User, VIP, Driver, ScheduleEvent, Flight, Vehicle } from '@prisma/client';

View File

@@ -18,16 +18,18 @@ export class AuthService {
const name = payload[`${namespace}/name`] || payload.name || 'Unknown User'; const name = payload[`${namespace}/name`] || payload.name || 'Unknown User';
const picture = payload[`${namespace}/picture`] || payload.picture; const picture = payload[`${namespace}/picture`] || payload.picture;
// Check if user exists // Check if user exists (soft-deleted users automatically excluded by middleware)
let user = await this.prisma.user.findUnique({ let user = await this.prisma.user.findFirst({
where: { auth0Id }, where: { auth0Id },
include: { driver: true }, include: { driver: true },
}); });
if (!user) { if (!user) {
// Check if this is the first user (auto-approve as admin) // Use serializable transaction to prevent race condition
const approvedUserCount = await this.prisma.user.count({ // where two simultaneous registrations both become admin
where: { isApproved: true, deletedAt: null }, user = await this.prisma.$transaction(async (tx) => {
const approvedUserCount = await tx.user.count({
where: { isApproved: true },
}); });
const isFirstUser = approvedUserCount === 0; const isFirstUser = approvedUserCount === 0;
@@ -35,34 +37,36 @@ export class AuthService {
`Creating new user: ${email} (approvedUserCount: ${approvedUserCount}, isFirstUser: ${isFirstUser})`, `Creating new user: ${email} (approvedUserCount: ${approvedUserCount}, isFirstUser: ${isFirstUser})`,
); );
// Create new user
// First user is auto-approved as ADMINISTRATOR // First user is auto-approved as ADMINISTRATOR
// Subsequent users default to DRIVER and require approval // Subsequent users default to DRIVER and require approval
user = await this.prisma.user.create({ const newUser = await tx.user.create({
data: { data: {
auth0Id, auth0Id,
email, email,
name, name,
picture, picture,
role: isFirstUser ? Role.ADMINISTRATOR : Role.DRIVER, role: isFirstUser ? Role.ADMINISTRATOR : Role.DRIVER,
isApproved: isFirstUser, // Auto-approve first user only isApproved: isFirstUser,
}, },
include: { driver: true }, include: { driver: true },
}); });
this.logger.log( this.logger.log(
`User created: ${user.email} with role ${user.role} (approved: ${user.isApproved})`, `User created: ${newUser.email} with role ${newUser.role} (approved: ${newUser.isApproved})`,
); );
return newUser;
}, { isolationLevel: 'Serializable' });
} }
return user; return user;
} }
/** /**
* Get current user profile * Get current user profile (soft-deleted users automatically excluded by middleware)
*/ */
async getCurrentUser(auth0Id: string) { async getCurrentUser(auth0Id: string) {
return this.prisma.user.findUnique({ return this.prisma.user.findFirst({
where: { auth0Id }, where: { auth0Id },
include: { driver: true }, include: { driver: true },
}); });

View File

@@ -0,0 +1 @@
export * from './parse-boolean.pipe';

View File

@@ -0,0 +1,49 @@
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
/**
* Transforms query string values to proper booleans.
*
* Handles common boolean string representations:
* - 'true', '1', 'yes', 'on' → true
* - 'false', '0', 'no', 'off' → false
* - undefined, null, '' → false (default)
* - Any other value → BadRequestException
*
* @example
* ```typescript
* @Delete(':id')
* async remove(
* @Param('id') id: string,
* @Query('hard', ParseBooleanPipe) hard: boolean,
* ) {
* return this.service.remove(id, hard);
* }
* ```
*/
@Injectable()
export class ParseBooleanPipe implements PipeTransform<string | undefined, boolean> {
transform(value: string | undefined): boolean {
// Handle undefined, null, or empty string as false (default)
if (value === undefined || value === null || value === '') {
return false;
}
// Normalize to lowercase for comparison
const normalized = value.toLowerCase().trim();
// True values
if (['true', '1', 'yes', 'on'].includes(normalized)) {
return true;
}
// False values
if (['false', '0', 'no', 'off'].includes(normalized)) {
return false;
}
// Invalid value
throw new BadRequestException(
`Invalid boolean value: "${value}". Expected: true, false, 1, 0, yes, no, on, off`,
);
}
}

View File

@@ -0,0 +1,99 @@
/**
* Date utility functions to consolidate common date manipulation patterns
* across the VIP Coordinator application.
*/
/**
* Converts a Date object to ISO date string format (YYYY-MM-DD).
* Replaces the repetitive pattern: date.toISOString().split('T')[0]
*
* @param date - The date to convert
* @returns ISO date string in YYYY-MM-DD format
*
* @example
* const dateStr = toDateString(new Date('2024-01-15T10:30:00Z'));
* // Returns: '2024-01-15'
*/
export function toDateString(date: Date): string {
return date.toISOString().split('T')[0];
}
/**
* Normalizes a Date object to the start of the day (00:00:00.000).
* Replaces the pattern: date.setHours(0, 0, 0, 0)
*
* @param date - The date to normalize
* @returns A new Date object set to the start of the day
*
* @example
* const dayStart = startOfDay(new Date('2024-01-15T15:45:30Z'));
* // Returns: Date object at 2024-01-15T00:00:00.000
*/
export function startOfDay(date: Date): Date {
const normalized = new Date(date);
normalized.setHours(0, 0, 0, 0);
return normalized;
}
/**
* Normalizes a Date object to the end of the day (23:59:59.999).
*
* @param date - The date to normalize
* @returns A new Date object set to the end of the day
*
* @example
* const dayEnd = endOfDay(new Date('2024-01-15T10:30:00Z'));
* // Returns: Date object at 2024-01-15T23:59:59.999
*/
export function endOfDay(date: Date): Date {
const normalized = new Date(date);
normalized.setHours(23, 59, 59, 999);
return normalized;
}
/**
* Converts optional date string fields to Date objects for multiple fields at once.
* Useful for DTO to Prisma data transformation where only provided fields should be converted.
*
* @param obj - The object containing date string fields
* @param fields - Array of field names that should be converted to Date objects if present
* @returns New object with specified fields converted to Date objects
*
* @example
* const dto = {
* name: 'Flight 123',
* scheduledDeparture: '2024-01-15T10:00:00Z',
* scheduledArrival: '2024-01-15T12:00:00Z',
* actualDeparture: undefined,
* };
*
* const data = convertOptionalDates(dto, [
* 'scheduledDeparture',
* 'scheduledArrival',
* 'actualDeparture',
* 'actualArrival'
* ]);
*
* // Result: {
* // name: 'Flight 123',
* // scheduledDeparture: Date object,
* // scheduledArrival: Date object,
* // actualDeparture: undefined,
* // actualArrival: undefined
* // }
*/
export function convertOptionalDates<T extends Record<string, any>>(
obj: T,
fields: (keyof T)[],
): T {
const result = { ...obj };
for (const field of fields) {
const value = obj[field];
if (value !== undefined && value !== null) {
result[field] = new Date(value as any) as any;
}
}
return result;
}

View File

@@ -0,0 +1,78 @@
import { ForbiddenException, Logger } from '@nestjs/common';
/**
* Enforces hard-delete authorization and executes the appropriate delete operation.
*
* @param options Configuration object
* @param options.id Entity ID to delete
* @param options.hardDelete Whether to perform hard delete (true) or soft delete (false)
* @param options.userRole User's role (required for hard delete authorization)
* @param options.findOne Function to find and verify entity exists
* @param options.performHardDelete Function to perform hard delete (e.g., prisma.model.delete)
* @param options.performSoftDelete Function to perform soft delete (e.g., prisma.model.update)
* @param options.entityName Name of entity for logging (e.g., 'VIP', 'Driver')
* @param options.logger Logger instance for the service
* @returns Promise resolving to the deleted entity
* @throws {ForbiddenException} If non-admin attempts hard delete
*
* @example
* ```typescript
* async remove(id: string, hardDelete = false, userRole?: string) {
* return executeHardDelete({
* id,
* hardDelete,
* userRole,
* findOne: async (id) => this.findOne(id),
* performHardDelete: async (id) => this.prisma.vIP.delete({ where: { id } }),
* performSoftDelete: async (id) => this.prisma.vIP.update({
* where: { id },
* data: { deletedAt: new Date() },
* }),
* entityName: 'VIP',
* logger: this.logger,
* });
* }
* ```
*/
export async function executeHardDelete<T>(options: {
id: string;
hardDelete: boolean;
userRole?: string;
findOne: (id: string) => Promise<T & { id: string; name?: string }>;
performHardDelete: (id: string) => Promise<any>;
performSoftDelete: (id: string) => Promise<any>;
entityName: string;
logger: Logger;
}): Promise<any> {
const {
id,
hardDelete,
userRole,
findOne,
performHardDelete,
performSoftDelete,
entityName,
logger,
} = options;
// Authorization check: only administrators can hard delete
if (hardDelete && userRole !== 'ADMINISTRATOR') {
throw new ForbiddenException(
'Only administrators can permanently delete records',
);
}
// Verify entity exists
const entity = await findOne(id);
// Perform the appropriate delete operation
if (hardDelete) {
const entityLabel = entity.name || entity.id;
logger.log(`Hard deleting ${entityName}: ${entityLabel}`);
return performHardDelete(entity.id);
}
const entityLabel = entity.name || entity.id;
logger.log(`Soft deleting ${entityName}: ${entityLabel}`);
return performSoftDelete(entity.id);
}

View File

@@ -0,0 +1,7 @@
/**
* Common utility functions used throughout the application.
* Export all utilities from this central location for easier imports.
*/
export * from './date.utils';
export * from './hard-delete.utils';

View File

@@ -0,0 +1,462 @@
import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { toDateString, startOfDay } from '../common/utils/date.utils';
interface ToolResult {
success: boolean;
data?: any;
error?: string;
message?: string;
}
@Injectable()
export class CopilotFleetService {
private readonly logger = new Logger(CopilotFleetService.name);
constructor(private readonly prisma: PrismaService) {}
async getAvailableVehicles(filters: Record<string, any>): Promise<ToolResult> {
const where: any = { deletedAt: null, status: 'AVAILABLE' };
if (filters.type) {
where.type = filters.type;
}
if (filters.minSeats) {
where.seatCapacity = { gte: filters.minSeats };
}
const vehicles = await this.prisma.vehicle.findMany({
where,
orderBy: [{ type: 'asc' }, { seatCapacity: 'desc' }],
});
return {
success: true,
data: vehicles,
message: `Found ${vehicles.length} available vehicle(s).`,
};
}
async assignVehicleToEvent(eventId: string, vehicleId: string): Promise<ToolResult> {
const event = await this.prisma.scheduleEvent.findFirst({
where: { id: eventId, deletedAt: null },
});
if (!event) {
return { success: false, error: `Event with ID ${eventId} not found.` };
}
// If vehicleId is null, we're unassigning
if (vehicleId === null || vehicleId === 'null') {
const updatedEvent = await this.prisma.scheduleEvent.update({
where: { id: eventId },
data: { vehicleId: null },
include: {
driver: true,
},
});
return {
success: true,
data: updatedEvent,
message: `Vehicle unassigned from event "${updatedEvent.title}"`,
};
}
// Verify vehicle exists
const vehicle = await this.prisma.vehicle.findFirst({
where: { id: vehicleId, deletedAt: null },
});
if (!vehicle) {
return { success: false, error: `Vehicle with ID ${vehicleId} not found.` };
}
const updatedEvent = await this.prisma.scheduleEvent.update({
where: { id: eventId },
data: { vehicleId },
include: {
driver: true,
vehicle: true,
},
});
return {
success: true,
data: updatedEvent,
message: `Vehicle ${vehicle.name} assigned to event "${updatedEvent.title}"`,
};
}
async suggestVehicleForEvent(input: Record<string, any>): Promise<ToolResult> {
const { eventId } = input;
const event = await this.prisma.scheduleEvent.findFirst({
where: { id: eventId, deletedAt: null },
});
if (!event) {
return { success: false, error: `Event with ID ${eventId} not found.` };
}
// Fetch VIP info to determine party size
const vips = await this.prisma.vIP.findMany({
where: { id: { in: event.vipIds } },
select: { id: true, name: true, partySize: true },
});
// Determine required capacity based on total party size
const requiredSeats = vips.reduce((sum, v) => sum + (v.partySize || 1), 0);
// Find vehicles not in use during this event time
const busyVehicleIds = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
id: { not: eventId },
status: { not: 'CANCELLED' },
vehicleId: { not: null },
OR: [
{
startTime: { lte: event.startTime },
endTime: { gt: event.startTime },
},
{
startTime: { lt: event.endTime },
endTime: { gte: event.endTime },
},
],
},
select: { vehicleId: true },
});
const busyIds = busyVehicleIds.map((e) => e.vehicleId).filter((id): id is string => id !== null);
// Find available vehicles with sufficient capacity
const suitableVehicles = await this.prisma.vehicle.findMany({
where: {
deletedAt: null,
status: 'AVAILABLE',
seatCapacity: { gte: requiredSeats },
id: { notIn: busyIds },
},
orderBy: [
{ seatCapacity: 'asc' }, // Prefer smallest suitable vehicle
],
});
return {
success: true,
data: {
eventId,
eventTitle: event.title,
vipNames: vips.map((v) => v.name),
requiredSeats,
suggestions: suitableVehicles.map((v) => ({
id: v.id,
name: v.name,
type: v.type,
seatCapacity: v.seatCapacity,
})),
},
message:
suitableVehicles.length > 0
? `Found ${suitableVehicles.length} suitable vehicle(s) for this event (requires ${requiredSeats} seat(s)).`
: `No available vehicles found with capacity for ${requiredSeats} passenger(s) during this time.`,
};
}
async getVehicleSchedule(input: Record<string, any>): Promise<ToolResult> {
const { vehicleName, vehicleId, startDate, endDate } = input;
let vehicle;
if (vehicleId) {
vehicle = await this.prisma.vehicle.findFirst({
where: { id: vehicleId, deletedAt: null },
});
} else if (vehicleName) {
const vehicles = await this.prisma.vehicle.findMany({
where: {
deletedAt: null,
name: { contains: vehicleName, mode: 'insensitive' },
},
});
if (vehicles.length === 0) {
return { success: false, error: `No vehicle found matching "${vehicleName}".` };
}
if (vehicles.length > 1) {
return {
success: false,
error: `Multiple vehicles match "${vehicleName}": ${vehicles.map((v) => v.name).join(', ')}. Please be more specific.`,
};
}
vehicle = vehicles[0];
} else {
return { success: false, error: 'Either vehicleName or vehicleId is required.' };
}
if (!vehicle) {
return { success: false, error: 'Vehicle not found.' };
}
const dateStart = startOfDay(new Date(startDate));
const dateEnd = new Date(endDate);
dateEnd.setHours(23, 59, 59, 999);
const events = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
vehicleId: vehicle.id,
startTime: { gte: dateStart, lte: dateEnd },
status: { not: 'CANCELLED' },
},
include: {
driver: true,
},
orderBy: { startTime: 'asc' },
});
// Fetch VIP names for all events
const allVipIds = events.flatMap((e) => e.vipIds);
const uniqueVipIds = [...new Set(allVipIds)];
const vips = await this.prisma.vIP.findMany({
where: { id: { in: uniqueVipIds } },
select: { id: true, name: true },
});
const vipMap = new Map(vips.map((v) => [v.id, v.name]));
const totalHours =
events.reduce((sum, e) => {
return sum + (e.endTime.getTime() - e.startTime.getTime());
}, 0) / 3600000;
return {
success: true,
data: {
vehicle: {
id: vehicle.id,
name: vehicle.name,
type: vehicle.type,
seatCapacity: vehicle.seatCapacity,
status: vehicle.status,
},
dateRange: {
start: toDateString(dateStart),
end: toDateString(dateEnd),
},
eventCount: events.length,
totalHours: Math.round(totalHours * 10) / 10,
events: events.map((e) => ({
eventId: e.id,
title: e.title,
type: e.type,
startTime: e.startTime,
endTime: e.endTime,
vipNames: e.vipIds.map((id) => vipMap.get(id) || 'Unknown'),
driverName: e.driver?.name || null,
pickupLocation: e.pickupLocation,
dropoffLocation: e.dropoffLocation,
location: e.location,
})),
},
message: `Vehicle ${vehicle.name} has ${events.length} scheduled event(s) (${Math.round(totalHours * 10) / 10} hours total).`,
};
}
async searchDrivers(filters: Record<string, any>): Promise<ToolResult> {
const where: any = { deletedAt: null };
if (filters.name) {
where.name = { contains: filters.name, mode: 'insensitive' };
}
if (filters.department) {
where.department = filters.department;
}
if (filters.availableOnly) {
where.isAvailable = true;
}
const drivers = await this.prisma.driver.findMany({
where,
orderBy: { name: 'asc' },
});
return {
success: true,
data: drivers,
message: `Found ${drivers.length} driver(s) matching the criteria.`,
};
}
async getDriverSchedule(
driverId: string,
startDate?: string,
endDate?: string,
): Promise<ToolResult> {
const driver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null },
});
if (!driver) {
return { success: false, error: `Driver with ID ${driverId} not found.` };
}
const where: any = {
deletedAt: null,
driverId,
status: { not: 'CANCELLED' },
};
if (startDate) {
where.startTime = { gte: new Date(startDate) };
}
if (endDate) {
where.endTime = { lte: new Date(endDate) };
}
const events = await this.prisma.scheduleEvent.findMany({
where,
include: {
vehicle: true,
},
orderBy: { startTime: 'asc' },
});
// Fetch VIP names for all events
const allVipIds = events.flatMap((e) => e.vipIds);
const uniqueVipIds = [...new Set(allVipIds)];
const vips = await this.prisma.vIP.findMany({
where: { id: { in: uniqueVipIds } },
select: { id: true, name: true },
});
const vipMap = new Map(vips.map((v) => [v.id, v.name]));
const eventsWithVipNames = events.map((event) => ({
...event,
vipNames: event.vipIds.map((id) => vipMap.get(id) || 'Unknown'),
}));
return {
success: true,
data: {
driver,
events: eventsWithVipNames,
eventCount: events.length,
},
message: `Driver ${driver.name} has ${events.length} scheduled event(s).`,
};
}
async listAllDrivers(input: Record<string, any>): Promise<ToolResult> {
const { includeUnavailable = true } = input;
const where: any = { deletedAt: null };
if (!includeUnavailable) {
where.isAvailable = true;
}
const drivers = await this.prisma.driver.findMany({
where,
orderBy: { name: 'asc' },
select: {
id: true,
name: true,
phone: true,
department: true,
isAvailable: true,
},
});
return {
success: true,
data: drivers,
message: `Found ${drivers.length} driver(s) in the system.`,
};
}
async findAvailableDriversForTimerange(input: Record<string, any>): Promise<ToolResult> {
const { startTime, endTime, preferredDepartment } = input;
// Get all drivers
const where: any = { deletedAt: null, isAvailable: true };
if (preferredDepartment) {
where.department = preferredDepartment;
}
const allDrivers = await this.prisma.driver.findMany({
where,
});
// Find drivers with conflicting events
const busyDriverIds = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
driverId: { not: null },
status: { not: 'CANCELLED' },
OR: [
{
startTime: { lte: new Date(startTime) },
endTime: { gt: new Date(startTime) },
},
{
startTime: { lt: new Date(endTime) },
endTime: { gte: new Date(endTime) },
},
],
},
select: { driverId: true },
});
const busyIds = new Set(busyDriverIds.map((e) => e.driverId));
const availableDrivers = allDrivers.filter((d) => !busyIds.has(d.id));
return {
success: true,
data: availableDrivers,
message: `Found ${availableDrivers.length} available driver(s) for the specified time range.`,
};
}
async updateDriver(input: Record<string, any>): Promise<ToolResult> {
const { driverId, ...updates } = input;
const existingDriver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null },
});
if (!existingDriver) {
return { success: false, error: `Driver with ID ${driverId} not found.` };
}
const updateData: any = {};
if (updates.name !== undefined) updateData.name = updates.name;
if (updates.phone !== undefined) updateData.phone = updates.phone;
if (updates.department !== undefined) updateData.department = updates.department;
if (updates.isAvailable !== undefined) updateData.isAvailable = updates.isAvailable;
if (updates.shiftStartTime !== undefined) updateData.shiftStartTime = updates.shiftStartTime;
if (updates.shiftEndTime !== undefined) updateData.shiftEndTime = updates.shiftEndTime;
const driver = await this.prisma.driver.update({
where: { id: driverId },
data: updateData,
});
this.logger.log(`Driver updated: ${driverId}`);
return {
success: true,
data: driver,
message: `Driver ${driver.name} updated successfully.`,
};
}
}

View File

@@ -0,0 +1,304 @@
import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { toDateString, startOfDay } from '../common/utils/date.utils';
interface ToolResult {
success: boolean;
data?: any;
error?: string;
message?: string;
}
@Injectable()
export class CopilotReportsService {
private readonly logger = new Logger(CopilotReportsService.name);
constructor(private readonly prisma: PrismaService) {}
async getDriverWorkloadSummary(input: Record<string, any>): Promise<ToolResult> {
const { startDate, endDate } = input;
const dateStart = startOfDay(new Date(startDate));
const dateEnd = new Date(endDate);
dateEnd.setHours(23, 59, 59, 999);
// Get all drivers
const drivers = await this.prisma.driver.findMany({
where: { deletedAt: null },
orderBy: { name: 'asc' },
});
// Get all events in range
const events = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
startTime: { gte: dateStart, lte: dateEnd },
status: { not: 'CANCELLED' },
driverId: { not: null },
},
include: {
driver: true,
},
});
// Calculate workload for each driver
const workloadData = drivers.map((driver) => {
const driverEvents = events.filter((e) => e.driverId === driver.id);
const totalHours =
driverEvents.reduce((sum, e) => {
return sum + (e.endTime.getTime() - e.startTime.getTime());
}, 0) / 3600000;
const totalDays = Math.ceil(
(dateEnd.getTime() - dateStart.getTime()) / (1000 * 60 * 60 * 24),
);
const eventsByType = driverEvents.reduce(
(acc, e) => {
acc[e.type] = (acc[e.type] || 0) + 1;
return acc;
},
{} as Record<string, number>,
);
return {
driverId: driver.id,
driverName: driver.name,
department: driver.department,
isAvailable: driver.isAvailable,
eventCount: driverEvents.length,
totalHours: Math.round(totalHours * 10) / 10,
averageHoursPerDay: Math.round((totalHours / totalDays) * 10) / 10,
eventsByType,
};
});
// Sort by total hours descending
workloadData.sort((a, b) => b.totalHours - a.totalHours);
const totalEvents = events.length;
const totalHours =
events.reduce((sum, e) => {
return sum + (e.endTime.getTime() - e.startTime.getTime());
}, 0) / 3600000;
return {
success: true,
data: {
dateRange: {
start: toDateString(dateStart),
end: toDateString(dateEnd),
},
summary: {
totalDrivers: drivers.length,
totalEvents,
totalHours: Math.round(totalHours * 10) / 10,
averageEventsPerDriver: Math.round((totalEvents / drivers.length) * 10) / 10,
},
driverWorkloads: workloadData,
},
message: `Workload summary for ${drivers.length} driver(s) from ${toDateString(dateStart)} to ${toDateString(dateEnd)}.`,
};
}
async getCurrentSystemStatus(): Promise<ToolResult> {
const now = new Date();
const today = startOfDay(now);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
const nextWeek = new Date(today);
nextWeek.setDate(nextWeek.getDate() + 7);
const [
vipCount,
vehicleCount,
driverCount,
todaysEvents,
upcomingEvents,
unassignedEvents,
availableDrivers,
availableVehicles,
] = await Promise.all([
this.prisma.vIP.count({ where: { deletedAt: null } }),
this.prisma.vehicle.count({ where: { deletedAt: null } }),
this.prisma.driver.count({ where: { deletedAt: null } }),
this.prisma.scheduleEvent.count({
where: {
deletedAt: null,
startTime: { gte: today, lt: tomorrow },
status: { not: 'CANCELLED' },
},
}),
this.prisma.scheduleEvent.count({
where: {
deletedAt: null,
startTime: { gte: tomorrow, lt: nextWeek },
status: { not: 'CANCELLED' },
},
}),
this.prisma.scheduleEvent.count({
where: {
deletedAt: null,
startTime: { gte: now },
status: { in: ['SCHEDULED'] },
OR: [{ driverId: null }, { vehicleId: null }],
},
}),
this.prisma.driver.count({ where: { deletedAt: null, isAvailable: true } }),
this.prisma.vehicle.count({ where: { deletedAt: null, status: 'AVAILABLE' } }),
]);
const status = {
timestamp: now.toISOString(),
resources: {
vips: vipCount,
drivers: { total: driverCount, available: availableDrivers },
vehicles: { total: vehicleCount, available: availableVehicles },
},
events: {
today: todaysEvents,
next7Days: upcomingEvents,
needingAttention: unassignedEvents,
},
alerts: [] as string[],
};
// Add alerts for issues
if (unassignedEvents > 0) {
status.alerts.push(`${unassignedEvents} upcoming event(s) need driver/vehicle assignment`);
}
if (availableDrivers === 0) {
status.alerts.push('No drivers currently marked as available');
}
if (availableVehicles === 0) {
status.alerts.push('No vehicles currently available');
}
return {
success: true,
data: status,
message:
status.alerts.length > 0
? `System status retrieved. ATTENTION: ${status.alerts.length} alert(s) require attention.`
: 'System status retrieved. No immediate issues.',
};
}
async getTodaysSummary(): Promise<ToolResult> {
const today = startOfDay(new Date());
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);
// Get today's events
const events = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
startTime: { gte: today, lt: tomorrow },
status: { not: 'CANCELLED' },
},
include: {
driver: true,
vehicle: true,
},
orderBy: { startTime: 'asc' },
});
// Fetch VIP names for all events
const allVipIds = events.flatMap((e) => e.vipIds);
const uniqueVipIds = [...new Set(allVipIds)];
const vips = await this.prisma.vIP.findMany({
where: { id: { in: uniqueVipIds } },
select: { id: true, name: true },
});
const vipMap = new Map(vips.map((v) => [v.id, v.name]));
// Get VIPs arriving today (flights or self-driving)
const arrivingVips = await this.prisma.vIP.findMany({
where: {
deletedAt: null,
OR: [
{
expectedArrival: { gte: today, lt: tomorrow },
},
{
flights: {
some: {
scheduledArrival: { gte: today, lt: tomorrow },
},
},
},
],
},
include: {
flights: {
where: {
scheduledArrival: { gte: today, lt: tomorrow },
},
orderBy: { scheduledArrival: 'asc' },
},
},
});
// Get driver assignments
const driversOnDuty = events
.filter((e) => e.driver)
.reduce((acc, e) => {
if (e.driver && !acc.find((d) => d.id === e.driver!.id)) {
acc.push(e.driver);
}
return acc;
}, [] as NonNullable<typeof events[0]['driver']>[]);
// Unassigned events
const unassigned = events.filter((e) => !e.driverId || !e.vehicleId);
return {
success: true,
data: {
date: toDateString(today),
summary: {
totalEvents: events.length,
arrivingVips: arrivingVips.length,
driversOnDuty: driversOnDuty.length,
unassignedEvents: unassigned.length,
},
events: events.map((e) => ({
id: e.id,
time: e.startTime,
title: e.title,
type: e.type,
vipNames: e.vipIds.map((id) => vipMap.get(id) || 'Unknown'),
driverName: e.driver?.name || 'UNASSIGNED',
vehicleName: e.vehicle?.name || 'UNASSIGNED',
location: e.location || e.pickupLocation,
})),
arrivingVips: arrivingVips.map((v) => ({
id: v.id,
name: v.name,
arrivalMode: v.arrivalMode,
expectedArrival: v.expectedArrival,
flights: v.flights.map((f) => ({
flightNumber: f.flightNumber,
scheduledArrival: f.scheduledArrival,
arrivalAirport: f.arrivalAirport,
})),
})),
driversOnDuty: driversOnDuty.map((d) => ({
id: d.id,
name: d.name,
eventCount: events.filter((e) => e.driverId === d.id).length,
})),
unassignedEvents: unassigned.map((e) => ({
id: e.id,
time: e.startTime,
title: e.title,
vipNames: e.vipIds.map((id) => vipMap.get(id) || 'Unknown'),
needsDriver: !e.driverId,
needsVehicle: !e.vehicleId,
})),
},
message: `Today's summary: ${events.length} event(s), ${arrivingVips.length} VIP(s) arriving, ${unassigned.length} unassigned.`,
};
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,275 @@
import { Injectable, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
interface ToolResult {
success: boolean;
data?: any;
error?: string;
message?: string;
}
@Injectable()
export class CopilotVipService {
private readonly logger = new Logger(CopilotVipService.name);
constructor(private readonly prisma: PrismaService) {}
async searchVips(filters: Record<string, any>): Promise<ToolResult> {
const where: any = { deletedAt: null };
if (filters.name) {
where.name = { contains: filters.name, mode: 'insensitive' };
}
if (filters.organization) {
where.organization = { contains: filters.organization, mode: 'insensitive' };
}
if (filters.department) {
where.department = filters.department;
}
if (filters.arrivalMode) {
where.arrivalMode = filters.arrivalMode;
}
const vips = await this.prisma.vIP.findMany({
where,
include: {
flights: true,
},
take: 20,
});
// Fetch events for these VIPs
const vipIds = vips.map((v) => v.id);
const events = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
vipIds: { hasSome: vipIds },
},
orderBy: { startTime: 'asc' },
});
// Attach events to VIPs
const vipsWithEvents = vips.map((vip) => ({
...vip,
events: events.filter((e) => e.vipIds.includes(vip.id)).slice(0, 5),
}));
return { success: true, data: vipsWithEvents };
}
async getVipDetails(vipId: string): Promise<ToolResult> {
const vip = await this.prisma.vIP.findUnique({
where: { id: vipId },
include: {
flights: true,
},
});
if (!vip) {
return { success: false, error: 'VIP not found' };
}
// Fetch events for this VIP
const events = await this.prisma.scheduleEvent.findMany({
where: {
deletedAt: null,
vipIds: { has: vipId },
},
include: {
driver: true,
vehicle: true,
},
orderBy: { startTime: 'asc' },
});
return { success: true, data: { ...vip, events } };
}
async createVip(input: Record<string, any>): Promise<ToolResult> {
const vip = await this.prisma.vIP.create({
data: {
name: input.name,
organization: input.organization,
department: input.department,
arrivalMode: input.arrivalMode,
expectedArrival: input.expectedArrival ? new Date(input.expectedArrival) : null,
airportPickup: input.airportPickup ?? false,
venueTransport: input.venueTransport ?? false,
partySize: input.partySize ?? 1,
notes: input.notes,
isRosterOnly: input.isRosterOnly ?? false,
phone: input.phone || null,
email: input.email || null,
emergencyContactName: input.emergencyContactName || null,
emergencyContactPhone: input.emergencyContactPhone || null,
},
});
return { success: true, data: vip };
}
async updateVip(input: Record<string, any>): Promise<ToolResult> {
const { vipId, ...updateData } = input;
const data: any = {};
if (updateData.name !== undefined) data.name = updateData.name;
if (updateData.organization !== undefined) data.organization = updateData.organization;
if (updateData.department !== undefined) data.department = updateData.department;
if (updateData.arrivalMode !== undefined) data.arrivalMode = updateData.arrivalMode;
if (updateData.expectedArrival !== undefined)
data.expectedArrival = updateData.expectedArrival
? new Date(updateData.expectedArrival)
: null;
if (updateData.airportPickup !== undefined) data.airportPickup = updateData.airportPickup;
if (updateData.venueTransport !== undefined)
data.venueTransport = updateData.venueTransport;
if (updateData.partySize !== undefined) data.partySize = updateData.partySize;
if (updateData.notes !== undefined) data.notes = updateData.notes;
if (updateData.isRosterOnly !== undefined) data.isRosterOnly = updateData.isRosterOnly;
if (updateData.phone !== undefined) data.phone = updateData.phone || null;
if (updateData.email !== undefined) data.email = updateData.email || null;
if (updateData.emergencyContactName !== undefined)
data.emergencyContactName = updateData.emergencyContactName || null;
if (updateData.emergencyContactPhone !== undefined)
data.emergencyContactPhone = updateData.emergencyContactPhone || null;
const vip = await this.prisma.vIP.update({
where: { id: vipId },
data,
include: { flights: true },
});
return { success: true, data: vip };
}
async getVipItinerary(input: Record<string, any>): Promise<ToolResult> {
const { vipId, startDate, endDate } = input;
const vip = await this.prisma.vIP.findUnique({
where: { id: vipId },
});
if (!vip) {
return { success: false, error: 'VIP not found' };
}
// Build date filters
const dateFilter: any = {};
if (startDate) dateFilter.gte = new Date(startDate);
if (endDate) dateFilter.lte = new Date(endDate);
// Get flights
const flightsWhere: any = { vipId };
if (startDate || endDate) {
flightsWhere.flightDate = dateFilter;
}
const flights = await this.prisma.flight.findMany({
where: flightsWhere,
orderBy: { scheduledDeparture: 'asc' },
});
// Get events
const eventsWhere: any = {
deletedAt: null,
vipIds: { has: vipId },
};
if (startDate || endDate) {
eventsWhere.startTime = dateFilter;
}
const events = await this.prisma.scheduleEvent.findMany({
where: eventsWhere,
include: {
driver: true,
vehicle: true,
},
orderBy: { startTime: 'asc' },
});
// Combine and sort chronologically
const itineraryItems: any[] = [
...flights.map((f) => ({
type: 'FLIGHT',
time: f.scheduledDeparture || f.flightDate,
data: f,
})),
...events.map((e) => ({
type: 'EVENT',
time: e.startTime,
data: e,
})),
].sort((a, b) => new Date(a.time).getTime() - new Date(b.time).getTime());
return {
success: true,
data: {
vip,
itinerary: itineraryItems,
summary: {
totalFlights: flights.length,
totalEvents: events.length,
},
},
};
}
async getFlightsForVip(vipId: string): Promise<ToolResult> {
const flights = await this.prisma.flight.findMany({
where: { vipId },
orderBy: { flightDate: 'asc' },
});
return { success: true, data: flights };
}
async createFlight(input: Record<string, any>): Promise<ToolResult> {
const flight = await this.prisma.flight.create({
data: {
vipId: input.vipId,
flightNumber: input.flightNumber,
flightDate: new Date(input.flightDate),
departureAirport: input.departureAirport,
arrivalAirport: input.arrivalAirport,
scheduledDeparture: input.scheduledDeparture
? new Date(input.scheduledDeparture)
: null,
scheduledArrival: input.scheduledArrival ? new Date(input.scheduledArrival) : null,
segment: input.segment || 1,
},
include: { vip: true },
});
return { success: true, data: flight };
}
async updateFlight(input: Record<string, any>): Promise<ToolResult> {
const { flightId, ...updateData } = input;
const flight = await this.prisma.flight.update({
where: { id: flightId },
data: updateData,
include: { vip: true },
});
return { success: true, data: flight };
}
async deleteFlight(flightId: string): Promise<ToolResult> {
const flight = await this.prisma.flight.findUnique({
where: { id: flightId },
include: { vip: true },
});
if (!flight) {
return { success: false, error: 'Flight not found' };
}
await this.prisma.flight.delete({
where: { id: flightId },
});
return {
success: true,
data: { deleted: true, flight },
};
}
}

View File

@@ -1,6 +1,10 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { CopilotController } from './copilot.controller'; import { CopilotController } from './copilot.controller';
import { CopilotService } from './copilot.service'; import { CopilotService } from './copilot.service';
import { CopilotVipService } from './copilot-vip.service';
import { CopilotScheduleService } from './copilot-schedule.service';
import { CopilotFleetService } from './copilot-fleet.service';
import { CopilotReportsService } from './copilot-reports.service';
import { PrismaModule } from '../prisma/prisma.module'; import { PrismaModule } from '../prisma/prisma.module';
import { SignalModule } from '../signal/signal.module'; import { SignalModule } from '../signal/signal.module';
import { DriversModule } from '../drivers/drivers.module'; import { DriversModule } from '../drivers/drivers.module';
@@ -8,6 +12,12 @@ import { DriversModule } from '../drivers/drivers.module';
@Module({ @Module({
imports: [PrismaModule, SignalModule, DriversModule], imports: [PrismaModule, SignalModule, DriversModule],
controllers: [CopilotController], controllers: [CopilotController],
providers: [CopilotService], providers: [
CopilotService,
CopilotVipService,
CopilotScheduleService,
CopilotFleetService,
CopilotReportsService,
],
}) })
export class CopilotModule {} export class CopilotModule {}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,13 @@
import { createParamDecorator, ExecutionContext } from '@nestjs/common';
/**
* Parameter decorator that extracts the current driver from the request.
* Should be used in conjunction with @UseInterceptors(ResolveDriverInterceptor)
* to ensure the driver is pre-resolved and attached to the request.
*/
export const CurrentDriver = createParamDecorator(
(data: unknown, ctx: ExecutionContext) => {
const request = ctx.switchToHttp().getRequest();
return request.driver;
},
);

View File

@@ -0,0 +1 @@
export * from './current-driver.decorator';

View File

@@ -8,6 +8,7 @@ import {
Param, Param,
Query, Query,
UseGuards, UseGuards,
UseInterceptors,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { DriversService } from './drivers.service'; import { DriversService } from './drivers.service';
@@ -16,8 +17,12 @@ import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard'; import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator'; import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator'; import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { CurrentDriver } from './decorators';
import { ResolveDriverInterceptor } from './interceptors';
import { Role } from '@prisma/client'; import { Role } from '@prisma/client';
import { CreateDriverDto, UpdateDriverDto } from './dto'; import { CreateDriverDto, UpdateDriverDto } from './dto';
import { toDateString } from '../common/utils/date.utils';
import { ParseBooleanPipe } from '../common/pipes';
@Controller('drivers') @Controller('drivers')
@UseGuards(JwtAuthGuard, RolesGuard) @UseGuards(JwtAuthGuard, RolesGuard)
@@ -41,11 +46,8 @@ export class DriversController {
@Get('me') @Get('me')
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
async getMyDriverProfile(@CurrentUser() user: any) { @UseInterceptors(ResolveDriverInterceptor)
const driver = await this.driversService.findByUserId(user.id); getMyDriverProfile(@CurrentDriver() driver: any) {
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
return driver; return driver;
} }
@@ -55,22 +57,19 @@ export class DriversController {
*/ */
@Get('me/schedule/ics') @Get('me/schedule/ics')
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
@UseInterceptors(ResolveDriverInterceptor)
async getMyScheduleICS( async getMyScheduleICS(
@CurrentUser() user: any, @CurrentDriver() driver: any,
@Query('date') dateStr?: string, @Query('date') dateStr?: string,
@Query('fullSchedule') fullScheduleStr?: string, @Query('fullSchedule') fullScheduleStr?: string,
) { ) {
const driver = await this.driversService.findByUserId(user.id);
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
const date = dateStr ? new Date(dateStr) : new Date(); const date = dateStr ? new Date(dateStr) : new Date();
// Default to full schedule (true) unless explicitly set to false // Default to full schedule (true) unless explicitly set to false
const fullSchedule = fullScheduleStr !== 'false'; const fullSchedule = fullScheduleStr !== 'false';
const icsContent = await this.scheduleExportService.generateICS(driver.id, date, fullSchedule); const icsContent = await this.scheduleExportService.generateICS(driver.id, date, fullSchedule);
const filename = fullSchedule const filename = fullSchedule
? `full-schedule-${new Date().toISOString().split('T')[0]}.ics` ? `full-schedule-${toDateString(new Date())}.ics`
: `schedule-${date.toISOString().split('T')[0]}.ics`; : `schedule-${toDateString(date)}.ics`;
return { ics: icsContent, filename }; return { ics: icsContent, filename };
} }
@@ -80,22 +79,19 @@ export class DriversController {
*/ */
@Get('me/schedule/pdf') @Get('me/schedule/pdf')
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
@UseInterceptors(ResolveDriverInterceptor)
async getMySchedulePDF( async getMySchedulePDF(
@CurrentUser() user: any, @CurrentDriver() driver: any,
@Query('date') dateStr?: string, @Query('date') dateStr?: string,
@Query('fullSchedule') fullScheduleStr?: string, @Query('fullSchedule') fullScheduleStr?: string,
) { ) {
const driver = await this.driversService.findByUserId(user.id);
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
const date = dateStr ? new Date(dateStr) : new Date(); const date = dateStr ? new Date(dateStr) : new Date();
// Default to full schedule (true) unless explicitly set to false // Default to full schedule (true) unless explicitly set to false
const fullSchedule = fullScheduleStr !== 'false'; const fullSchedule = fullScheduleStr !== 'false';
const pdfBuffer = await this.scheduleExportService.generatePDF(driver.id, date, fullSchedule); const pdfBuffer = await this.scheduleExportService.generatePDF(driver.id, date, fullSchedule);
const filename = fullSchedule const filename = fullSchedule
? `full-schedule-${new Date().toISOString().split('T')[0]}.pdf` ? `full-schedule-${toDateString(new Date())}.pdf`
: `schedule-${date.toISOString().split('T')[0]}.pdf`; : `schedule-${toDateString(date)}.pdf`;
return { pdf: pdfBuffer.toString('base64'), filename }; return { pdf: pdfBuffer.toString('base64'), filename };
} }
@@ -105,14 +101,11 @@ export class DriversController {
*/ */
@Post('me/send-schedule') @Post('me/send-schedule')
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
@UseInterceptors(ResolveDriverInterceptor)
async sendMySchedule( async sendMySchedule(
@CurrentUser() user: any, @CurrentDriver() driver: any,
@Body() body: { date?: string; format?: 'ics' | 'pdf' | 'both'; fullSchedule?: boolean }, @Body() body: { date?: string; format?: 'ics' | 'pdf' | 'both'; fullSchedule?: boolean },
) { ) {
const driver = await this.driversService.findByUserId(user.id);
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
const date = body.date ? new Date(body.date) : new Date(); const date = body.date ? new Date(body.date) : new Date();
const format = body.format || 'both'; const format = body.format || 'both';
// Default to full schedule (true) unless explicitly set to false // Default to full schedule (true) unless explicitly set to false
@@ -122,11 +115,8 @@ export class DriversController {
@Patch('me') @Patch('me')
@Roles(Role.DRIVER) @Roles(Role.DRIVER)
async updateMyProfile(@CurrentUser() user: any, @Body() updateDriverDto: UpdateDriverDto) { @UseInterceptors(ResolveDriverInterceptor)
const driver = await this.driversService.findByUserId(user.id); updateMyProfile(@CurrentDriver() driver: any, @Body() updateDriverDto: UpdateDriverDto) {
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
return this.driversService.update(driver.id, updateDriverDto); return this.driversService.update(driver.id, updateDriverDto);
} }
@@ -219,9 +209,9 @@ export class DriversController {
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
remove( remove(
@Param('id') id: string, @Param('id') id: string,
@Query('hard') hard?: string, @Query('hard', ParseBooleanPipe) hard: boolean,
@CurrentUser() user?: any,
) { ) {
const isHardDelete = hard === 'true'; return this.driversService.remove(id, hard, user?.role);
return this.driversService.remove(id, isHardDelete);
} }
} }

View File

@@ -1,11 +1,20 @@
import { Injectable, NotFoundException, Logger } from '@nestjs/common'; import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { CreateDriverDto, UpdateDriverDto } from './dto'; import { CreateDriverDto, UpdateDriverDto } from './dto';
import { executeHardDelete } from '../common/utils';
@Injectable() @Injectable()
export class DriversService { export class DriversService {
private readonly logger = new Logger(DriversService.name); private readonly logger = new Logger(DriversService.name);
private readonly driverInclude = {
user: true,
events: {
include: { vehicle: true, driver: true },
orderBy: { startTime: 'asc' as const },
},
} as const;
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async create(createDriverDto: CreateDriverDto) { async create(createDriverDto: CreateDriverDto) {
@@ -19,30 +28,15 @@ export class DriversService {
async findAll() { async findAll() {
return this.prisma.driver.findMany({ return this.prisma.driver.findMany({
where: { deletedAt: null }, include: this.driverInclude,
include: {
user: true,
events: {
where: { deletedAt: null },
include: { vehicle: true, driver: true },
orderBy: { startTime: 'asc' },
},
},
orderBy: { name: 'asc' }, orderBy: { name: 'asc' },
}); });
} }
async findOne(id: string) { async findOne(id: string) {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id, deletedAt: null }, where: { id },
include: { include: this.driverInclude,
user: true,
events: {
where: { deletedAt: null },
include: { vehicle: true, driver: true },
orderBy: { startTime: 'asc' },
},
},
}); });
if (!driver) { if (!driver) {
@@ -54,15 +48,8 @@ export class DriversService {
async findByUserId(userId: string) { async findByUserId(userId: string) {
return this.prisma.driver.findFirst({ return this.prisma.driver.findFirst({
where: { userId, deletedAt: null }, where: { userId },
include: { include: this.driverInclude,
user: true,
events: {
where: { deletedAt: null },
include: { vehicle: true, driver: true },
orderBy: { startTime: 'asc' },
},
},
}); });
} }
@@ -78,20 +65,20 @@ export class DriversService {
}); });
} }
async remove(id: string, hardDelete = false) { async remove(id: string, hardDelete = false, userRole?: string) {
const driver = await this.findOne(id); return executeHardDelete({
id,
if (hardDelete) { hardDelete,
this.logger.log(`Hard deleting driver: ${driver.name}`); userRole,
return this.prisma.driver.delete({ findOne: (id) => this.findOne(id),
where: { id: driver.id }, performHardDelete: (id) => this.prisma.driver.delete({ where: { id } }),
}); performSoftDelete: (id) =>
} this.prisma.driver.update({
where: { id },
this.logger.log(`Soft deleting driver: ${driver.name}`);
return this.prisma.driver.update({
where: { id: driver.id },
data: { deletedAt: new Date() }, data: { deletedAt: new Date() },
}),
entityName: 'Driver',
logger: this.logger,
}); });
} }

View File

@@ -0,0 +1 @@
export * from './resolve-driver.interceptor';

View File

@@ -0,0 +1,40 @@
import {
Injectable,
NestInterceptor,
ExecutionContext,
CallHandler,
NotFoundException,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { DriversService } from '../drivers.service';
/**
* Interceptor that resolves the current driver from the authenticated user
* and attaches it to the request object for /me routes.
* This prevents multiple calls to findByUserId() in each route handler.
*/
@Injectable()
export class ResolveDriverInterceptor implements NestInterceptor {
constructor(private readonly driversService: DriversService) {}
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<any>> {
const request = context.switchToHttp().getRequest();
const user = request.user;
if (!user) {
throw new NotFoundException('User not authenticated');
}
// Resolve driver from user ID and attach to request
const driver = await this.driversService.findByUserId(user.id);
if (!driver) {
throw new NotFoundException('Driver profile not found for current user');
}
// Attach driver to request for use in route handlers
request.driver = driver;
return next.handle();
}
}

View File

@@ -3,6 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { SignalService } from '../signal/signal.service'; import { SignalService } from '../signal/signal.service';
import * as ics from 'ics'; import * as ics from 'ics';
import * as PDFDocument from 'pdfkit'; import * as PDFDocument from 'pdfkit';
import { toDateString, startOfDay } from '../common/utils/date.utils';
interface ScheduleEventWithDetails { interface ScheduleEventWithDetails {
id: string; id: string;
@@ -36,8 +37,7 @@ export class ScheduleExportService {
driverId: string, driverId: string,
date: Date, date: Date,
): Promise<ScheduleEventWithDetails[]> { ): Promise<ScheduleEventWithDetails[]> {
const startOfDay = new Date(date); const dayStart = startOfDay(date);
startOfDay.setHours(0, 0, 0, 0);
const endOfDay = new Date(date); const endOfDay = new Date(date);
endOfDay.setHours(23, 59, 59, 999); endOfDay.setHours(23, 59, 59, 999);
@@ -45,9 +45,8 @@ export class ScheduleExportService {
const events = await this.prisma.scheduleEvent.findMany({ const events = await this.prisma.scheduleEvent.findMany({
where: { where: {
driverId, driverId,
deletedAt: null,
startTime: { startTime: {
gte: startOfDay, gte: dayStart,
lte: endOfDay, lte: endOfDay,
}, },
status: { status: {
@@ -71,13 +70,11 @@ export class ScheduleExportService {
async getDriverFullSchedule( async getDriverFullSchedule(
driverId: string, driverId: string,
): Promise<ScheduleEventWithDetails[]> { ): Promise<ScheduleEventWithDetails[]> {
const now = new Date(); const now = startOfDay(new Date()); // Start of today
now.setHours(0, 0, 0, 0); // Start of today
const events = await this.prisma.scheduleEvent.findMany({ const events = await this.prisma.scheduleEvent.findMany({
where: { where: {
driverId, driverId,
deletedAt: null,
endTime: { endTime: {
gte: now, // Include events that haven't ended yet gte: now, // Include events that haven't ended yet
}, },
@@ -134,7 +131,7 @@ export class ScheduleExportService {
*/ */
async generateICS(driverId: string, date: Date, fullSchedule = false): Promise<string> { async generateICS(driverId: string, date: Date, fullSchedule = false): Promise<string> {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null }, where: { id: driverId },
}); });
if (!driver) { if (!driver) {
@@ -211,7 +208,7 @@ export class ScheduleExportService {
*/ */
async generatePDF(driverId: string, date: Date, fullSchedule = false): Promise<Buffer> { async generatePDF(driverId: string, date: Date, fullSchedule = false): Promise<Buffer> {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null }, where: { id: driverId },
}); });
if (!driver) { if (!driver) {
@@ -358,7 +355,7 @@ export class ScheduleExportService {
fullSchedule = false, fullSchedule = false,
): Promise<{ success: boolean; message: string }> { ): Promise<{ success: boolean; message: string }> {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null }, where: { id: driverId },
}); });
if (!driver) { if (!driver) {
@@ -411,8 +408,8 @@ export class ScheduleExportService {
const icsContent = await this.generateICS(driverId, date, fullSchedule); const icsContent = await this.generateICS(driverId, date, fullSchedule);
const icsBase64 = Buffer.from(icsContent).toString('base64'); const icsBase64 = Buffer.from(icsContent).toString('base64');
const filename = fullSchedule const filename = fullSchedule
? `full-schedule-${new Date().toISOString().split('T')[0]}.ics` ? `full-schedule-${toDateString(new Date())}.ics`
: `schedule-${date.toISOString().split('T')[0]}.ics`; : `schedule-${toDateString(date)}.ics`;
await this.signalService.sendMessageWithAttachment( await this.signalService.sendMessageWithAttachment(
fromNumber, fromNumber,
@@ -435,8 +432,8 @@ export class ScheduleExportService {
const pdfBuffer = await this.generatePDF(driverId, date, fullSchedule); const pdfBuffer = await this.generatePDF(driverId, date, fullSchedule);
const pdfBase64 = pdfBuffer.toString('base64'); const pdfBase64 = pdfBuffer.toString('base64');
const filename = fullSchedule const filename = fullSchedule
? `full-schedule-${new Date().toISOString().split('T')[0]}.pdf` ? `full-schedule-${toDateString(new Date())}.pdf`
: `schedule-${date.toISOString().split('T')[0]}.pdf`; : `schedule-${toDateString(date)}.pdf`;
await this.signalService.sendMessageWithAttachment( await this.signalService.sendMessageWithAttachment(
fromNumber, fromNumber,

View File

@@ -55,4 +55,8 @@ export class CreateEventDto {
@IsUUID() @IsUUID()
@IsOptional() @IsOptional()
vehicleId?: string; vehicleId?: string;
@IsUUID()
@IsOptional()
masterEventId?: string;
} }

View File

@@ -86,7 +86,6 @@ export class EventStatusService implements OnModuleInit, OnModuleDestroy {
startTime: { lte: twentyMinutesFromNow, gt: now }, startTime: { lte: twentyMinutesFromNow, gt: now },
reminder20MinSent: false, reminder20MinSent: false,
driverId: { not: null }, driverId: { not: null },
deletedAt: null,
}, },
include: { include: {
driver: true, driver: true,
@@ -110,7 +109,6 @@ export class EventStatusService implements OnModuleInit, OnModuleDestroy {
startTime: { lte: fiveMinutesFromNow, gt: now }, startTime: { lte: fiveMinutesFromNow, gt: now },
reminder5MinSent: false, reminder5MinSent: false,
driverId: { not: null }, driverId: { not: null },
deletedAt: null,
}, },
include: { include: {
driver: true, driver: true,
@@ -218,7 +216,6 @@ Reply:
where: { where: {
status: EventStatus.SCHEDULED, status: EventStatus.SCHEDULED,
startTime: { lte: now }, startTime: { lte: now },
deletedAt: null,
}, },
include: { include: {
driver: true, driver: true,
@@ -264,7 +261,6 @@ Reply:
where: { where: {
status: EventStatus.IN_PROGRESS, status: EventStatus.IN_PROGRESS,
endTime: { lte: gracePeriodAgo }, endTime: { lte: gracePeriodAgo },
deletedAt: null,
}, },
include: { include: {
driver: true, driver: true,
@@ -347,7 +343,6 @@ Reply with 1, 2, or 3`;
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { where: {
phone: { contains: driverPhone.replace(/\D/g, '').slice(-10) }, phone: { contains: driverPhone.replace(/\D/g, '').slice(-10) },
deletedAt: null,
}, },
}); });
@@ -360,7 +355,6 @@ Reply with 1, 2, or 3`;
where: { where: {
driverId: driver.id, driverId: driver.id,
status: EventStatus.IN_PROGRESS, status: EventStatus.IN_PROGRESS,
deletedAt: null,
}, },
include: { vehicle: true }, include: { vehicle: true },
}); });

View File

@@ -13,8 +13,10 @@ import { EventsService } from './events.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard'; import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator'; import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Role } from '@prisma/client'; import { Role } from '@prisma/client';
import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto'; import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto';
import { ParseBooleanPipe } from '../common/pipes';
@Controller('events') @Controller('events')
@UseGuards(JwtAuthGuard, RolesGuard) @UseGuards(JwtAuthGuard, RolesGuard)
@@ -58,9 +60,9 @@ export class EventsController {
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
remove( remove(
@Param('id') id: string, @Param('id') id: string,
@Query('hard') hard?: string, @Query('hard', ParseBooleanPipe) hard: boolean,
@CurrentUser() user?: any,
) { ) {
const isHardDelete = hard === 'true'; return this.eventsService.remove(id, hard, user?.role);
return this.eventsService.remove(id, isHardDelete);
} }
} }

View File

@@ -2,15 +2,28 @@ import {
Injectable, Injectable,
NotFoundException, NotFoundException,
BadRequestException, BadRequestException,
ForbiddenException,
Logger, Logger,
} from '@nestjs/common'; } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto'; import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto';
import { executeHardDelete } from '../common/utils';
@Injectable() @Injectable()
export class EventsService { export class EventsService {
private readonly logger = new Logger(EventsService.name); private readonly logger = new Logger(EventsService.name);
private readonly eventInclude = {
driver: true,
vehicle: true,
masterEvent: {
select: { id: true, title: true, type: true, startTime: true, endTime: true },
},
childEvents: {
select: { id: true, title: true, type: true },
},
} as const;
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async create(createEventDto: CreateEventDto) { async create(createEventDto: CreateEventDto) {
@@ -21,7 +34,6 @@ export class EventsService {
const vips = await this.prisma.vIP.findMany({ const vips = await this.prisma.vIP.findMany({
where: { where: {
id: { in: createEventDto.vipIds }, id: { in: createEventDto.vipIds },
deletedAt: null,
}, },
}); });
@@ -34,7 +46,7 @@ export class EventsService {
if (createEventDto.vehicleId && createEventDto.vipIds) { if (createEventDto.vehicleId && createEventDto.vipIds) {
await this.checkVehicleCapacity( await this.checkVehicleCapacity(
createEventDto.vehicleId, createEventDto.vehicleId,
createEventDto.vipIds.length, createEventDto.vipIds,
); );
} }
@@ -68,10 +80,7 @@ export class EventsService {
startTime: new Date(createEventDto.startTime), startTime: new Date(createEventDto.startTime),
endTime: new Date(createEventDto.endTime), endTime: new Date(createEventDto.endTime),
}, },
include: { include: this.eventInclude,
driver: true,
vehicle: true,
},
}); });
return this.enrichEventWithVips(event); return this.enrichEventWithVips(event);
@@ -79,24 +88,45 @@ export class EventsService {
async findAll() { async findAll() {
const events = await this.prisma.scheduleEvent.findMany({ const events = await this.prisma.scheduleEvent.findMany({
where: { deletedAt: null }, include: this.eventInclude,
include: {
driver: true,
vehicle: true,
},
orderBy: { startTime: 'asc' }, orderBy: { startTime: 'asc' },
}); });
return Promise.all(events.map((event) => this.enrichEventWithVips(event))); // Collect all unique VIP IDs from all events
const allVipIds = new Set<string>();
events.forEach((event) => {
event.vipIds?.forEach((vipId) => allVipIds.add(vipId));
});
// Fetch all VIPs in a single query (eliminates N+1)
const vipsMap = new Map();
if (allVipIds.size > 0) {
const vips = await this.prisma.vIP.findMany({
where: {
id: { in: Array.from(allVipIds) },
},
});
vips.forEach((vip) => vipsMap.set(vip.id, vip));
}
// Enrich each event with its VIPs from the map (no additional queries)
return events.map((event) => {
if (!event.vipIds || event.vipIds.length === 0) {
return { ...event, vips: [], vip: null };
}
const vips = event.vipIds
.map((vipId) => vipsMap.get(vipId))
.filter((vip) => vip !== undefined);
return { ...event, vips, vip: vips[0] || null };
});
} }
async findOne(id: string) { async findOne(id: string) {
const event = await this.prisma.scheduleEvent.findFirst({ const event = await this.prisma.scheduleEvent.findFirst({
where: { id, deletedAt: null }, where: { id },
include: { include: this.eventInclude,
driver: true,
vehicle: true,
},
}); });
if (!event) { if (!event) {
@@ -114,7 +144,6 @@ export class EventsService {
const vips = await this.prisma.vIP.findMany({ const vips = await this.prisma.vIP.findMany({
where: { where: {
id: { in: updateEventDto.vipIds }, id: { in: updateEventDto.vipIds },
deletedAt: null,
}, },
}); });
@@ -125,12 +154,10 @@ export class EventsService {
// Check vehicle capacity if vehicle or VIPs are being updated // Check vehicle capacity if vehicle or VIPs are being updated
const vehicleId = updateEventDto.vehicleId || event.vehicleId; const vehicleId = updateEventDto.vehicleId || event.vehicleId;
const vipCount = updateEventDto.vipIds const vipIds = updateEventDto.vipIds || event.vipIds;
? updateEventDto.vipIds.length
: event.vipIds.length;
if (vehicleId && vipCount > 0 && !updateEventDto.forceAssign) { if (vehicleId && vipIds.length > 0 && !updateEventDto.forceAssign) {
await this.checkVehicleCapacity(vehicleId, vipCount); await this.checkVehicleCapacity(vehicleId, vipIds);
} }
// Check for conflicts if driver or times are being updated (unless forceAssign is true) // Check for conflicts if driver or times are being updated (unless forceAssign is true)
@@ -187,10 +214,7 @@ export class EventsService {
const updatedEvent = await this.prisma.scheduleEvent.update({ const updatedEvent = await this.prisma.scheduleEvent.update({
where: { id: event.id }, where: { id: event.id },
data: updateData, data: updateData,
include: { include: this.eventInclude,
driver: true,
vehicle: true,
},
}); });
return this.enrichEventWithVips(updatedEvent); return this.enrichEventWithVips(updatedEvent);
@@ -206,52 +230,56 @@ export class EventsService {
const updatedEvent = await this.prisma.scheduleEvent.update({ const updatedEvent = await this.prisma.scheduleEvent.update({
where: { id: event.id }, where: { id: event.id },
data: { status: updateEventStatusDto.status }, data: { status: updateEventStatusDto.status },
include: { include: this.eventInclude,
driver: true,
vehicle: true,
},
}); });
return this.enrichEventWithVips(updatedEvent); return this.enrichEventWithVips(updatedEvent);
} }
async remove(id: string, hardDelete = false) { async remove(id: string, hardDelete = false, userRole?: string) {
const event = await this.findOne(id); return executeHardDelete({
id,
if (hardDelete) { hardDelete,
this.logger.log(`Hard deleting event: ${event.title}`); userRole,
return this.prisma.scheduleEvent.delete({ findOne: (id) => this.findOne(id),
where: { id: event.id }, performHardDelete: (id) =>
}); this.prisma.scheduleEvent.delete({ where: { id } }),
} performSoftDelete: (id) =>
this.prisma.scheduleEvent.update({
this.logger.log(`Soft deleting event: ${event.title}`); where: { id },
return this.prisma.scheduleEvent.update({
where: { id: event.id },
data: { deletedAt: new Date() }, data: { deletedAt: new Date() },
}),
entityName: 'Event',
logger: this.logger,
}); });
} }
/** /**
* Check vehicle capacity * Check vehicle capacity using sum of VIP party sizes
*/ */
private async checkVehicleCapacity(vehicleId: string, vipCount: number) { private async checkVehicleCapacity(vehicleId: string, vipIds: string[]) {
const vehicle = await this.prisma.vehicle.findFirst({ const vehicle = await this.prisma.vehicle.findFirst({
where: { id: vehicleId, deletedAt: null }, where: { id: vehicleId },
}); });
if (!vehicle) { if (!vehicle) {
throw new NotFoundException('Vehicle not found'); throw new NotFoundException('Vehicle not found');
} }
if (vipCount > vehicle.seatCapacity) { const vips = await this.prisma.vIP.findMany({
where: { id: { in: vipIds } },
select: { partySize: true },
});
const totalPeople = vips.reduce((sum, v) => sum + v.partySize, 0);
if (totalPeople > vehicle.seatCapacity) {
this.logger.warn( this.logger.warn(
`Vehicle capacity exceeded: ${vipCount} VIPs > ${vehicle.seatCapacity} seats`, `Vehicle capacity exceeded: ${totalPeople} people > ${vehicle.seatCapacity} seats`,
); );
throw new BadRequestException({ throw new BadRequestException({
message: `Vehicle capacity exceeded: ${vipCount} VIPs require more than ${vehicle.seatCapacity} available seats`, message: `Vehicle capacity exceeded: ${totalPeople} people require more than ${vehicle.seatCapacity} available seats`,
capacity: vehicle.seatCapacity, capacity: vehicle.seatCapacity,
requested: vipCount, requested: totalPeople,
exceeded: true, exceeded: true,
}); });
} }
@@ -269,7 +297,6 @@ export class EventsService {
return this.prisma.scheduleEvent.findMany({ return this.prisma.scheduleEvent.findMany({
where: { where: {
driverId, driverId,
deletedAt: null,
id: excludeEventId ? { not: excludeEventId } : undefined, id: excludeEventId ? { not: excludeEventId } : undefined,
OR: [ OR: [
{ {
@@ -310,7 +337,6 @@ export class EventsService {
const vips = await this.prisma.vIP.findMany({ const vips = await this.prisma.vIP.findMany({
where: { where: {
id: { in: event.vipIds }, id: { in: event.vipIds },
deletedAt: null,
}, },
}); });

View File

@@ -0,0 +1,466 @@
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { HttpService } from '@nestjs/axios';
import { ConfigService } from '@nestjs/config';
import { Cron } from '@nestjs/schedule';
import { PrismaService } from '../prisma/prisma.service';
import { firstValueFrom } from 'rxjs';
import { Flight } from '@prisma/client';
import { toDateString } from '../common/utils/date.utils';
// Tracking phases - determines polling priority
const PHASE = {
FAR_OUT: 'FAR_OUT', // >24h before departure - no auto-poll
PRE_DEPARTURE: 'PRE_DEPARTURE', // 6-24h before departure
DEPARTURE_WINDOW: 'DEPARTURE_WINDOW', // 0-6h before departure
ACTIVE: 'ACTIVE', // In flight
ARRIVAL_WINDOW: 'ARRIVAL_WINDOW', // Within 1h of ETA
LANDED: 'LANDED', // Flight has landed
TERMINAL: 'TERMINAL', // Cancelled/diverted/incident - terminal state
} as const;
// Priority scores for each phase (higher = more urgent)
const PHASE_PRIORITY: Record<string, number> = {
[PHASE.ARRIVAL_WINDOW]: 100,
[PHASE.ACTIVE]: 60,
[PHASE.DEPARTURE_WINDOW]: 40,
[PHASE.PRE_DEPARTURE]: 10,
[PHASE.FAR_OUT]: 0,
[PHASE.LANDED]: 0,
[PHASE.TERMINAL]: 0,
};
// Minimum minutes between polls per phase (to prevent wasting budget)
const MIN_POLL_INTERVAL: Record<string, number> = {
[PHASE.ARRIVAL_WINDOW]: 20,
[PHASE.ACTIVE]: 45,
[PHASE.DEPARTURE_WINDOW]: 60,
[PHASE.PRE_DEPARTURE]: 180,
[PHASE.FAR_OUT]: Infinity,
[PHASE.LANDED]: Infinity,
[PHASE.TERMINAL]: Infinity,
};
// Map AviationStack status to our tracking phase
const STATUS_TO_TERMINAL: string[] = ['cancelled', 'incident', 'diverted'];
@Injectable()
export class FlightTrackingService {
private readonly logger = new Logger(FlightTrackingService.name);
private readonly apiKey: string;
private readonly baseUrl = 'http://api.aviationstack.com/v1';
constructor(
private prisma: PrismaService,
private httpService: HttpService,
private configService: ConfigService,
) {
this.apiKey = this.configService.get('AVIATIONSTACK_API_KEY') || '';
if (this.apiKey) {
this.logger.log('AviationStack API key configured - flight tracking enabled');
} else {
this.logger.warn('AviationStack API key not configured - flight tracking disabled');
}
}
// ============================================
// Cron Job: Smart Flight Polling (every 5 min)
// ============================================
@Cron('*/5 * * * *')
async pollFlightsCron(): Promise<void> {
if (!this.apiKey) return;
try {
// 1. Check budget
const budget = await this.getOrCreateBudget();
const budgetPercent = (budget.requestsUsed / budget.requestLimit) * 100;
if (budgetPercent >= 95) {
this.logger.debug('Flight API budget exhausted (>=95%) - skipping auto-poll');
return;
}
// 2. Get all trackable flights (not in terminal states)
const flights = await this.prisma.flight.findMany({
where: {
autoTrackEnabled: true,
trackingPhase: {
notIn: [PHASE.LANDED, PHASE.TERMINAL, PHASE.FAR_OUT],
},
},
include: { vip: true },
});
if (flights.length === 0) return;
// 3. Recalculate phases and score each flight
const candidates: { flight: Flight; phase: string; priority: number }[] = [];
for (const flight of flights) {
const phase = this.calculateTrackingPhase(flight);
// Update phase in DB if changed
if (phase !== flight.trackingPhase) {
await this.prisma.flight.update({
where: { id: flight.id },
data: { trackingPhase: phase },
});
}
// Skip phases that shouldn't be polled
if (PHASE_PRIORITY[phase] === 0) continue;
// Budget conservation: if >80% used, only poll high-priority
if (budgetPercent > 80 && PHASE_PRIORITY[phase] < 60) continue;
// Check minimum polling interval
if (!this.shouldPoll(flight, phase)) continue;
candidates.push({
flight,
phase,
priority: PHASE_PRIORITY[phase],
});
}
if (candidates.length === 0) return;
// 4. Pick the highest-priority candidate
candidates.sort((a, b) => b.priority - a.priority);
const best = candidates[0];
this.logger.log(
`Auto-polling flight ${best.flight.flightNumber} (phase: ${best.phase}, priority: ${best.priority}, budget: ${budget.requestsUsed}/${budget.requestLimit})`,
);
// 5. Poll it
await this.callAviationStackAndUpdate(best.flight);
} catch (error) {
this.logger.error(`Flight polling cron error: ${error.message}`, error.stack);
}
}
// ============================================
// Manual Refresh (coordinator-triggered)
// ============================================
async refreshFlight(flightId: string) {
const flight = await this.prisma.flight.findUnique({
where: { id: flightId },
include: { vip: true },
});
if (!flight) {
throw new NotFoundException(`Flight ${flightId} not found`);
}
if (!this.apiKey) {
return {
message: 'Flight tracking API not configured',
flight,
};
}
const updated = await this.callAviationStackAndUpdate(flight);
return updated;
}
async refreshActiveFlights() {
if (!this.apiKey) {
return { refreshed: 0, skipped: 0, budgetRemaining: 0, message: 'API key not configured' };
}
const budget = await this.getOrCreateBudget();
const remaining = budget.requestLimit - budget.requestsUsed;
// Get active flights that would benefit from refresh
const flights = await this.prisma.flight.findMany({
where: {
trackingPhase: {
in: [PHASE.ACTIVE, PHASE.ARRIVAL_WINDOW, PHASE.DEPARTURE_WINDOW],
},
},
include: { vip: true },
orderBy: { scheduledDeparture: 'asc' },
});
let refreshed = 0;
let skipped = 0;
for (const flight of flights) {
if (refreshed >= remaining) {
skipped += flights.length - refreshed - skipped;
break;
}
try {
await this.callAviationStackAndUpdate(flight);
refreshed++;
} catch (error) {
this.logger.error(`Failed to refresh flight ${flight.flightNumber}: ${error.message}`);
skipped++;
}
}
const updatedBudget = await this.getOrCreateBudget();
return {
refreshed,
skipped,
budgetRemaining: updatedBudget.requestLimit - updatedBudget.requestsUsed,
};
}
// ============================================
// Budget Management
// ============================================
async getBudgetStatus() {
const budget = await this.getOrCreateBudget();
return {
used: budget.requestsUsed,
limit: budget.requestLimit,
remaining: budget.requestLimit - budget.requestsUsed,
month: budget.monthYear,
};
}
private async getOrCreateBudget() {
const monthYear = this.getCurrentMonthYear();
let budget = await this.prisma.flightApiBudget.findUnique({
where: { monthYear },
});
if (!budget) {
budget = await this.prisma.flightApiBudget.create({
data: { monthYear, requestLimit: 100 },
});
}
return budget;
}
private async incrementBudget() {
const monthYear = this.getCurrentMonthYear();
return this.prisma.flightApiBudget.upsert({
where: { monthYear },
update: {
requestsUsed: { increment: 1 },
lastRequestAt: new Date(),
},
create: {
monthYear,
requestsUsed: 1,
requestLimit: 100,
lastRequestAt: new Date(),
},
});
}
private getCurrentMonthYear(): string {
const now = new Date();
return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`;
}
// ============================================
// Phase Calculation
// ============================================
calculateTrackingPhase(flight: Flight): string {
const now = new Date();
const status = flight.status?.toLowerCase();
// Terminal states
if (status === 'landed' || flight.actualArrival) return PHASE.LANDED;
if (STATUS_TO_TERMINAL.includes(status || '')) return PHASE.TERMINAL;
// Active in flight
if (status === 'active') {
// Check if within arrival window
const eta = flight.estimatedArrival || flight.scheduledArrival;
if (eta) {
const minutesToArrival = (new Date(eta).getTime() - now.getTime()) / 60000;
if (minutesToArrival <= 60) return PHASE.ARRIVAL_WINDOW;
}
return PHASE.ACTIVE;
}
// Pre-departure phases based on scheduled departure
const departure = flight.estimatedDeparture || flight.scheduledDeparture;
if (!departure) return PHASE.FAR_OUT;
const hoursUntilDeparture = (new Date(departure).getTime() - now.getTime()) / 3600000;
if (hoursUntilDeparture <= 0) {
// Past scheduled departure but no "active" status from API
// Could be delayed at gate - treat as departure window
return PHASE.DEPARTURE_WINDOW;
}
if (hoursUntilDeparture <= 6) return PHASE.DEPARTURE_WINDOW;
if (hoursUntilDeparture <= 24) return PHASE.PRE_DEPARTURE;
return PHASE.FAR_OUT;
}
// ============================================
// Polling Decision
// ============================================
private shouldPoll(flight: Flight, phase: string): boolean {
const minInterval = MIN_POLL_INTERVAL[phase];
if (!isFinite(minInterval)) return false;
if (!flight.lastPolledAt) return true; // Never polled
const minutesSincePoll = (Date.now() - new Date(flight.lastPolledAt).getTime()) / 60000;
return minutesSincePoll >= minInterval;
}
// ============================================
// AviationStack API Integration
// ============================================
private async callAviationStackAndUpdate(flight: Flight & { vip?: any }): Promise<Flight> {
const flightDate = flight.flightDate
? toDateString(new Date(flight.flightDate))
: undefined;
try {
const params: any = {
access_key: this.apiKey,
flight_iata: flight.flightNumber,
};
if (flightDate) {
params.flight_date = flightDate;
}
const response = await firstValueFrom(
this.httpService.get(`${this.baseUrl}/flights`, {
params,
timeout: 15000,
}),
);
// Increment budget after successful call
await this.incrementBudget();
const data = response.data as any;
if (data?.error) {
this.logger.warn(`AviationStack API error for ${flight.flightNumber}: ${data.error.message || JSON.stringify(data.error)}`);
// Still update lastPolledAt so we don't spam on errors
return this.prisma.flight.update({
where: { id: flight.id },
data: { lastPolledAt: new Date(), pollCount: { increment: 1 } },
include: { vip: true },
});
}
if (data?.data && data.data.length > 0) {
const apiResult = data.data[0];
const updateData = this.parseAviationStackResponse(apiResult);
// Calculate new phase based on updated data
const tempFlight = { ...flight, ...updateData };
const newPhase = this.calculateTrackingPhase(tempFlight as Flight);
const updated = await this.prisma.flight.update({
where: { id: flight.id },
data: {
...updateData,
trackingPhase: newPhase,
lastPolledAt: new Date(),
pollCount: { increment: 1 },
lastApiResponse: apiResult,
},
include: { vip: true },
});
this.logger.log(
`Updated flight ${flight.flightNumber}: status=${updated.status}, phase=${newPhase}, delay=${updated.arrivalDelay || 0}min`,
);
return updated;
}
// Flight not found in API
this.logger.warn(`Flight ${flight.flightNumber} not found in AviationStack API`);
return this.prisma.flight.update({
where: { id: flight.id },
data: { lastPolledAt: new Date(), pollCount: { increment: 1 } },
include: { vip: true },
});
} catch (error) {
this.logger.error(`AviationStack API call failed for ${flight.flightNumber}: ${error.message}`);
// Still update lastPolledAt on error to prevent rapid retries
return this.prisma.flight.update({
where: { id: flight.id },
data: { lastPolledAt: new Date() },
include: { vip: true },
});
}
}
// ============================================
// Response Parser
// ============================================
private parseAviationStackResponse(apiData: any): Partial<Flight> {
const update: any = {};
// Flight status
if (apiData.flight_status) {
update.status = apiData.flight_status;
}
// Departure info
if (apiData.departure) {
const dep = apiData.departure;
if (dep.terminal) update.departureTerminal = dep.terminal;
if (dep.gate) update.departureGate = dep.gate;
if (dep.delay != null) update.departureDelay = dep.delay;
if (dep.scheduled) update.scheduledDeparture = new Date(dep.scheduled);
if (dep.estimated) update.estimatedDeparture = new Date(dep.estimated);
if (dep.actual) update.actualDeparture = new Date(dep.actual);
// Store departure airport name if we only had IATA code
if (dep.iata && !update.departureAirport) update.departureAirport = dep.iata;
}
// Arrival info
if (apiData.arrival) {
const arr = apiData.arrival;
if (arr.terminal) update.arrivalTerminal = arr.terminal;
if (arr.gate) update.arrivalGate = arr.gate;
if (arr.baggage) update.arrivalBaggage = arr.baggage;
if (arr.delay != null) update.arrivalDelay = arr.delay;
if (arr.scheduled) update.scheduledArrival = new Date(arr.scheduled);
if (arr.estimated) update.estimatedArrival = new Date(arr.estimated);
if (arr.actual) update.actualArrival = new Date(arr.actual);
if (arr.iata && !update.arrivalAirport) update.arrivalAirport = arr.iata;
}
// Airline info
if (apiData.airline) {
if (apiData.airline.name) update.airlineName = apiData.airline.name;
if (apiData.airline.iata) update.airlineIata = apiData.airline.iata;
}
// Aircraft info
if (apiData.aircraft?.iata) {
update.aircraftType = apiData.aircraft.iata;
}
// Live tracking data (may not be available on free tier)
if (apiData.live) {
const live = apiData.live;
if (live.latitude != null) update.liveLatitude = live.latitude;
if (live.longitude != null) update.liveLongitude = live.longitude;
if (live.altitude != null) update.liveAltitude = live.altitude;
if (live.speed_horizontal != null) update.liveSpeed = live.speed_horizontal;
if (live.direction != null) update.liveDirection = live.direction;
if (live.is_ground != null) update.liveIsGround = live.is_ground;
if (live.updated) update.liveUpdatedAt = new Date(live.updated);
}
return update;
}
}

View File

@@ -10,16 +10,21 @@ import {
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { FlightsService } from './flights.service'; import { FlightsService } from './flights.service';
import { FlightTrackingService } from './flight-tracking.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard'; import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator'; import { Roles } from '../auth/decorators/roles.decorator';
import { Role } from '@prisma/client'; import { Role } from '@prisma/client';
import { CreateFlightDto, UpdateFlightDto } from './dto'; import { CreateFlightDto, UpdateFlightDto } from './dto';
import { ParseBooleanPipe } from '../common/pipes';
@Controller('flights') @Controller('flights')
@UseGuards(JwtAuthGuard, RolesGuard) @UseGuards(JwtAuthGuard, RolesGuard)
export class FlightsController { export class FlightsController {
constructor(private readonly flightsService: FlightsService) {} constructor(
private readonly flightsService: FlightsService,
private readonly flightTrackingService: FlightTrackingService,
) {}
@Post() @Post()
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
@@ -33,6 +38,20 @@ export class FlightsController {
return this.flightsService.findAll(); return this.flightsService.findAll();
} }
// --- Tracking Endpoints (must come before :id param routes) ---
@Get('tracking/budget')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
getBudgetStatus() {
return this.flightTrackingService.getBudgetStatus();
}
@Post('refresh-active')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
refreshActiveFlights() {
return this.flightTrackingService.refreshActiveFlights();
}
@Get('status/:flightNumber') @Get('status/:flightNumber')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
getFlightStatus( getFlightStatus(
@@ -54,6 +73,12 @@ export class FlightsController {
return this.flightsService.findOne(id); return this.flightsService.findOne(id);
} }
@Post(':id/refresh')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
refreshFlight(@Param('id') id: string) {
return this.flightTrackingService.refreshFlight(id);
}
@Patch(':id') @Patch(':id')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
update(@Param('id') id: string, @Body() updateFlightDto: UpdateFlightDto) { update(@Param('id') id: string, @Body() updateFlightDto: UpdateFlightDto) {
@@ -64,9 +89,8 @@ export class FlightsController {
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
remove( remove(
@Param('id') id: string, @Param('id') id: string,
@Query('hard') hard?: string, @Query('hard', ParseBooleanPipe) hard: boolean,
) { ) {
const isHardDelete = hard === 'true'; return this.flightsService.remove(id, hard);
return this.flightsService.remove(id, isHardDelete);
} }
} }

View File

@@ -2,11 +2,12 @@ import { Module } from '@nestjs/common';
import { HttpModule } from '@nestjs/axios'; import { HttpModule } from '@nestjs/axios';
import { FlightsController } from './flights.controller'; import { FlightsController } from './flights.controller';
import { FlightsService } from './flights.service'; import { FlightsService } from './flights.service';
import { FlightTrackingService } from './flight-tracking.service';
@Module({ @Module({
imports: [HttpModule], imports: [HttpModule],
controllers: [FlightsController], controllers: [FlightsController],
providers: [FlightsService], providers: [FlightsService, FlightTrackingService],
exports: [FlightsService], exports: [FlightsService, FlightTrackingService],
}) })
export class FlightsModule {} export class FlightsModule {}

View File

@@ -4,6 +4,7 @@ import { ConfigService } from '@nestjs/config';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { CreateFlightDto, UpdateFlightDto } from './dto'; import { CreateFlightDto, UpdateFlightDto } from './dto';
import { firstValueFrom } from 'rxjs'; import { firstValueFrom } from 'rxjs';
import { convertOptionalDates } from '../common/utils/date.utils';
@Injectable() @Injectable()
export class FlightsService { export class FlightsService {
@@ -24,17 +25,16 @@ export class FlightsService {
`Creating flight: ${createFlightDto.flightNumber} for VIP ${createFlightDto.vipId}`, `Creating flight: ${createFlightDto.flightNumber} for VIP ${createFlightDto.vipId}`,
); );
return this.prisma.flight.create({ const data = convertOptionalDates(
data: { {
...createFlightDto, ...createFlightDto,
flightDate: new Date(createFlightDto.flightDate), flightDate: new Date(createFlightDto.flightDate),
scheduledDeparture: createFlightDto.scheduledDeparture
? new Date(createFlightDto.scheduledDeparture)
: undefined,
scheduledArrival: createFlightDto.scheduledArrival
? new Date(createFlightDto.scheduledArrival)
: undefined,
}, },
['scheduledDeparture', 'scheduledArrival'],
);
return this.prisma.flight.create({
data,
include: { vip: true }, include: { vip: true },
}); });
} }
@@ -71,24 +71,13 @@ export class FlightsService {
this.logger.log(`Updating flight ${id}: ${flight.flightNumber}`); this.logger.log(`Updating flight ${id}: ${flight.flightNumber}`);
const updateData: any = { ...updateFlightDto }; const updateData = convertOptionalDates(updateFlightDto, [
const dto = updateFlightDto as any; // Type assertion to work around PartialType 'flightDate',
'scheduledDeparture',
if (dto.flightDate) { 'scheduledArrival',
updateData.flightDate = new Date(dto.flightDate); 'actualDeparture',
} 'actualArrival',
if (dto.scheduledDeparture) { ]);
updateData.scheduledDeparture = new Date(dto.scheduledDeparture);
}
if (dto.scheduledArrival) {
updateData.scheduledArrival = new Date(dto.scheduledArrival);
}
if (dto.actualDeparture) {
updateData.actualDeparture = new Date(dto.actualDeparture);
}
if (dto.actualArrival) {
updateData.actualArrival = new Date(dto.actualArrival);
}
return this.prisma.flight.update({ return this.prisma.flight.update({
where: { id: flight.id }, where: { id: flight.id },

View File

@@ -33,6 +33,7 @@ export class DriverStatsDto {
averageSpeedMph: number; averageSpeedMph: number;
totalTrips: number; totalTrips: number;
totalDrivingMinutes: number; totalDrivingMinutes: number;
distanceMethod?: string; // 'osrm' or 'haversine'
}; };
recentLocations: LocationDataDto[]; recentLocations: LocationDataDto[];
} }

View File

@@ -78,6 +78,15 @@ export class GpsController {
return this.gpsService.getEnrolledDevices(); return this.gpsService.getEnrolledDevices();
} }
/**
* Get QR code info for an enrolled device
*/
@Get('devices/:driverId/qr')
@Roles(Role.ADMINISTRATOR)
async getDeviceQr(@Param('driverId') driverId: string) {
return this.gpsService.getDeviceQrInfo(driverId);
}
/** /**
* Enroll a driver for GPS tracking * Enroll a driver for GPS tracking
*/ */
@@ -100,7 +109,7 @@ export class GpsController {
} }
/** /**
* Get all active driver locations (Admin map view) * Get all active driver locations (used by CommandCenter)
*/ */
@Get('locations') @Get('locations')
@Roles(Role.ADMINISTRATOR) @Roles(Role.ADMINISTRATOR)
@@ -108,34 +117,6 @@ export class GpsController {
return this.gpsService.getActiveDriverLocations(); return this.gpsService.getActiveDriverLocations();
} }
/**
* Get a specific driver's location
*/
@Get('locations/:driverId')
@Roles(Role.ADMINISTRATOR)
async getDriverLocation(@Param('driverId') driverId: string) {
const location = await this.gpsService.getDriverLocation(driverId);
if (!location) {
throw new NotFoundException('Driver not found or not enrolled for GPS tracking');
}
return location;
}
/**
* Get a driver's stats (Admin viewing any driver)
*/
@Get('stats/:driverId')
@Roles(Role.ADMINISTRATOR)
async getDriverStats(
@Param('driverId') driverId: string,
@Query('from') fromStr?: string,
@Query('to') toStr?: string,
) {
const from = fromStr ? new Date(fromStr) : undefined;
const to = toStr ? new Date(toStr) : undefined;
return this.gpsService.getDriverStats(driverId, from, to);
}
// ============================================ // ============================================
// Traccar Admin Access // Traccar Admin Access
// ============================================ // ============================================

View File

@@ -196,14 +196,18 @@ export class GpsService implements OnModuleInit {
const settings = await this.getSettings(); const settings = await this.getSettings();
// Build QR code URL for Traccar Client app // Build QR code URL for Traccar Client app
// Format: https://server:5055?id=DEVICE_ID&interval=SECONDS
// The Traccar Client app parses this as: server URL (origin) + query params (id, interval, etc.)
const devicePort = this.configService.get<number>('TRACCAR_DEVICE_PORT') || 5055; const devicePort = this.configService.get<number>('TRACCAR_DEVICE_PORT') || 5055;
const traccarPublicUrl = this.traccarClient.getTraccarUrl(); const traccarPublicUrl = this.traccarClient.getTraccarUrl();
const qrUrl = new URL(traccarPublicUrl); const qrUrl = new URL(traccarPublicUrl);
qrUrl.port = String(devicePort); qrUrl.port = String(devicePort);
qrUrl.searchParams.set('id', actualDeviceId); qrUrl.searchParams.set('id', actualDeviceId);
qrUrl.searchParams.set('interval', String(settings.updateIntervalSeconds)); qrUrl.searchParams.set('interval', String(settings.updateIntervalSeconds));
qrUrl.searchParams.set('accuracy', 'highest');
qrUrl.searchParams.set('distance', '0');
qrUrl.searchParams.set('angle', '30');
qrUrl.searchParams.set('heartbeat', '300');
qrUrl.searchParams.set('stop_detection', 'false');
qrUrl.searchParams.set('buffer', 'true');
const qrCodeUrl = qrUrl.toString(); const qrCodeUrl = qrUrl.toString();
this.logger.log(`QR code URL for driver: ${qrCodeUrl}`); this.logger.log(`QR code URL for driver: ${qrCodeUrl}`);
@@ -215,15 +219,21 @@ GPS Tracking Setup Instructions for ${driver.name}:
- iOS: https://apps.apple.com/app/traccar-client/id843156974 - iOS: https://apps.apple.com/app/traccar-client/id843156974
- Android: https://play.google.com/store/apps/details?id=org.traccar.client - Android: https://play.google.com/store/apps/details?id=org.traccar.client
2. Open the app and configure: 2. Open the app and scan the QR code (or configure manually):
- Device identifier: ${actualDeviceId} - Device identifier: ${actualDeviceId}
- Server URL: ${serverUrl} - Server URL: ${serverUrl}
- Location accuracy: Highest
- Frequency: ${settings.updateIntervalSeconds} seconds - Frequency: ${settings.updateIntervalSeconds} seconds
- Location accuracy: High - Distance: 0
- Angle: 30
3. Tap "Service Status" to start tracking. 3. IMPORTANT iPhone Settings:
- Settings > Privacy > Location Services > Traccar Client > "Always"
- Settings > General > Background App Refresh > ON for Traccar Client
- Do NOT swipe the app away from the app switcher
- Low Power Mode should be OFF while driving
Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}:00 - ${settings.shiftEndHour}:00). 4. Tap "Service Status" to start tracking.
`.trim(); `.trim();
let signalMessageSent = false; let signalMessageSent = false;
@@ -248,7 +258,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
return { return {
success: true, success: true,
deviceIdentifier: actualDeviceId, // Return what Traccar actually stored deviceIdentifier: actualDeviceId,
serverUrl, serverUrl,
qrCodeUrl, qrCodeUrl,
instructions, instructions,
@@ -256,6 +266,50 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
}; };
} }
/**
* Get QR code info for an already-enrolled device
*/
async getDeviceQrInfo(driverId: string): Promise<{
driverName: string;
deviceIdentifier: string;
serverUrl: string;
qrCodeUrl: string;
updateIntervalSeconds: number;
}> {
const device = await this.prisma.gpsDevice.findUnique({
where: { driverId },
include: { driver: { select: { id: true, name: true } } },
});
if (!device) {
throw new NotFoundException('Driver is not enrolled for GPS tracking');
}
const settings = await this.getSettings();
const serverUrl = this.traccarClient.getDeviceServerUrl();
const devicePort = this.configService.get<number>('TRACCAR_DEVICE_PORT') || 5055;
const traccarPublicUrl = this.traccarClient.getTraccarUrl();
const qrUrl = new URL(traccarPublicUrl);
qrUrl.port = String(devicePort);
qrUrl.searchParams.set('id', device.deviceIdentifier);
qrUrl.searchParams.set('interval', String(settings.updateIntervalSeconds));
qrUrl.searchParams.set('accuracy', 'highest');
qrUrl.searchParams.set('distance', '0');
qrUrl.searchParams.set('angle', '30');
qrUrl.searchParams.set('heartbeat', '300');
qrUrl.searchParams.set('stop_detection', 'false');
qrUrl.searchParams.set('buffer', 'true');
return {
driverName: device.driver.name,
deviceIdentifier: device.deviceIdentifier,
serverUrl,
qrCodeUrl: qrUrl.toString(),
updateIntervalSeconds: settings.updateIntervalSeconds,
};
}
/** /**
* Unenroll a driver from GPS tracking * Unenroll a driver from GPS tracking
*/ */
@@ -331,15 +385,12 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
} }
/** /**
* Get all active driver locations (Admin only) * Get all active driver locations (used by CommandCenter + GPS page)
*/ */
async getActiveDriverLocations(): Promise<DriverLocationDto[]> { async getActiveDriverLocations(): Promise<DriverLocationDto[]> {
const devices = await this.prisma.gpsDevice.findMany({ const devices = await this.prisma.gpsDevice.findMany({
where: { where: {
isActive: true, isActive: true,
driver: {
deletedAt: null,
},
}, },
include: { include: {
driver: { driver: {
@@ -387,7 +438,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
} }
/** /**
* Get a specific driver's location * Get a specific driver's location (used by driver self-service)
*/ */
async getDriverLocation(driverId: string): Promise<DriverLocationDto | null> { async getDriverLocation(driverId: string): Promise<DriverLocationDto | null> {
const device = await this.prisma.gpsDevice.findUnique({ const device = await this.prisma.gpsDevice.findUnique({
@@ -437,7 +488,98 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
} }
/** /**
* Get driver's own stats (for driver self-view) * Calculate distance between two GPS coordinates using Haversine formula
* Returns distance in miles
*/
private calculateHaversineDistance(
lat1: number,
lon1: number,
lat2: number,
lon2: number,
): number {
const R = 3958.8; // Earth's radius in miles
const dLat = this.toRadians(lat2 - lat1);
const dLon = this.toRadians(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(this.toRadians(lat1)) *
Math.cos(this.toRadians(lat2)) *
Math.sin(dLon / 2) *
Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
private toRadians(degrees: number): number {
return degrees * (Math.PI / 180);
}
/**
* Calculate total distance from position history
*/
private async calculateDistanceFromHistory(
deviceId: string,
from: Date,
to: Date,
): Promise<number> {
const positions = await this.prisma.gpsLocationHistory.findMany({
where: {
deviceId,
timestamp: {
gte: from,
lte: to,
},
},
orderBy: { timestamp: 'asc' },
select: {
latitude: true,
longitude: true,
timestamp: true,
speed: true,
accuracy: true,
},
});
if (positions.length < 2) {
return 0;
}
let totalMiles = 0;
for (let i = 1; i < positions.length; i++) {
const prev = positions[i - 1];
const curr = positions[i];
const timeDiffMs = curr.timestamp.getTime() - prev.timestamp.getTime();
const timeDiffMinutes = timeDiffMs / 60000;
// Skip if gap is too large (more than 10 minutes)
if (timeDiffMinutes > 10) continue;
const distance = this.calculateHaversineDistance(
prev.latitude,
prev.longitude,
curr.latitude,
curr.longitude,
);
// Sanity check: skip unrealistic distances (> 100 mph equivalent)
const maxPossibleDistance = (timeDiffMinutes / 60) * 100;
if (distance > maxPossibleDistance) continue;
// Filter out GPS jitter (movements < 0.01 miles / ~50 feet)
if (distance < 0.01) continue;
totalMiles += distance;
}
return totalMiles;
}
/**
* Get driver stats (used by driver self-service via me/stats)
*/ */
async getDriverStats( async getDriverStats(
driverId: string, driverId: string,
@@ -464,58 +606,54 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
const to = toDate || new Date(); const to = toDate || new Date();
const from = fromDate || new Date(to.getTime() - 7 * 24 * 60 * 60 * 1000); const from = fromDate || new Date(to.getTime() - 7 * 24 * 60 * 60 * 1000);
// Get summary from Traccar const totalMiles = await this.calculateDistanceFromHistory(device.id, from, to);
let totalMiles = 0;
// Get all positions for speed/time analysis
const allPositions = await this.prisma.gpsLocationHistory.findMany({
where: {
deviceId: device.id,
timestamp: {
gte: from,
lte: to,
},
},
orderBy: { timestamp: 'asc' },
});
let topSpeedMph = 0; let topSpeedMph = 0;
let topSpeedTimestamp: Date | null = null; let topSpeedTimestamp: Date | null = null;
let totalTrips = 0;
let totalDrivingMinutes = 0; let totalDrivingMinutes = 0;
let currentTripStart: Date | null = null;
let totalTrips = 0;
try { for (const pos of allPositions) {
const summary = await this.traccarClient.getSummaryReport( const speedMph = pos.speed || 0;
device.traccarDeviceId,
from,
to,
);
if (summary.length > 0) { if (speedMph > topSpeedMph) {
const report = summary[0]; topSpeedMph = speedMph;
// Distance is in meters, convert to miles topSpeedTimestamp = pos.timestamp;
totalMiles = (report.distance || 0) / 1609.344;
topSpeedMph = this.traccarClient.knotsToMph(report.maxSpeed || 0);
// Engine hours in milliseconds, convert to minutes
totalDrivingMinutes = Math.round((report.engineHours || 0) / 60000);
} }
// Get trips for additional stats if (speedMph > 5) {
const trips = await this.traccarClient.getTripReport( if (!currentTripStart) {
device.traccarDeviceId, currentTripStart = pos.timestamp;
from, totalTrips++;
to, }
); } else if (currentTripStart) {
totalTrips = trips.length; const tripDurationMs = pos.timestamp.getTime() - currentTripStart.getTime();
totalDrivingMinutes += tripDurationMs / 60000;
// Find top speed timestamp from positions currentTripStart = null;
const positions = await this.traccarClient.getPositionHistory(
device.traccarDeviceId,
from,
to,
);
let maxSpeed = 0;
for (const pos of positions) {
const speedMph = this.traccarClient.knotsToMph(pos.speed || 0);
if (speedMph > maxSpeed) {
maxSpeed = speedMph;
topSpeedTimestamp = new Date(pos.deviceTime);
} }
} }
topSpeedMph = maxSpeed;
} catch (error) { // Close last trip if still driving
this.logger.warn(`Failed to fetch stats from Traccar: ${error}`); if (currentTripStart && allPositions.length > 0) {
const lastPos = allPositions[allPositions.length - 1];
const tripDurationMs = lastPos.timestamp.getTime() - currentTripStart.getTime();
totalDrivingMinutes += tripDurationMs / 60000;
} }
// Get recent locations from our database // Get recent locations for display (last 100)
const recentLocations = await this.prisma.gpsLocationHistory.findMany({ const recentLocations = await this.prisma.gpsLocationHistory.findMany({
where: { where: {
deviceId: device.id, deviceId: device.id,
@@ -528,6 +666,11 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
take: 100, take: 100,
}); });
const averageSpeedMph =
totalDrivingMinutes > 0
? totalMiles / (totalDrivingMinutes / 60)
: 0;
return { return {
driverId, driverId,
driverName: device.driver.name, driverName: device.driver.name,
@@ -539,11 +682,9 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
totalMiles: Math.round(totalMiles * 10) / 10, totalMiles: Math.round(totalMiles * 10) / 10,
topSpeedMph: Math.round(topSpeedMph), topSpeedMph: Math.round(topSpeedMph),
topSpeedTimestamp, topSpeedTimestamp,
averageSpeedMph: totalDrivingMinutes > 0 averageSpeedMph: Math.round(averageSpeedMph * 10) / 10,
? Math.round((totalMiles / (totalDrivingMinutes / 60)) * 10) / 10
: 0,
totalTrips, totalTrips,
totalDrivingMinutes, totalDrivingMinutes: Math.round(totalDrivingMinutes),
}, },
recentLocations: recentLocations.map((loc) => ({ recentLocations: recentLocations.map((loc) => ({
latitude: loc.latitude, latitude: loc.latitude,
@@ -562,7 +703,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
* Sync positions from Traccar to our database (for history/stats) * Sync positions from Traccar to our database (for history/stats)
* Called periodically via cron job * Called periodically via cron job
*/ */
@Cron(CronExpression.EVERY_MINUTE) @Cron(CronExpression.EVERY_30_SECONDS)
async syncPositions(): Promise<void> { async syncPositions(): Promise<void> {
const devices = await this.prisma.gpsDevice.findMany({ const devices = await this.prisma.gpsDevice.findMany({
where: { where: {
@@ -570,41 +711,67 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
}, },
}); });
if (devices.length === 0) return; if (devices.length === 0) {
this.logger.debug('[GPS Sync] No active devices to sync');
return;
}
try { const now = new Date();
const positions = await this.traccarClient.getAllPositions(); this.logger.log(`[GPS Sync] Starting sync for ${devices.length} active devices`);
for (const device of devices) { for (const device of devices) {
const position = positions.find((p) => p.deviceId === device.traccarDeviceId); try {
if (!position) continue; const since = device.lastActive
? new Date(device.lastActive.getTime() - 30000)
: new Date(now.getTime() - 120000);
// Update last active timestamp const positions = await this.traccarClient.getPositionHistory(
device.traccarDeviceId,
since,
now,
);
this.logger.log(`[GPS Sync] Device ${device.traccarDeviceId}: Retrieved ${positions.length} positions from Traccar`);
if (positions.length === 0) continue;
const insertResult = await this.prisma.gpsLocationHistory.createMany({
data: positions.map((p) => ({
deviceId: device.id,
latitude: p.latitude,
longitude: p.longitude,
altitude: p.altitude || null,
speed: this.traccarClient.knotsToMph(p.speed || 0),
course: p.course || null,
accuracy: p.accuracy || null,
battery: p.attributes?.batteryLevel || null,
timestamp: new Date(p.deviceTime),
})),
skipDuplicates: true,
});
const inserted = insertResult.count;
const skipped = positions.length - inserted;
this.logger.log(
`[GPS Sync] Device ${device.traccarDeviceId}: ` +
`Inserted ${inserted} new positions, skipped ${skipped} duplicates`
);
const latestPosition = positions.reduce((latest, p) =>
new Date(p.deviceTime) > new Date(latest.deviceTime) ? p : latest
);
await this.prisma.gpsDevice.update({ await this.prisma.gpsDevice.update({
where: { id: device.id }, where: { id: device.id },
data: { lastActive: new Date(position.deviceTime) }, data: { lastActive: new Date(latestPosition.deviceTime) },
}); });
// Store in history
await this.prisma.gpsLocationHistory.create({
data: {
deviceId: device.id,
latitude: position.latitude,
longitude: position.longitude,
altitude: position.altitude || null,
speed: this.traccarClient.knotsToMph(position.speed || 0),
course: position.course || null,
accuracy: position.accuracy || null,
battery: position.attributes?.batteryLevel || null,
timestamp: new Date(position.deviceTime),
},
});
}
} catch (error) { } catch (error) {
this.logger.error(`Failed to sync positions: ${error}`); this.logger.error(`[GPS Sync] Failed to sync positions for device ${device.traccarDeviceId}: ${error}`);
} }
} }
this.logger.log('[GPS Sync] Sync completed');
}
/** /**
* Clean up old location history (runs daily at 2 AM) * Clean up old location history (runs daily at 2 AM)
*/ */
@@ -629,11 +796,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
// Traccar User Sync (VIP Admin -> Traccar Admin) // Traccar User Sync (VIP Admin -> Traccar Admin)
// ============================================ // ============================================
/**
* Generate a secure password for Traccar user
*/
private generateTraccarPassword(userId: string): string { private generateTraccarPassword(userId: string): string {
// Generate deterministic but secure password based on user ID + secret
const secret = process.env.JWT_SECRET || 'vip-coordinator-traccar-sync'; const secret = process.env.JWT_SECRET || 'vip-coordinator-traccar-sync';
return crypto return crypto
.createHmac('sha256', secret) .createHmac('sha256', secret)
@@ -642,11 +805,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
.substring(0, 24); .substring(0, 24);
} }
/**
* Generate a secure token for Traccar auto-login
*/
private generateTraccarToken(userId: string): string { private generateTraccarToken(userId: string): string {
// Generate deterministic token for auto-login
const secret = process.env.JWT_SECRET || 'vip-coordinator-traccar-token'; const secret = process.env.JWT_SECRET || 'vip-coordinator-traccar-token';
return crypto return crypto
.createHmac('sha256', secret + '-token') .createHmac('sha256', secret + '-token')
@@ -655,9 +814,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
.substring(0, 32); .substring(0, 32);
} }
/**
* Sync a VIP user to Traccar
*/
async syncUserToTraccar(user: User): Promise<boolean> { async syncUserToTraccar(user: User): Promise<boolean> {
if (!user.email) return false; if (!user.email) return false;
@@ -671,7 +827,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
user.name || user.email, user.name || user.email,
password, password,
isAdmin, isAdmin,
token, // Include token for auto-login token,
); );
this.logger.log(`Synced user ${user.email} to Traccar (admin: ${isAdmin})`); this.logger.log(`Synced user ${user.email} to Traccar (admin: ${isAdmin})`);
@@ -682,15 +838,11 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
} }
} }
/**
* Sync all VIP admins to Traccar
*/
async syncAllAdminsToTraccar(): Promise<{ synced: number; failed: number }> { async syncAllAdminsToTraccar(): Promise<{ synced: number; failed: number }> {
const admins = await this.prisma.user.findMany({ const admins = await this.prisma.user.findMany({
where: { where: {
role: 'ADMINISTRATOR', role: 'ADMINISTRATOR',
isApproved: true, isApproved: true,
deletedAt: null,
}, },
}); });
@@ -707,9 +859,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
return { synced, failed }; return { synced, failed };
} }
/**
* Get auto-login URL for Traccar (for admin users)
*/
async getTraccarAutoLoginUrl(user: User): Promise<{ async getTraccarAutoLoginUrl(user: User): Promise<{
url: string; url: string;
directAccess: boolean; directAccess: boolean;
@@ -718,30 +867,22 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
throw new BadRequestException('Only administrators can access Traccar admin'); throw new BadRequestException('Only administrators can access Traccar admin');
} }
// Ensure user is synced to Traccar (this also sets up their token)
await this.syncUserToTraccar(user); await this.syncUserToTraccar(user);
// Get the token for auto-login
const token = this.generateTraccarToken(user.id); const token = this.generateTraccarToken(user.id);
const baseUrl = this.traccarClient.getTraccarUrl(); const baseUrl = this.traccarClient.getTraccarUrl();
// Return URL with token parameter for auto-login
// Traccar supports ?token=xxx for direct authentication
return { return {
url: `${baseUrl}?token=${token}`, url: `${baseUrl}?token=${token}`,
directAccess: true, directAccess: true,
}; };
} }
/**
* Get Traccar session cookie for a user (for proxy/iframe auth)
*/
async getTraccarSessionForUser(user: User): Promise<string | null> { async getTraccarSessionForUser(user: User): Promise<string | null> {
if (user.role !== 'ADMINISTRATOR') { if (user.role !== 'ADMINISTRATOR') {
return null; return null;
} }
// Ensure user is synced
await this.syncUserToTraccar(user); await this.syncUserToTraccar(user);
const password = this.generateTraccarPassword(user.id); const password = this.generateTraccarPassword(user.id);
@@ -750,9 +891,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
return session?.cookie || null; return session?.cookie || null;
} }
/**
* Check if Traccar needs initial setup
*/
async checkTraccarSetup(): Promise<{ async checkTraccarSetup(): Promise<{
needsSetup: boolean; needsSetup: boolean;
isAvailable: boolean; isAvailable: boolean;
@@ -766,11 +904,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
return { needsSetup, isAvailable }; return { needsSetup, isAvailable };
} }
/**
* Perform initial Traccar setup
*/
async performTraccarSetup(adminEmail: string): Promise<boolean> { async performTraccarSetup(adminEmail: string): Promise<boolean> {
// Generate a secure password for the service account
const servicePassword = crypto.randomBytes(16).toString('hex'); const servicePassword = crypto.randomBytes(16).toString('hex');
const success = await this.traccarClient.performInitialSetup( const success = await this.traccarClient.performInitialSetup(
@@ -779,7 +913,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
); );
if (success) { if (success) {
// Save the service account credentials to settings
await this.updateSettings({ await this.updateSettings({
traccarAdminUser: adminEmail, traccarAdminUser: adminEmail,
traccarAdminPassword: servicePassword, traccarAdminPassword: servicePassword,

View File

@@ -53,8 +53,8 @@ export class TraccarClientService implements OnModuleInit {
private client: AxiosInstance; private client: AxiosInstance;
private readonly baseUrl: string; private readonly baseUrl: string;
private sessionCookie: string | null = null; private sessionCookie: string | null = null;
private adminUser: string = 'admin'; private adminUser: string = '';
private adminPassword: string = 'admin'; private adminPassword: string = '';
constructor(private configService: ConfigService) { constructor(private configService: ConfigService) {
this.baseUrl = this.configService.get<string>('TRACCAR_API_URL') || 'http://localhost:8082'; this.baseUrl = this.configService.get<string>('TRACCAR_API_URL') || 'http://localhost:8082';
@@ -86,6 +86,11 @@ export class TraccarClientService implements OnModuleInit {
* Authenticate with Traccar and get session cookie * Authenticate with Traccar and get session cookie
*/ */
async authenticate(): Promise<boolean> { async authenticate(): Promise<boolean> {
if (!this.adminUser || !this.adminPassword) {
this.logger.warn('Traccar credentials not configured - skipping authentication');
return false;
}
try { try {
const response = await this.client.post( const response = await this.client.post(
'/api/session', '/api/session',
@@ -316,7 +321,7 @@ export class TraccarClientService implements OnModuleInit {
deviceId: number, deviceId: number,
from: Date, from: Date,
to: Date, to: Date,
): Promise<any[]> { ): Promise<TraccarTrip[]> {
const fromStr = from.toISOString(); const fromStr = from.toISOString();
const toStr = to.toISOString(); const toStr = to.toISOString();
return this.request('get', `/api/reports/trips?deviceId=${deviceId}&from=${fromStr}&to=${toStr}`); return this.request('get', `/api/reports/trips?deviceId=${deviceId}&from=${fromStr}&to=${toStr}`);
@@ -562,3 +567,27 @@ export interface TraccarUser {
token: string | null; token: string | null;
attributes: Record<string, any>; attributes: Record<string, any>;
} }
export interface TraccarTrip {
deviceId: number;
deviceName: string;
distance: number; // meters
averageSpeed: number; // knots
maxSpeed: number; // knots
spentFuel: number;
startOdometer: number;
endOdometer: number;
startTime: string;
endTime: string;
startPositionId: number;
endPositionId: number;
startLat: number;
startLon: number;
endLat: number;
endLon: number;
startAddress: string | null;
endAddress: string | null;
duration: number; // milliseconds
driverUniqueId: string | null;
driverName: string | null;
}

View File

@@ -1,6 +1,7 @@
import { NestFactory } from '@nestjs/core'; import { NestFactory } from '@nestjs/core';
import { ValidationPipe, Logger } from '@nestjs/common'; import { ValidationPipe, Logger } from '@nestjs/common';
import { json, urlencoded } from 'express'; import { json, urlencoded } from 'express';
import helmet from 'helmet';
import { AppModule } from './app.module'; import { AppModule } from './app.module';
import { AllExceptionsFilter, HttpExceptionFilter } from './common/filters'; import { AllExceptionsFilter, HttpExceptionFilter } from './common/filters';
@@ -9,6 +10,9 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule); const app = await NestFactory.create(AppModule);
// Security headers
app.use(helmet());
// Increase body size limit for PDF attachments (base64 encoded) // Increase body size limit for PDF attachments (base64 encoded)
app.use(json({ limit: '5mb' })); app.use(json({ limit: '5mb' }));
app.use(urlencoded({ extended: true, limit: '5mb' })); app.use(urlencoded({ extended: true, limit: '5mb' }));

View File

@@ -1,6 +1,9 @@
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common'; import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
// Models that have soft delete (deletedAt field)
const SOFT_DELETE_MODELS = ['User', 'VIP', 'Driver', 'ScheduleEvent', 'Vehicle'];
@Injectable() @Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(PrismaService.name); private readonly logger = new Logger(PrismaService.name);
@@ -9,18 +12,69 @@ export class PrismaService extends PrismaClient implements OnModuleInit, OnModul
super({ super({
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'], log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
}); });
// Apply soft-delete middleware
this.applySoftDeleteMiddleware();
} }
async onModuleInit() { async onModuleInit() {
try { try {
await this.$connect(); await this.$connect();
this.logger.log('✅ Database connected successfully'); this.logger.log('✅ Database connected successfully');
this.logger.log('✅ Soft-delete middleware active for: ' + SOFT_DELETE_MODELS.join(', '));
} catch (error) { } catch (error) {
this.logger.error('❌ Database connection failed', error); this.logger.error('❌ Database connection failed', error);
throw error; throw error;
} }
} }
/**
* Apply Prisma middleware to automatically filter out soft-deleted records
*
* This middleware automatically adds `deletedAt: null` to where clauses for models
* that have a deletedAt field, preventing soft-deleted records from being returned.
*
* Escape hatches:
* - Pass `{ deletedAt: { not: null } }` to query ONLY deleted records
* - Pass `{ deletedAt: undefined }` or any explicit deletedAt filter to bypass middleware
* - Hard delete operations (delete, deleteMany) are not affected
*/
private applySoftDeleteMiddleware() {
this.$use(async (params, next) => {
// Only apply to models with soft delete
if (!SOFT_DELETE_MODELS.includes(params.model || '')) {
return next(params);
}
// Operations to apply soft-delete filter to
const operations = ['findUnique', 'findFirst', 'findMany', 'count', 'aggregate'];
if (operations.includes(params.action)) {
// Initialize where clause if it doesn't exist
params.args.where = params.args.where || {};
// Only apply filter if deletedAt is not already specified
// This allows explicit queries for deleted records: { deletedAt: { not: null } }
// or to bypass middleware: { deletedAt: undefined }
if (!('deletedAt' in params.args.where)) {
params.args.where.deletedAt = null;
}
}
// For update/updateMany, ensure we don't accidentally update soft-deleted records
if (params.action === 'update' || params.action === 'updateMany') {
params.args.where = params.args.where || {};
// Only apply if not explicitly specified
if (!('deletedAt' in params.args.where)) {
params.args.where.deletedAt = null;
}
}
return next(params);
});
}
async onModuleDestroy() { async onModuleDestroy() {
await this.$disconnect(); await this.$disconnect();
this.logger.log('Database disconnected'); this.logger.log('Database disconnected');

File diff suppressed because it is too large Load Diff

View File

@@ -12,6 +12,7 @@ import {
MaxFileSizeValidator, MaxFileSizeValidator,
FileTypeValidator, FileTypeValidator,
} from '@nestjs/common'; } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express'; import { FileInterceptor } from '@nestjs/platform-express';
import { SettingsService } from './settings.service'; import { SettingsService } from './settings.service';
import { UpdatePdfSettingsDto } from './dto/update-pdf-settings.dto'; import { UpdatePdfSettingsDto } from './dto/update-pdf-settings.dto';
@@ -22,7 +23,41 @@ import { CanUpdate } from '../auth/decorators/check-ability.decorator';
@Controller('settings') @Controller('settings')
@UseGuards(JwtAuthGuard, AbilitiesGuard) @UseGuards(JwtAuthGuard, AbilitiesGuard)
export class SettingsController { export class SettingsController {
constructor(private readonly settingsService: SettingsService) {} constructor(
private readonly settingsService: SettingsService,
private readonly configService: ConfigService,
) {}
/**
* Feature flags - tells the frontend which optional services are configured.
* No ability decorator = any authenticated user can access.
*/
@Get('features')
getFeatureFlags() {
return {
copilot: !!this.configService.get('ANTHROPIC_API_KEY'),
flightTracking: !!this.configService.get('AVIATIONSTACK_API_KEY'),
signalMessaging: !!this.configService.get('SIGNAL_API_URL'),
gpsTracking: !!this.configService.get('TRACCAR_API_URL'),
};
}
/**
* Get app timezone - any authenticated user can read this
*/
@Get('timezone')
getTimezone() {
return this.settingsService.getTimezone();
}
/**
* Update app timezone - admin only
*/
@Patch('timezone')
@CanUpdate('Settings')
updateTimezone(@Body() dto: { timezone: string }) {
return this.settingsService.updateTimezone(dto.timezone);
}
@Get('pdf') @Get('pdf')
@CanUpdate('Settings') // Admin-only (Settings subject is admin-only) @CanUpdate('Settings') // Admin-only (Settings subject is admin-only)

View File

@@ -75,6 +75,37 @@ export class SettingsService {
} }
} }
/**
* Get the app-wide timezone setting
*/
async getTimezone(): Promise<{ timezone: string }> {
const settings = await this.getPdfSettings();
return { timezone: settings.timezone };
}
/**
* Update the app-wide timezone setting
*/
async updateTimezone(timezone: string): Promise<{ timezone: string }> {
this.logger.log(`Updating timezone to: ${timezone}`);
// Validate the timezone string
try {
Intl.DateTimeFormat(undefined, { timeZone: timezone });
} catch {
throw new BadRequestException(`Invalid timezone: ${timezone}`);
}
const existing = await this.getPdfSettings();
await this.prisma.pdfSettings.update({
where: { id: existing.id },
data: { timezone },
});
return { timezone };
}
/** /**
* Upload logo as base64 data URL * Upload logo as base64 data URL
*/ */

View File

@@ -6,16 +6,18 @@ import {
Body, Body,
Param, Param,
Query, Query,
Req,
UseGuards, UseGuards,
Logger, Logger,
Res, Res,
} from '@nestjs/common'; } from '@nestjs/common';
import { Response } from 'express'; import { Request, Response } from 'express';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard'; import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator'; import { Roles } from '../auth/decorators/roles.decorator';
import { Public } from '../auth/decorators/public.decorator'; import { Public } from '../auth/decorators/public.decorator';
import { MessagesService, SendMessageDto } from './messages.service'; import { MessagesService, SendMessageDto } from './messages.service';
import { toDateString } from '../common/utils/date.utils';
// DTO for incoming Signal webhook // DTO for incoming Signal webhook
interface SignalWebhookPayload { interface SignalWebhookPayload {
@@ -105,7 +107,14 @@ export class MessagesController {
*/ */
@Public() @Public()
@Post('webhook') @Post('webhook')
async handleWebhook(@Body() payload: SignalWebhookPayload) { async handleWebhook(@Body() payload: SignalWebhookPayload, @Req() req: Request) {
// Validate webhook secret if configured
const secret = process.env.SIGNAL_WEBHOOK_SECRET;
if (secret && req.headers['x-webhook-secret'] !== secret) {
this.logger.warn('Webhook rejected: invalid or missing secret');
return { success: false, error: 'Unauthorized' };
}
this.logger.debug('Received Signal webhook:', JSON.stringify(payload)); this.logger.debug('Received Signal webhook:', JSON.stringify(payload));
try { try {
@@ -146,7 +155,7 @@ export class MessagesController {
async exportMessages(@Res() res: Response) { async exportMessages(@Res() res: Response) {
const exportData = await this.messagesService.exportAllMessages(); const exportData = await this.messagesService.exportAllMessages();
const filename = `signal-chats-${new Date().toISOString().split('T')[0]}.txt`; const filename = `signal-chats-${toDateString(new Date())}.txt`;
res.setHeader('Content-Type', 'text/plain; charset=utf-8'); res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`); res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);

View File

@@ -36,7 +36,7 @@ export class MessagesService {
*/ */
async getMessagesForDriver(driverId: string, limit: number = 50) { async getMessagesForDriver(driverId: string, limit: number = 50) {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id: driverId, deletedAt: null }, where: { id: driverId },
}); });
if (!driver) { if (!driver) {
@@ -55,7 +55,7 @@ export class MessagesService {
*/ */
async sendMessage(dto: SendMessageDto) { async sendMessage(dto: SendMessageDto) {
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { id: dto.driverId, deletedAt: null }, where: { id: dto.driverId },
}); });
if (!driver) { if (!driver) {
@@ -113,7 +113,6 @@ export class MessagesService {
// Find driver by phone number // Find driver by phone number
const driver = await this.prisma.driver.findFirst({ const driver = await this.prisma.driver.findFirst({
where: { where: {
deletedAt: null,
OR: [ OR: [
{ phone: fromNumber }, { phone: fromNumber },
{ phone: normalizedPhone }, { phone: normalizedPhone },
@@ -172,7 +171,6 @@ export class MessagesService {
where: { where: {
driverId: driver.id, driverId: driver.id,
status: EventStatus.IN_PROGRESS, status: EventStatus.IN_PROGRESS,
deletedAt: null,
}, },
include: { vehicle: true }, include: { vehicle: true },
}); });

View File

@@ -11,7 +11,6 @@ export class UsersService {
async findAll() { async findAll() {
return this.prisma.user.findMany({ return this.prisma.user.findMany({
where: { deletedAt: null },
include: { driver: true }, include: { driver: true },
orderBy: { createdAt: 'desc' }, orderBy: { createdAt: 'desc' },
}); });
@@ -19,7 +18,7 @@ export class UsersService {
async findOne(id: string) { async findOne(id: string) {
const user = await this.prisma.user.findFirst({ const user = await this.prisma.user.findFirst({
where: { id, deletedAt: null }, where: { id },
include: { driver: true }, include: { driver: true },
}); });
@@ -38,8 +37,20 @@ export class UsersService {
const { isAlsoDriver, ...prismaData } = updateUserDto; const { isAlsoDriver, ...prismaData } = updateUserDto;
const effectiveRole = updateUserDto.role || user.role; const effectiveRole = updateUserDto.role || user.role;
// Handle role change to DRIVER: auto-create driver record const hasActiveDriver = user.driver && !user.driver.deletedAt;
if (updateUserDto.role === Role.DRIVER && !user.driver) { const hasSoftDeletedDriver = user.driver && user.driver.deletedAt;
// Handle role change to DRIVER: auto-create or restore driver record
if (updateUserDto.role === Role.DRIVER && !hasActiveDriver) {
if (hasSoftDeletedDriver) {
this.logger.log(
`Restoring soft-deleted Driver record for user ${user.email} (role change to DRIVER)`,
);
await this.prisma.driver.update({
where: { id: user.driver!.id },
data: { deletedAt: null, name: user.name || user.email },
});
} else {
this.logger.log( this.logger.log(
`Creating Driver record for user ${user.email} (role change to DRIVER)`, `Creating Driver record for user ${user.email} (role change to DRIVER)`,
); );
@@ -51,12 +62,22 @@ export class UsersService {
}, },
}); });
} }
}
// When promoting FROM DRIVER to Admin/Coordinator, keep the driver record // When promoting FROM DRIVER to Admin/Coordinator, keep the driver record
// (admin can explicitly uncheck the driver box later if they want) // (admin can explicitly uncheck the driver box later if they want)
// Handle "Also a Driver" toggle (independent of role) // Handle "Also a Driver" toggle (independent of role)
if (isAlsoDriver === true && !user.driver) { if (isAlsoDriver === true && !hasActiveDriver) {
if (hasSoftDeletedDriver) {
this.logger.log(
`Restoring soft-deleted Driver record for user ${user.email} (isAlsoDriver toggled on)`,
);
await this.prisma.driver.update({
where: { id: user.driver!.id },
data: { deletedAt: null, name: user.name || user.email },
});
} else {
this.logger.log( this.logger.log(
`Creating Driver record for user ${user.email} (isAlsoDriver toggled on)`, `Creating Driver record for user ${user.email} (isAlsoDriver toggled on)`,
); );
@@ -67,13 +88,14 @@ export class UsersService {
userId: user.id, userId: user.id,
}, },
}); });
} else if (isAlsoDriver === false && user.driver && effectiveRole !== Role.DRIVER) { }
} else if (isAlsoDriver === false && hasActiveDriver && effectiveRole !== Role.DRIVER) {
// Only allow removing driver record if user is NOT in the DRIVER role // Only allow removing driver record if user is NOT in the DRIVER role
this.logger.log( this.logger.log(
`Soft-deleting Driver record for user ${user.email} (isAlsoDriver toggled off)`, `Soft-deleting Driver record for user ${user.email} (isAlsoDriver toggled off)`,
); );
await this.prisma.driver.update({ await this.prisma.driver.update({
where: { id: user.driver.id }, where: { id: user.driver!.id },
data: { deletedAt: new Date() }, data: { deletedAt: new Date() },
}); });
} }
@@ -113,7 +135,6 @@ export class UsersService {
async getPendingUsers() { async getPendingUsers() {
return this.prisma.user.findMany({ return this.prisma.user.findMany({
where: { where: {
deletedAt: null,
isApproved: false, isApproved: false,
}, },
orderBy: { createdAt: 'asc' }, orderBy: { createdAt: 'asc' },

View File

@@ -13,8 +13,10 @@ import { VehiclesService } from './vehicles.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard'; import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles } from '../auth/decorators/roles.decorator'; import { Roles } from '../auth/decorators/roles.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { Role } from '@prisma/client'; import { Role } from '@prisma/client';
import { CreateVehicleDto, UpdateVehicleDto } from './dto'; import { CreateVehicleDto, UpdateVehicleDto } from './dto';
import { ParseBooleanPipe } from '../common/pipes';
@Controller('vehicles') @Controller('vehicles')
@UseGuards(JwtAuthGuard, RolesGuard) @UseGuards(JwtAuthGuard, RolesGuard)
@@ -56,8 +58,11 @@ export class VehiclesController {
@Delete(':id') @Delete(':id')
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR) @Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
remove(@Param('id') id: string, @Query('hard') hard?: string) { remove(
const isHardDelete = hard === 'true'; @Param('id') id: string,
return this.vehiclesService.remove(id, isHardDelete); @Query('hard', ParseBooleanPipe) hard: boolean,
@CurrentUser() user?: any,
) {
return this.vehiclesService.remove(id, hard, user?.role);
} }
} }

View File

@@ -1,11 +1,20 @@
import { Injectable, NotFoundException, Logger } from '@nestjs/common'; import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { CreateVehicleDto, UpdateVehicleDto } from './dto'; import { CreateVehicleDto, UpdateVehicleDto } from './dto';
import { executeHardDelete } from '../common/utils';
@Injectable() @Injectable()
export class VehiclesService { export class VehiclesService {
private readonly logger = new Logger(VehiclesService.name); private readonly logger = new Logger(VehiclesService.name);
private readonly vehicleInclude = {
currentDriver: true,
events: {
include: { driver: true, vehicle: true },
orderBy: { startTime: 'asc' as const },
},
} as const;
constructor(private prisma: PrismaService) {} constructor(private prisma: PrismaService) {}
async create(createVehicleDto: CreateVehicleDto) { async create(createVehicleDto: CreateVehicleDto) {
@@ -13,27 +22,13 @@ export class VehiclesService {
return this.prisma.vehicle.create({ return this.prisma.vehicle.create({
data: createVehicleDto, data: createVehicleDto,
include: { include: this.vehicleInclude,
currentDriver: true,
events: {
where: { deletedAt: null },
include: { driver: true, vehicle: true },
},
},
}); });
} }
async findAll() { async findAll() {
return this.prisma.vehicle.findMany({ return this.prisma.vehicle.findMany({
where: { deletedAt: null }, include: this.vehicleInclude,
include: {
currentDriver: true,
events: {
where: { deletedAt: null },
include: { driver: true, vehicle: true },
orderBy: { startTime: 'asc' },
},
},
orderBy: { name: 'asc' }, orderBy: { name: 'asc' },
}); });
} }
@@ -41,7 +36,6 @@ export class VehiclesService {
async findAvailable() { async findAvailable() {
return this.prisma.vehicle.findMany({ return this.prisma.vehicle.findMany({
where: { where: {
deletedAt: null,
status: 'AVAILABLE', status: 'AVAILABLE',
}, },
include: { include: {
@@ -53,15 +47,8 @@ export class VehiclesService {
async findOne(id: string) { async findOne(id: string) {
const vehicle = await this.prisma.vehicle.findFirst({ const vehicle = await this.prisma.vehicle.findFirst({
where: { id, deletedAt: null }, where: { id },
include: { include: this.vehicleInclude,
currentDriver: true,
events: {
where: { deletedAt: null },
include: { driver: true, vehicle: true },
orderBy: { startTime: 'asc' },
},
},
}); });
if (!vehicle) { if (!vehicle) {
@@ -79,30 +66,24 @@ export class VehiclesService {
return this.prisma.vehicle.update({ return this.prisma.vehicle.update({
where: { id: vehicle.id }, where: { id: vehicle.id },
data: updateVehicleDto, data: updateVehicleDto,
include: { include: this.vehicleInclude,
currentDriver: true,
events: {
where: { deletedAt: null },
include: { driver: true, vehicle: true },
},
},
}); });
} }
async remove(id: string, hardDelete = false) { async remove(id: string, hardDelete = false, userRole?: string) {
const vehicle = await this.findOne(id); return executeHardDelete({
id,
if (hardDelete) { hardDelete,
this.logger.log(`Hard deleting vehicle: ${vehicle.name}`); userRole,
return this.prisma.vehicle.delete({ findOne: (id) => this.findOne(id),
where: { id: vehicle.id }, performHardDelete: (id) => this.prisma.vehicle.delete({ where: { id } }),
}); performSoftDelete: (id) =>
} this.prisma.vehicle.update({
where: { id },
this.logger.log(`Soft deleting vehicle: ${vehicle.name}`);
return this.prisma.vehicle.update({
where: { id: vehicle.id },
data: { deletedAt: new Date() }, data: { deletedAt: new Date() },
}),
entityName: 'Vehicle',
logger: this.logger,
}); });
} }
@@ -110,23 +91,32 @@ export class VehiclesService {
* Get vehicle utilization statistics * Get vehicle utilization statistics
*/ */
async getUtilization() { async getUtilization() {
const vehicles = await this.findAll(); const now = new Date();
const stats = vehicles.map((vehicle) => { // Fetch vehicles with only upcoming events (filtered at database level)
const upcomingEvents = vehicle.events.filter( const vehicles = await this.prisma.vehicle.findMany({
(event) => new Date(event.startTime) > new Date(), include: {
); currentDriver: true,
events: {
where: {
startTime: { gt: now }, // Only fetch upcoming events
},
include: { driver: true, vehicle: true },
orderBy: { startTime: 'asc' },
},
},
orderBy: { name: 'asc' },
});
return { const stats = vehicles.map((vehicle) => ({
id: vehicle.id, id: vehicle.id,
name: vehicle.name, name: vehicle.name,
type: vehicle.type, type: vehicle.type,
seatCapacity: vehicle.seatCapacity, seatCapacity: vehicle.seatCapacity,
status: vehicle.status, status: vehicle.status,
upcomingTrips: upcomingEvents.length, upcomingTrips: vehicle.events.length, // Already filtered at DB level
currentDriver: vehicle.currentDriver?.name, currentDriver: vehicle.currentDriver?.name,
}; }));
});
return { return {
totalVehicles: vehicles.length, totalVehicles: vehicles.length,

View File

@@ -4,6 +4,9 @@ import {
IsOptional, IsOptional,
IsBoolean, IsBoolean,
IsDateString, IsDateString,
IsInt,
IsEmail,
Min,
} from 'class-validator'; } from 'class-validator';
import { Department, ArrivalMode } from '@prisma/client'; import { Department, ArrivalMode } from '@prisma/client';
@@ -33,7 +36,35 @@ export class CreateVipDto {
@IsOptional() @IsOptional()
venueTransport?: boolean; venueTransport?: boolean;
@IsInt()
@IsOptional()
@Min(1)
partySize?: number;
@IsString() @IsString()
@IsOptional() @IsOptional()
notes?: string; notes?: string;
// Roster-only flag: true = just tracking for accountability, not active coordination
@IsBoolean()
@IsOptional()
isRosterOnly?: boolean;
// VIP contact info
@IsString()
@IsOptional()
phone?: string;
@IsEmail()
@IsOptional()
email?: string;
// Emergency contact info (for accountability reports)
@IsString()
@IsOptional()
emergencyContactName?: string;
@IsString()
@IsOptional()
emergencyContactPhone?: string;
} }

View File

@@ -13,7 +13,9 @@ import { VipsService } from './vips.service';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AbilitiesGuard } from '../auth/guards/abilities.guard'; import { AbilitiesGuard } from '../auth/guards/abilities.guard';
import { CanCreate, CanRead, CanUpdate, CanDelete } from '../auth/decorators/check-ability.decorator'; import { CanCreate, CanRead, CanUpdate, CanDelete } from '../auth/decorators/check-ability.decorator';
import { CurrentUser } from '../auth/decorators/current-user.decorator';
import { CreateVipDto, UpdateVipDto } from './dto'; import { CreateVipDto, UpdateVipDto } from './dto';
import { ParseBooleanPipe } from '../common/pipes';
@Controller('vips') @Controller('vips')
@UseGuards(JwtAuthGuard, AbilitiesGuard) @UseGuards(JwtAuthGuard, AbilitiesGuard)
@@ -48,10 +50,9 @@ export class VipsController {
@CanDelete('VIP') @CanDelete('VIP')
remove( remove(
@Param('id') id: string, @Param('id') id: string,
@Query('hard') hard?: string, @Query('hard', ParseBooleanPipe) hard: boolean,
@CurrentUser() user?: any,
) { ) {
// Only administrators can hard delete return this.vipsService.remove(id, hard, user?.role);
const isHardDelete = hard === 'true';
return this.vipsService.remove(id, isHardDelete);
} }
} }

View File

@@ -1,6 +1,7 @@
import { Injectable, NotFoundException, Logger } from '@nestjs/common'; import { Injectable, NotFoundException, Logger } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service'; import { PrismaService } from '../prisma/prisma.service';
import { CreateVipDto, UpdateVipDto } from './dto'; import { CreateVipDto, UpdateVipDto } from './dto';
import { executeHardDelete } from '../common/utils';
@Injectable() @Injectable()
export class VipsService { export class VipsService {
@@ -21,7 +22,6 @@ export class VipsService {
async findAll() { async findAll() {
return this.prisma.vIP.findMany({ return this.prisma.vIP.findMany({
where: { deletedAt: null },
include: { include: {
flights: true, flights: true,
}, },
@@ -31,7 +31,7 @@ export class VipsService {
async findOne(id: string) { async findOne(id: string) {
const vip = await this.prisma.vIP.findFirst({ const vip = await this.prisma.vIP.findFirst({
where: { id, deletedAt: null }, where: { id },
include: { include: {
flights: true, flights: true,
}, },
@@ -58,20 +58,20 @@ export class VipsService {
}); });
} }
async remove(id: string, hardDelete = false) { async remove(id: string, hardDelete = false, userRole?: string) {
const vip = await this.findOne(id); return executeHardDelete({
id,
if (hardDelete) { hardDelete,
this.logger.log(`Hard deleting VIP: ${vip.name}`); userRole,
return this.prisma.vIP.delete({ findOne: (id) => this.findOne(id),
where: { id: vip.id }, performHardDelete: (id) => this.prisma.vIP.delete({ where: { id } }),
}); performSoftDelete: (id) =>
} this.prisma.vIP.update({
where: { id },
this.logger.log(`Soft deleting VIP: ${vip.name}`);
return this.prisma.vIP.update({
where: { id: vip.id },
data: { deletedAt: new Date() }, data: { deletedAt: new Date() },
}),
entityName: 'VIP',
logger: this.logger,
}); });
} }
} }

View File

@@ -80,6 +80,7 @@ services:
DATABASE_URL: postgresql://postgres:changeme@postgres:5432/vip_coordinator DATABASE_URL: postgresql://postgres:changeme@postgres:5432/vip_coordinator
REDIS_URL: redis://redis:6379 REDIS_URL: redis://redis:6379
SIGNAL_API_URL: http://signal-api:8080 SIGNAL_API_URL: http://signal-api:8080
SIGNAL_WEBHOOK_SECRET: ${SIGNAL_WEBHOOK_SECRET:-}
TRACCAR_API_URL: http://traccar:8082 TRACCAR_API_URL: http://traccar:8082
TRACCAR_DEVICE_PORT: 5055 TRACCAR_DEVICE_PORT: 5055
AUTH0_DOMAIN: ${AUTH0_DOMAIN} AUTH0_DOMAIN: ${AUTH0_DOMAIN}

630
docs/USER_GUIDE.md Normal file
View File

@@ -0,0 +1,630 @@
# VIP Coordinator - User Guide
A comprehensive guide to using the VIP Coordinator application for managing VIP transportation logistics, driver coordination, event scheduling, and fleet management.
---
## Table of Contents
1. [Getting Started](#getting-started)
- [Logging In](#logging-in)
- [Understanding Your Role](#understanding-your-role)
- [Navigation Overview](#navigation-overview)
2. [Dashboard](#dashboard)
3. [War Room (Command Center)](#war-room-command-center)
4. [Managing VIPs](#managing-vips)
- [Viewing the VIP List](#viewing-the-vip-list)
- [Adding a New VIP](#adding-a-new-vip)
- [Editing a VIP](#editing-a-vip)
- [VIP Contact & Emergency Info](#vip-contact--emergency-info)
- [Deleting a VIP](#deleting-a-vip)
5. [Fleet Management](#fleet-management)
- [Drivers Tab](#drivers-tab)
- [Adding a Driver](#adding-a-driver)
- [Vehicles Tab](#vehicles-tab)
- [Adding a Vehicle](#adding-a-vehicle)
6. [Activities (Events & Scheduling)](#activities-events--scheduling)
- [Viewing Activities](#viewing-activities)
- [Creating an Activity](#creating-an-activity)
- [Activity Types](#activity-types)
- [Conflict Detection](#conflict-detection)
7. [Flight Tracking](#flight-tracking)
- [Viewing Flights](#viewing-flights)
- [Adding a Flight](#adding-a-flight)
8. [GPS Tracking](#gps-tracking)
- [Overview](#gps-overview)
- [Enrolling a Driver for GPS](#enrolling-a-driver-for-gps)
- [Live Map](#live-map)
- [GPS Settings](#gps-settings)
9. [Reports](#reports)
- [VIP Accountability Roster](#vip-accountability-roster)
- [PDF Customization](#pdf-customization)
10. [User Management](#user-management)
- [Approving New Users](#approving-new-users)
- [Changing User Roles](#changing-user-roles)
11. [Admin Tools](#admin-tools)
- [Database Statistics](#database-statistics)
- [PDF Customization](#pdf-customization-settings)
- [Signal Messaging](#signal-messaging)
- [Test Data Management](#test-data-management)
12. [AI Assistant](#ai-assistant)
13. [Driver View (My Schedule)](#driver-view-my-schedule)
---
## Getting Started
### Logging In
1. Navigate to your VIP Coordinator URL (e.g., `https://vip.madeamess.online`).
2. Click the **"Sign in with Auth0"** button on the login page.
![Login Page](screenshots/01-login-page.png)
3. You will be redirected to the Auth0 login screen. Enter your email address and password, then click **Continue**.
![Auth0 Login](screenshots/02-auth0-login.png)
4. After successful authentication, you will be redirected to the application.
- **First-time users:** Your account requires administrator approval before you can access the system. You'll see a "Pending Approval" page until an admin approves your account.
- **Returning users:** You'll land on the Dashboard (or My Schedule if you're a Driver).
> **Tip:** Your login session persists across browser refreshes and tabs. You won't need to log in again unless you explicitly sign out or your session expires.
### Understanding Your Role
VIP Coordinator has three user roles, each with different levels of access:
| Feature | Administrator | Coordinator | Driver |
|---------|:---:|:---:|:---:|
| Dashboard & War Room | Full access | Full access | -- |
| VIP Management | Create, Edit, Delete | Create, Edit, Delete | View only |
| Fleet (Drivers/Vehicles) | Create, Edit, Delete | Create, Edit, Delete | View only |
| Activities/Events | Create, Edit, Delete | Create, Edit, Delete | View & Update status |
| Flight Tracking | Full access | Full access | -- |
| GPS Tracking | Full access | Full access | View own location |
| Reports | Full access | Full access | -- |
| User Management | Full access | -- | -- |
| Admin Tools | Full access | -- | -- |
| AI Assistant | Full access | Full access | -- |
### Navigation Overview
The top navigation bar provides access to all major sections:
- **Dashboard** - Quick overview of today's activities and stats
- **War Room** - Real-time command center for active operations
- **VIPs** - Manage VIP profiles and their travel details
- **Fleet** - Manage drivers and vehicles
- **Activities** - Schedule and track events/transport
- **Flights** - Track flight arrivals and departures
- **Admin** (dropdown) - User Management, GPS Tracking, Reports, Admin Tools
Your user avatar and email appear in the top-right corner. Click it to access your profile or sign out.
---
## Dashboard
The Dashboard is your home base, providing a quick overview of the current situation.
![Dashboard](screenshots/03-dashboard.png)
**What you'll see:**
- **Summary Cards** - Quick counts of VIPs, drivers, vehicles, and today's events
- **Today's Schedule** - A timeline of upcoming activities for the day
- **Recent Activity** - Latest changes and updates in the system
- **Quick Actions** - Shortcuts to common tasks like adding a VIP or creating an event
> **Tip:** The Dashboard automatically refreshes to show you the latest data. It's a great page to keep open as your main monitoring screen.
---
## War Room (Command Center)
The War Room is your real-time operations center, designed for active event coordination.
![War Room](screenshots/04-war-room.png)
**Key Features:**
- **Active Events Panel** - Shows all currently in-progress events with live status
- **Upcoming Events** - Events starting soon, sorted by urgency
- **Driver Status** - Which drivers are currently assigned and available
- **Quick Status Updates** - One-click buttons to mark events as started, completed, or cancelled
**How to use the War Room:**
1. Open the **War Room** from the top navigation.
2. Events are color-coded by status:
- **Red/Urgent** - Events starting in the next 5-15 minutes
- **Blue/In Progress** - Currently active events
- **Green/Completed** - Recently finished events
- **Gray/Scheduled** - Upcoming events
3. Click on any event card to see full details or update its status.
4. Use the **Refresh** button to get the latest data instantly.
> **Tip:** The War Room is ideal for day-of-event coordination. Keep it open on a large screen or dedicated monitor during active operations.
---
## Managing VIPs
### Viewing the VIP List
Navigate to **VIPs** from the top menu to see all VIP profiles.
![VIP List](screenshots/05-vip-list.png)
**Features:**
- **Search** - Filter VIPs by name or organization using the search bar
- **Department Filter** - Filter by department (Office of Development, Admin, Other)
- **Arrival Mode** - See whether each VIP is arriving by flight or self-driving
- **Party Size** - Shows the total number of people in the VIP's group
- **Quick Actions** - Edit or view schedule for each VIP
### Adding a New VIP
1. Click the **"+ Add VIP"** button in the top-right corner of the VIP List page.
2. Fill in the VIP's details:
![VIP Edit Form](screenshots/06-vip-edit-form.png)
**Required fields:**
- **Name** - Full name of the VIP
- **Department** - Which department is hosting (Office of Development, Admin, or Other)
- **Arrival Mode** - How the VIP is arriving:
- **Flight** - Arriving by air (enables flight tracking)
- **Self-Driving** - Arriving by personal vehicle (allows setting expected arrival time)
**Optional fields:**
- **Organization** - The VIP's company or organization
- **Airport Pickup** - Check if the VIP needs airport pickup service
- **Venue Transport** - Check if the VIP needs transportation between venues
- **Party Size** - Total number of people (VIP + entourage, default is 1)
- **Notes** - Any special instructions or requirements
- **Roster Only** - Check this if you're only tracking the VIP for accountability purposes (not active coordination)
3. Click **Save** to create the VIP profile.
### Editing a VIP
1. On the VIP List, click the **Edit** (pencil) icon on any VIP row.
2. The edit form opens with the VIP's current information pre-filled.
3. Make your changes and click **Save**.
### VIP Contact & Emergency Info
Scroll down in the VIP edit form to find the contact and emergency information section.
![VIP Contact Info](screenshots/07-vip-edit-contact-info.png)
**Contact fields:**
- **Phone** - VIP's phone number
- **Email** - VIP's email address
- **Emergency Contact Name** - Name of the VIP's emergency contact
- **Emergency Contact Phone** - Phone number for the emergency contact
> **Important:** Emergency contact information is included in the Accountability Roster report. Filling this in is recommended for all VIPs attending large events.
### Deleting a VIP
1. On the VIP List, click the **Delete** (trash) icon on the VIP's row.
2. Confirm the deletion when prompted.
> **Note:** VIP deletion is a "soft delete" - the record is hidden but preserved in the database for audit purposes.
---
## Fleet Management
The Fleet page manages both **Drivers** and **Vehicles** from a single location.
### Drivers Tab
![Fleet - Drivers](screenshots/08-fleet-drivers.png)
The Drivers tab shows all drivers in the system, including:
- **Name** and **Phone** number
- **Department** assignment
- **Availability Status** - Whether the driver is available for assignments
- **Shift Times** - When the driver's shift starts and ends
- **Linked Account** - Whether the driver has a user account for app login
### Adding a Driver
1. Navigate to **Fleet** and ensure the **Drivers** tab is selected.
2. Click the **"+ Add Driver"** button.
3. Fill in the required information:
- **Full Name** (required)
- **Phone Number** (required)
- **Department** (optional - Office of Development, Admin, or Other)
- **User Account ID** (optional - links the driver to a login account)
4. Click **Create Driver**.
> **Tip:** When you link a driver to a user account, that user will be able to log in and see their own schedule on the "My Schedule" page. Create the user account first (they sign up and get approved), then link it here.
### Vehicles Tab
![Fleet - Vehicles](screenshots/09-fleet-vehicles.png)
The Vehicles tab displays your entire fleet, showing:
- **Vehicle Name** - Descriptive name (e.g., "Blue Van", "Suburban #3")
- **Type** - Van, SUV, Sedan, Bus, Golf Cart, or Truck
- **License Plate** number
- **Seat Capacity** - Total available seats
- **Status** - Available, In Use, Maintenance, or Reserved
- **Current Driver** - Who is currently assigned to the vehicle
### Adding a Vehicle
1. Navigate to **Fleet** and click the **Vehicles** tab.
2. Click the **"+ Add Vehicle"** button.
3. Fill in:
- **Vehicle Name** (required) - Give it a recognizable name
- **Type** (required) - Select the vehicle type
- **License Plate** (optional)
- **Seat Capacity** (required) - Total number of passenger seats
- **Notes** (optional) - Any special notes about the vehicle
4. Click **Create Vehicle**.
> **Tip:** Keep vehicle names simple and distinctive. During hectic operations, coordinators need to quickly identify vehicles. Names like "White Suburban" or "Van #2" work well.
---
## Activities (Events & Scheduling)
### Viewing Activities
Navigate to **Activities** from the top menu to see all scheduled events.
![Activities](screenshots/10-activities.png)
**Features:**
- **Status Filters** - Filter by Scheduled, In Progress, Completed, or Cancelled
- **Date Filtering** - View events for specific dates
- **Type Filtering** - Filter by Transport, Meeting, Event, Meal, or Accommodation
- **Search** - Find events by title, VIP name, or location
### Creating an Activity
1. Click **"+ New Activity"** on the Activities page.
2. Fill in the event details:
- **Title** (required) - Descriptive name for the event
- **Type** - Transport, Meeting, Event, Meal, or Accommodation
- **VIP(s)** - Select one or more VIPs for this event
- **Start Time** and **End Time** (required)
- **Driver** (optional) - Assign a driver
- **Vehicle** (optional) - Assign a vehicle
- **Pickup Location** and **Dropoff Location** (for transport events)
- **Location** (for non-transport events)
- **Description** and **Notes** (optional)
3. Click **Create** to save the event.
### Activity Types
| Type | Use For |
|------|---------|
| **Transport** | Airport pickups, venue-to-venue rides, departure drops |
| **Meeting** | Scheduled meetings between VIPs and hosts |
| **Event** | Conferences, ceremonies, tours, and other events |
| **Meal** | Breakfast, lunch, dinner, and receptions |
| **Accommodation** | Hotel check-in/check-out |
### Conflict Detection
When creating or editing an activity, the system automatically checks for scheduling conflicts:
- **Driver conflicts** - A driver can't be assigned to two events at the same time
- **Vehicle conflicts** - A vehicle can't be double-booked
- **VIP conflicts** - VIPs can't be in two places at once
If a conflict is detected, you'll see a warning with details about the overlapping event. You can choose to proceed anyway or adjust the timing.
---
## Flight Tracking
### Viewing Flights
Navigate to **Flights** from the top menu to see all tracked flights.
![Flights](screenshots/11-flights.png)
**The flights page shows:**
- **Flight Number** - Airline and flight number (e.g., AA1234)
- **Route** - Departure and arrival airports (IATA codes)
- **Date** - Flight date
- **Scheduled Times** - Planned departure and arrival
- **Actual Times** - Real departure and arrival (when available)
- **Status** - Scheduled, Delayed, In Air, Landed, etc.
- **VIP** - Which VIP is on this flight
### Adding a Flight
Flights are typically added through the VIP edit form:
1. Navigate to a VIP's profile (edit the VIP).
2. In the **Flights** section, click **"+ Add Flight"**.
3. Enter:
- **Flight Number** (e.g., "AA1234")
- **Flight Date**
- **Departure Airport** (IATA code, e.g., "JFK")
- **Arrival Airport** (IATA code, e.g., "LAX")
- **Segment** - For multi-leg itineraries (1 for first leg, 2 for second, etc.)
4. The system will attempt to look up real-time flight data if an API key is configured.
> **Tip:** Use standard IATA 3-letter airport codes (e.g., JFK, LAX, ORD, ATL). The system uses these to track flight status automatically.
---
## GPS Tracking
### GPS Overview
The GPS Tracking page provides real-time location monitoring for your driver fleet.
![GPS Tracking](screenshots/15-gps-tracking.png)
**Dashboard cards at the top show:**
- **Total Enrolled** - Number of drivers enrolled in GPS tracking
- **Active Now** - Drivers currently reporting their location
- **Update Interval** - How frequently locations update (e.g., 30 seconds)
- **Shift Hours** - Hours during which tracking is active
The page has four tabs: **Live Map**, **Devices**, **Stats**, and **Settings**.
### Enrolling a Driver for GPS
To enable GPS tracking for a driver, you need to enroll them:
![GPS Devices](screenshots/16-gps-devices.png)
1. Go to **GPS Tracking** and click the **Devices** tab.
2. Click the **"Enroll Driver"** button.
3. Select the driver you want to enroll from the dropdown.
4. The system will create a unique device identifier for that driver.
5. The driver then needs to install the **Traccar Client** app on their phone:
- Available for both **iOS** (App Store) and **Android** (Google Play)
- Search for "Traccar Client" in the app store
6. In the Traccar Client app, configure:
- **Device identifier** - Enter the unique ID shown after enrollment
- **Server URL** - Enter the Traccar server URL provided by your administrator
- **Frequency** - Set to match your GPS settings (e.g., 30 seconds)
- **Location accuracy** - Set to "High"
7. Enable tracking in the app and the driver's location will appear on the Live Map.
> **Important:** GPS tracking respects driver privacy. Tracking only occurs during configured shift hours. Drivers must give consent, and the system clearly shows when tracking is active.
### Live Map
The **Live Map** tab shows all active drivers on an interactive map:
- **Green dots** indicate active drivers currently reporting location
- **Gray dots** indicate enrolled but inactive drivers
- Click on any driver marker to see their name, speed, and last update time
- The map auto-refreshes based on the configured update interval
### GPS Settings
![GPS Settings](screenshots/17-gps-settings.png)
Administrators can configure GPS tracking behavior:
1. Go to **GPS Tracking** and click the **Settings** tab.
2. Adjustable settings:
- **Update Interval** (30-300 seconds) - How often driver phones report location. Lower values = more precise tracking but higher battery usage.
- **Data Retention** (7-90 days) - How long location history is kept before automatic cleanup.
- **Tracking Hours** - Set the start and end time for when GPS tracking is active. Drivers are NOT tracked outside these hours.
3. Click **Save** to apply changes.
> **Tip:** For most events, a 30-60 second update interval provides good tracking while preserving driver phone battery. During critical operations, you can temporarily lower this to 15-30 seconds.
---
## Reports
### VIP Accountability Roster
Navigate to **Reports** under the **Admin** dropdown to access the accountability roster.
![Reports](screenshots/12-reports.png)
The **VIP Accountability Roster** is a comprehensive report designed for event-day accountability. It includes:
- **VIP Name and Organization**
- **Contact Information** (phone, email)
- **Emergency Contact** details
- **Arrival Mode** and expected arrival time
- **Assigned Driver and Vehicle**
- **Flight Details** (for VIPs arriving by air)
- **Party Size**
- **Special Notes**
**To generate the report:**
1. Navigate to **Reports**.
2. The roster is displayed on screen with all active VIPs.
3. Click **"Download PDF"** to generate a professionally formatted PDF document.
4. The PDF uses your configured branding (logo, colors, contact info) from the Admin Tools settings.
> **Tip:** Print the Accountability Roster before each event starts. It serves as a backup reference when technology isn't available and is useful for emergency situations where you need quick access to VIP contact and emergency information.
### PDF Customization
The appearance of generated PDF reports can be fully customized. See [Admin Tools > PDF Customization](#pdf-customization-settings) for details.
---
## User Management
Administrators can manage user accounts from the **Users** page.
![User Management](screenshots/13-users.png)
### Approving New Users
When a new person signs up, their account starts in a "Pending Approval" state:
1. Navigate to **Admin > Users**.
2. Look for users with a **"Pending"** status badge.
3. Click **"Approve"** to grant them access to the system.
4. The user will be able to log in on their next attempt.
> **Note:** The very first user to register is automatically approved and given the Administrator role. All subsequent users require manual approval.
### Changing User Roles
1. On the Users page, find the user whose role you want to change.
2. Use the **Role** dropdown to select:
- **Administrator** - Full system access, can manage users and settings
- **Coordinator** - Can manage VIPs, drivers, events, and view all data
- **Driver** - Limited view, can see their own schedule and update event status
3. The change takes effect immediately.
> **Warning:** Be careful when changing roles. Removing someone's Administrator role cannot be undone by that user - another admin must restore it.
---
## Admin Tools
The Admin Tools page is only accessible to Administrators and provides system management capabilities.
![Admin Tools](screenshots/14-admin-tools.png)
### Database Statistics
At the top of the page, you'll see a live count of all records in the system:
- Number of VIPs, Drivers, Vehicles, Events, Flights, and Users
- Click **Refresh** to update the counts
### PDF Customization Settings
Customize how generated PDF documents look:
**Branding:**
- **Organization Name** - Appears in the PDF header
- **Organization Logo** - Upload your logo (PNG, JPG, or SVG, max 2MB)
- **Accent Color** - The primary color used for headers and section titles
- **Tagline** - Optional text below the organization name
**Contact Information:**
- **Contact Email** and **Phone** - Shown in the PDF footer
- **Secondary Contact** - Optional backup contact
- **Contact Label** - The heading above contact info (e.g., "Questions or Changes?")
**Document Options:**
- **Draft Watermark** - Add a diagonal "DRAFT" watermark
- **Confidential Watermark** - Add a "CONFIDENTIAL" watermark
- **Show Timestamp** - Include generation date/time
- **Page Size** - Letter or A4
**Content Display:**
- Toggle visibility of flight info, driver names, vehicle names, VIP notes, and event descriptions
**Custom Messages:**
- **Header Message** - Custom text at the top of the document
- **Footer Message** - Custom text at the bottom
Click **"Preview Sample PDF"** to see how your settings look before saving, then click **"Save PDF Settings"** to apply.
### Signal Messaging
The Signal Messaging section allows you to communicate with drivers via Signal (encrypted messaging):
- **Connection Status** - Shows whether the Signal service is connected and which phone number is linked
- **Send Test Message** - Send a test message to verify the connection
- **Chat History** - View message statistics and manage chat history
### Test Data Management
For development and demo purposes:
- **Generate Complete Test Data** - Creates a full set of realistic test data (20 VIPs, 8 drivers, 10 vehicles, 100+ events)
- **Refresh Event Times** - Keeps existing VIPs/drivers/vehicles but regenerates all events with fresh timestamps relative to the current time
- **Clear All Data** - Removes all VIPs, drivers, vehicles, events, flights, and messages
> **Warning:** "Clear All Data" is irreversible. Only use it when you want to start completely fresh.
---
## AI Assistant
The AI Assistant is a built-in copilot that can help you with VIP coordination tasks.
![AI Assistant](screenshots/18-ai-assistant.png)
**To open the AI Assistant:**
1. Click the blue **"AI Assistant"** button in the bottom-right corner of any page.
2. The chat panel slides open.
**What the AI Assistant can do:**
- Answer questions about your VIPs, drivers, and events
- Look up what's happening today or at specific times
- Find available drivers for assignments
- Check which VIPs are arriving by flight
- Help you understand the current status of operations
- Process screenshots of emails (upload an image of an email with VIP travel details)
**Example questions you can ask:**
- *"What's happening today?"*
- *"Who are the VIPs arriving by flight?"*
- *"Which drivers are available right now?"*
- *"Show me the schedule for Roger Mosby"*
- *"What events are in progress?"*
**To upload an image:**
1. Click the **image upload** button (camera icon) in the chat input area.
2. Select a screenshot or photo (e.g., an email with travel itinerary details).
3. The AI will read the image and extract relevant information.
> **Tip:** The AI Assistant has access to your live data. It can query VIPs, drivers, events, and more in real-time. Use it as a quick way to get answers without navigating to different pages.
---
## Driver View (My Schedule)
Drivers who have a linked user account see a simplified interface focused on their assignments.
**When a driver logs in, they see:**
- **My Schedule** - Their personal schedule showing only events assigned to them
- **Today's Events** - Quick view of what's coming up
- **Status Updates** - Ability to mark their events as "In Progress" or "Completed"
**How drivers update event status:**
1. On their schedule, find the current event.
2. Click the status button to cycle through:
- **Scheduled** (default) - Not yet started
- **In Progress** - Currently underway (click when you start the pickup/transport)
- **Completed** - Finished (click when the VIP has been dropped off)
3. Coordinators and administrators see these status changes in real-time on the War Room.
> **Tip for Drivers:** Keep your event statuses updated! This helps the coordination team know exactly where VIPs are at all times. Mark "In Progress" when you begin a pickup and "Completed" when the VIP is delivered to their destination.
---
## Frequently Asked Questions
**Q: I just signed up but can't access anything. What do I do?**
A: Your account needs to be approved by an administrator. Contact your team lead and ask them to approve your account in the User Management section.
**Q: I'm a driver but I can't see my schedule. What's wrong?**
A: Make sure your user account is linked to a driver profile. An administrator needs to go to Fleet > Drivers, find your driver record, and enter your User Account ID.
**Q: Can I use the app on my phone?**
A: Yes! The web application is responsive and works on mobile browsers. Simply navigate to the same URL on your phone's browser. For GPS tracking, you'll also need the Traccar Client app.
**Q: How do I change my password?**
A: Passwords are managed through Auth0. Click your profile avatar in the top-right corner, then follow the "Change Password" link, or use the "Forgot Password" option on the login screen.
**Q: What happens if two events conflict?**
A: The system will warn you about scheduling conflicts when creating or editing events. You'll see which driver, vehicle, or VIP has an overlapping booking and can choose to adjust the timing or proceed anyway.
**Q: Is the GPS tracking always on?**
A: No. GPS tracking only operates during the configured Shift Hours (set by administrators). Outside those hours, driver locations are not tracked or recorded.
**Q: How long is location data kept?**
A: Location data is automatically deleted after the configured retention period (default: 30 days). Administrators can adjust this in GPS Settings.
---
*This documentation was generated for VIP Coordinator. For technical support or feature requests, contact your system administrator.*

View File

@@ -11,12 +11,12 @@
"@auth0/auth0-react": "^2.2.4", "@auth0/auth0-react": "^2.2.4",
"@casl/ability": "^6.8.0", "@casl/ability": "^6.8.0",
"@casl/react": "^5.0.1", "@casl/react": "^5.0.1",
"@heroicons/react": "^2.2.0",
"@react-pdf/renderer": "^4.3.2", "@react-pdf/renderer": "^4.3.2",
"@tanstack/react-query": "^5.17.19", "@tanstack/react-query": "^5.17.19",
"axios": "^1.6.5", "axios": "^1.6.5",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"date-fns": "^3.2.0", "date-fns": "^3.2.0",
"fuse.js": "^7.1.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.309.0", "lucide-react": "^0.309.0",
"qrcode.react": "^4.2.0", "qrcode.react": "^4.2.0",
@@ -912,15 +912,6 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0" "node": "^12.22.0 || ^14.17.0 || >=16.0.0"
} }
}, },
"node_modules/@heroicons/react": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@heroicons/react/-/react-2.2.0.tgz",
"integrity": "sha512-LMcepvRaS9LYHJGsF0zzmgKCUim/X3N/DQKc4jepAXJ7l8QxJ1PmxJzqplF2Z3FE4PqBAIGyJAQ/w4B5dsqbtQ==",
"license": "MIT",
"peerDependencies": {
"react": ">= 16 || ^19.0.0-rc"
}
},
"node_modules/@humanwhocodes/config-array": { "node_modules/@humanwhocodes/config-array": {
"version": "0.13.0", "version": "0.13.0",
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz", "resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
@@ -3452,6 +3443,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/fuse.js": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/fuse.js/-/fuse.js-7.1.0.tgz",
"integrity": "sha512-trLf4SzuuUxfusZADLINj+dE8clK1frKdmqiJNb1Es75fmI5oY6X2mxLVUciLLjxqw/xr72Dhy+lER6dGd02FQ==",
"license": "Apache-2.0",
"engines": {
"node": ">=10"
}
},
"node_modules/gensync": { "node_modules/gensync": {
"version": "1.0.0-beta.2", "version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",

View File

@@ -18,12 +18,12 @@
"@auth0/auth0-react": "^2.2.4", "@auth0/auth0-react": "^2.2.4",
"@casl/ability": "^6.8.0", "@casl/ability": "^6.8.0",
"@casl/react": "^5.0.1", "@casl/react": "^5.0.1",
"@heroicons/react": "^2.2.0",
"@react-pdf/renderer": "^4.3.2", "@react-pdf/renderer": "^4.3.2",
"@tanstack/react-query": "^5.17.19", "@tanstack/react-query": "^5.17.19",
"axios": "^1.6.5", "axios": "^1.6.5",
"clsx": "^2.1.0", "clsx": "^2.1.0",
"date-fns": "^3.2.0", "date-fns": "^3.2.0",
"fuse.js": "^7.1.0",
"leaflet": "^1.9.4", "leaflet": "^1.9.4",
"lucide-react": "^0.309.0", "lucide-react": "^0.309.0",
"qrcode.react": "^4.2.0", "qrcode.react": "^4.2.0",

Binary file not shown.

After

Width:  |  Height:  |  Size: 468 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

View File

@@ -4,6 +4,7 @@ import { Auth0Provider } from '@auth0/auth0-react';
import { Toaster } from 'react-hot-toast'; import { Toaster } from 'react-hot-toast';
import { AuthProvider } from '@/contexts/AuthContext'; import { AuthProvider } from '@/contexts/AuthContext';
import { AbilityProvider } from '@/contexts/AbilityContext'; import { AbilityProvider } from '@/contexts/AbilityContext';
import { TimezoneProvider } from '@/contexts/TimezoneContext';
import { ThemeProvider } from '@/contexts/ThemeContext'; import { ThemeProvider } from '@/contexts/ThemeContext';
import { ProtectedRoute } from '@/components/ProtectedRoute'; import { ProtectedRoute } from '@/components/ProtectedRoute';
import { Layout } from '@/components/Layout'; import { Layout } from '@/components/Layout';
@@ -13,7 +14,7 @@ import { Callback } from '@/pages/Callback';
import { PendingApproval } from '@/pages/PendingApproval'; import { PendingApproval } from '@/pages/PendingApproval';
import { Dashboard } from '@/pages/Dashboard'; import { Dashboard } from '@/pages/Dashboard';
import { CommandCenter } from '@/pages/CommandCenter'; import { CommandCenter } from '@/pages/CommandCenter';
import { VIPList } from '@/pages/VipList'; import { VIPList } from '@/pages/VIPList';
import { VIPSchedule } from '@/pages/VIPSchedule'; import { VIPSchedule } from '@/pages/VIPSchedule';
import { FleetPage } from '@/pages/FleetPage'; import { FleetPage } from '@/pages/FleetPage';
import { EventList } from '@/pages/EventList'; import { EventList } from '@/pages/EventList';
@@ -23,6 +24,8 @@ import { AdminTools } from '@/pages/AdminTools';
import { DriverProfile } from '@/pages/DriverProfile'; import { DriverProfile } from '@/pages/DriverProfile';
import { MySchedule } from '@/pages/MySchedule'; import { MySchedule } from '@/pages/MySchedule';
import { GpsTracking } from '@/pages/GpsTracking'; import { GpsTracking } from '@/pages/GpsTracking';
import { Reports } from '@/pages/Reports';
import { Help } from '@/pages/Help';
import { useAuth } from '@/contexts/AuthContext'; import { useAuth } from '@/contexts/AuthContext';
// Smart redirect based on user role // Smart redirect based on user role
@@ -66,6 +69,7 @@ function App() {
> >
<QueryClientProvider client={queryClient}> <QueryClientProvider client={queryClient}>
<AuthProvider> <AuthProvider>
<TimezoneProvider>
<AbilityProvider> <AbilityProvider>
<BrowserRouter <BrowserRouter
future={{ future={{
@@ -122,6 +126,8 @@ function App() {
<Route path="/users" element={<UserList />} /> <Route path="/users" element={<UserList />} />
<Route path="/admin-tools" element={<AdminTools />} /> <Route path="/admin-tools" element={<AdminTools />} />
<Route path="/gps-tracking" element={<GpsTracking />} /> <Route path="/gps-tracking" element={<GpsTracking />} />
<Route path="/reports" element={<Reports />} />
<Route path="/help" element={<Help />} />
<Route path="/profile" element={<DriverProfile />} /> <Route path="/profile" element={<DriverProfile />} />
<Route path="/my-schedule" element={<MySchedule />} /> <Route path="/my-schedule" element={<MySchedule />} />
<Route path="/" element={<HomeRedirect />} /> <Route path="/" element={<HomeRedirect />} />
@@ -134,6 +140,7 @@ function App() {
</Routes> </Routes>
</BrowserRouter> </BrowserRouter>
</AbilityProvider> </AbilityProvider>
</TimezoneProvider>
</AuthProvider> </AuthProvider>
</QueryClientProvider> </QueryClientProvider>
</Auth0Provider> </Auth0Provider>

View File

@@ -0,0 +1,524 @@
/**
* Accountability Roster PDF Generator
*
* Professional roster document for emergency preparedness.
* Follows VIPSchedulePDF patterns for consistent styling.
*/
import {
Document,
Page,
Text,
View,
StyleSheet,
Font,
Image,
} from '@react-pdf/renderer';
import { PdfSettings } from '@/types/settings';
Font.register({
family: 'Helvetica',
fonts: [
{ src: 'Helvetica' },
{ src: 'Helvetica-Bold', fontWeight: 'bold' },
],
});
interface VIP {
id: string;
name: string;
organization: string | null;
department: string;
phone: string | null;
email: string | null;
emergencyContactName: string | null;
emergencyContactPhone: string | null;
isRosterOnly: boolean;
partySize: number;
}
interface AccountabilityRosterPDFProps {
vips: VIP[];
settings?: PdfSettings | null;
}
const createStyles = (accentColor: string = '#2c3e50', _pageSize: 'LETTER' | 'A4' = 'LETTER') =>
StyleSheet.create({
page: {
padding: 40,
paddingBottom: 80,
fontSize: 9,
fontFamily: 'Helvetica',
backgroundColor: '#ffffff',
color: '#333333',
},
// Watermark
watermark: {
position: 'absolute',
top: '40%',
left: '50%',
transform: 'translate(-50%, -50%) rotate(-45deg)',
fontSize: 72,
color: '#888888',
opacity: 0.2,
fontWeight: 'bold',
zIndex: 0,
},
// Logo
logoContainer: {
marginBottom: 10,
flexDirection: 'row',
justifyContent: 'center',
},
logo: {
maxWidth: 130,
maxHeight: 50,
objectFit: 'contain',
},
// Header
header: {
marginBottom: 20,
borderBottom: `2 solid ${accentColor}`,
paddingBottom: 15,
},
orgName: {
fontSize: 9,
color: '#7f8c8d',
textTransform: 'uppercase',
letterSpacing: 2,
marginBottom: 6,
},
title: {
fontSize: 22,
fontWeight: 'bold',
color: accentColor,
marginBottom: 4,
},
subtitle: {
fontSize: 10,
color: '#7f8c8d',
},
customMessage: {
fontSize: 9,
color: '#7f8c8d',
marginTop: 8,
padding: 8,
backgroundColor: '#f8f9fa',
borderLeft: `3 solid ${accentColor}`,
},
timestampBar: {
marginTop: 10,
paddingTop: 8,
borderTop: '1 solid #ecf0f1',
flexDirection: 'row',
justifyContent: 'space-between',
},
timestamp: {
fontSize: 7,
color: '#95a5a6',
},
// Summary stats row
summaryRow: {
flexDirection: 'row',
marginBottom: 15,
gap: 10,
},
summaryCard: {
flex: 1,
padding: 10,
backgroundColor: '#f8f9fa',
borderLeft: `3 solid ${accentColor}`,
},
summaryValue: {
fontSize: 18,
fontWeight: 'bold',
color: '#2c3e50',
},
summaryLabel: {
fontSize: 8,
color: '#7f8c8d',
textTransform: 'uppercase',
letterSpacing: 0.5,
},
// Section
sectionTitle: {
fontSize: 10,
fontWeight: 'bold',
color: accentColor,
textTransform: 'uppercase',
letterSpacing: 1,
marginBottom: 8,
paddingBottom: 4,
borderBottom: `2 solid ${accentColor}`,
},
section: {
marginBottom: 18,
},
// Table
table: {
borderLeft: '1 solid #dee2e6',
borderRight: '1 solid #dee2e6',
borderTop: '1 solid #dee2e6',
},
tableHeader: {
flexDirection: 'row',
backgroundColor: accentColor,
minHeight: 24,
},
tableHeaderCell: {
color: '#ffffff',
fontSize: 7,
fontWeight: 'bold',
textTransform: 'uppercase',
letterSpacing: 0.5,
padding: 6,
justifyContent: 'center',
},
tableRow: {
flexDirection: 'row',
borderBottom: '1 solid #dee2e6',
minHeight: 28,
},
tableRowAlt: {
backgroundColor: '#f8f9fa',
},
tableRowRoster: {
backgroundColor: '#fef9e7',
},
tableRowRosterAlt: {
backgroundColor: '#fdf3d0',
},
tableCell: {
padding: 5,
justifyContent: 'center',
},
cellName: {
fontSize: 9,
fontWeight: 'bold',
color: '#2c3e50',
},
cellDept: {
fontSize: 7,
color: '#7f8c8d',
marginTop: 1,
},
cellText: {
fontSize: 8,
color: '#34495e',
},
cellSmall: {
fontSize: 7,
color: '#7f8c8d',
},
cellCenter: {
fontSize: 9,
fontWeight: 'bold',
color: '#2c3e50',
textAlign: 'center',
},
cellNoData: {
fontSize: 7,
color: '#bdc3c7',
fontStyle: 'italic',
},
// Column widths
colName: { width: '22%' },
colOrg: { width: '18%' },
colContact: { width: '22%' },
colEmergency: { width: '22%' },
colParty: { width: '8%' },
colNotes: { width: '8%' },
// Footer
footer: {
position: 'absolute',
bottom: 25,
left: 40,
right: 40,
paddingTop: 10,
borderTop: '1 solid #dee2e6',
},
footerContent: {
flexDirection: 'row',
justifyContent: 'space-between',
},
footerLeft: {
maxWidth: '60%',
},
footerTitle: {
fontSize: 8,
fontWeight: 'bold',
color: '#2c3e50',
marginBottom: 3,
},
footerContact: {
fontSize: 7,
color: '#7f8c8d',
marginBottom: 1,
},
footerRight: {
textAlign: 'right',
},
pageNumber: {
fontSize: 7,
color: '#95a5a6',
},
// Empty state
emptyState: {
textAlign: 'center',
padding: 30,
color: '#95a5a6',
fontSize: 11,
},
});
const formatDepartment = (dept: string) => {
switch (dept) {
case 'OFFICE_OF_DEVELOPMENT':
return 'Office of Dev';
case 'ADMIN':
return 'Admin';
default:
return dept;
}
};
export function AccountabilityRosterPDF({
vips,
settings,
}: AccountabilityRosterPDFProps) {
const config = settings || {
organizationName: 'VIP Transportation Services',
accentColor: '#2c3e50',
contactEmail: 'coordinator@example.com',
contactPhone: '(555) 123-4567',
contactLabel: 'Questions or Changes?',
showDraftWatermark: false,
showConfidentialWatermark: false,
showTimestamp: true,
showAppUrl: false,
pageSize: 'LETTER' as const,
logoUrl: null,
tagline: null,
headerMessage: null,
footerMessage: null,
secondaryContactName: null,
secondaryContactPhone: null,
};
const styles = createStyles(config.accentColor, config.pageSize);
const generatedAt = new Date().toLocaleString('en-US', {
month: 'long',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: '2-digit',
});
const activeVips = vips.filter((v) => !v.isRosterOnly).sort((a, b) => a.name.localeCompare(b.name));
const rosterOnlyVips = vips.filter((v) => v.isRosterOnly).sort((a, b) => a.name.localeCompare(b.name));
const totalPeople = vips.reduce((sum, v) => sum + (v.partySize || 1), 0);
const activeCount = activeVips.reduce((sum, v) => sum + (v.partySize || 1), 0);
const rosterCount = rosterOnlyVips.reduce((sum, v) => sum + (v.partySize || 1), 0);
const renderTableHeader = () => (
<View style={styles.tableHeader}>
<View style={[styles.tableHeaderCell, styles.colName]}>
<Text>Name</Text>
</View>
<View style={[styles.tableHeaderCell, styles.colOrg]}>
<Text>Organization</Text>
</View>
<View style={[styles.tableHeaderCell, styles.colContact]}>
<Text>Contact</Text>
</View>
<View style={[styles.tableHeaderCell, styles.colEmergency]}>
<Text>Emergency Contact</Text>
</View>
<View style={[styles.tableHeaderCell, styles.colParty]}>
<Text>Party</Text>
</View>
</View>
);
const renderVipRow = (vip: VIP, index: number, isRoster: boolean) => (
<View
key={vip.id}
style={[
styles.tableRow,
isRoster
? index % 2 === 1 ? styles.tableRowRosterAlt : styles.tableRowRoster
: index % 2 === 1 ? styles.tableRowAlt : {},
]}
wrap={false}
>
<View style={[styles.tableCell, styles.colName]}>
<Text style={styles.cellName}>{vip.name}</Text>
<Text style={styles.cellDept}>{formatDepartment(vip.department)}</Text>
</View>
<View style={[styles.tableCell, styles.colOrg]}>
{vip.organization ? (
<Text style={styles.cellText}>{vip.organization}</Text>
) : (
<Text style={styles.cellNoData}>-</Text>
)}
</View>
<View style={[styles.tableCell, styles.colContact]}>
{vip.phone && <Text style={styles.cellText}>{vip.phone}</Text>}
{vip.email && <Text style={styles.cellSmall}>{vip.email}</Text>}
{!vip.phone && !vip.email && <Text style={styles.cellNoData}>No contact info</Text>}
</View>
<View style={[styles.tableCell, styles.colEmergency]}>
{vip.emergencyContactName ? (
<>
<Text style={styles.cellText}>{vip.emergencyContactName}</Text>
{vip.emergencyContactPhone && (
<Text style={styles.cellSmall}>{vip.emergencyContactPhone}</Text>
)}
</>
) : (
<Text style={styles.cellNoData}>Not provided</Text>
)}
</View>
<View style={[styles.tableCell, styles.colParty]}>
<Text style={styles.cellCenter}>{vip.partySize}</Text>
</View>
</View>
);
return (
<Document>
<Page size={config.pageSize} style={styles.page}>
{/* Watermarks */}
{config.showDraftWatermark && (
<View style={styles.watermark} fixed>
<Text>DRAFT</Text>
</View>
)}
{config.showConfidentialWatermark && (
<View style={styles.watermark} fixed>
<Text>CONFIDENTIAL</Text>
</View>
)}
{/* Header */}
<View style={styles.header}>
{config.logoUrl && (
<View style={styles.logoContainer}>
<Image src={config.logoUrl} style={styles.logo} />
</View>
)}
<Text style={styles.orgName}>{config.organizationName}</Text>
<Text style={styles.title}>Accountability Roster</Text>
<Text style={styles.subtitle}>Emergency Preparedness & Personnel Tracking</Text>
{config.headerMessage && (
<Text style={styles.customMessage}>{config.headerMessage}</Text>
)}
{(config.showTimestamp || config.showAppUrl) && (
<View style={styles.timestampBar}>
{config.showTimestamp && (
<Text style={styles.timestamp}>Generated: {generatedAt}</Text>
)}
{config.showAppUrl && (
<Text style={styles.timestamp}>
Latest version: {typeof window !== 'undefined' ? window.location.origin : ''}
</Text>
)}
</View>
)}
</View>
{/* Summary Stats */}
<View style={styles.summaryRow}>
<View style={styles.summaryCard}>
<Text style={styles.summaryValue}>{totalPeople}</Text>
<Text style={styles.summaryLabel}>Total People</Text>
</View>
<View style={styles.summaryCard}>
<Text style={styles.summaryValue}>{activeCount}</Text>
<Text style={styles.summaryLabel}>Active VIPs</Text>
</View>
<View style={styles.summaryCard}>
<Text style={styles.summaryValue}>{rosterCount}</Text>
<Text style={styles.summaryLabel}>Roster Only</Text>
</View>
</View>
{/* Active VIPs Table */}
{activeVips.length > 0 && (
<View style={styles.section}>
<Text style={styles.sectionTitle}>
Active VIPs ({activeVips.length} entries, {activeCount} people)
</Text>
<View style={styles.table}>
{renderTableHeader()}
{activeVips.map((vip, i) => renderVipRow(vip, i, false))}
</View>
</View>
)}
{/* Roster Only Table */}
{rosterOnlyVips.length > 0 && (
<View style={styles.section}>
<Text style={styles.sectionTitle}>
Roster Only ({rosterOnlyVips.length} entries, {rosterCount} people)
</Text>
<View style={styles.table}>
{renderTableHeader()}
{rosterOnlyVips.map((vip, i) => renderVipRow(vip, i, true))}
</View>
</View>
)}
{/* Empty State */}
{vips.length === 0 && (
<Text style={styles.emptyState}>No personnel records found.</Text>
)}
{/* Custom Footer Message */}
{config.footerMessage && (
<View style={styles.section}>
<Text style={styles.customMessage}>{config.footerMessage}</Text>
</View>
)}
{/* Footer */}
<View style={styles.footer} fixed>
<View style={styles.footerContent}>
<View style={styles.footerLeft}>
<Text style={styles.footerTitle}>{config.contactLabel}</Text>
<Text style={styles.footerContact}>{config.contactEmail}</Text>
<Text style={styles.footerContact}>{config.contactPhone}</Text>
{config.secondaryContactName && (
<Text style={styles.footerContact}>
{config.secondaryContactName}
{config.secondaryContactPhone ? ` - ${config.secondaryContactPhone}` : ''}
</Text>
)}
</View>
<View style={styles.footerRight}>
<Text
style={styles.pageNumber}
render={({ pageNumber, totalPages }) =>
`Page ${pageNumber} of ${totalPages}`
}
/>
</View>
</View>
</View>
</Page>
</Document>
);
}

View File

@@ -0,0 +1,90 @@
import { AlertTriangle } from 'lucide-react';
interface ConfirmModalProps {
isOpen: boolean;
onConfirm: () => void;
onCancel: () => void;
title: string;
description: string;
confirmLabel?: string;
cancelLabel?: string;
variant?: 'destructive' | 'warning' | 'default';
}
export function ConfirmModal({
isOpen,
onConfirm,
onCancel,
title,
description,
confirmLabel = 'Delete',
cancelLabel = 'Cancel',
variant = 'destructive',
}: ConfirmModalProps) {
if (!isOpen) return null;
const getConfirmButtonStyles = () => {
switch (variant) {
case 'destructive':
return 'bg-red-600 hover:bg-red-700 text-white';
case 'warning':
return 'bg-yellow-600 hover:bg-yellow-700 text-white';
case 'default':
return 'bg-primary hover:bg-primary/90 text-white';
default:
return 'bg-red-600 hover:bg-red-700 text-white';
}
};
return (
<div
className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50"
onClick={onCancel}
>
<div
className="bg-card rounded-lg shadow-xl w-full max-w-md"
onClick={(e) => e.stopPropagation()}
>
{/* Header with icon */}
<div className="flex items-start gap-4 p-6 pb-4">
<div className={`flex-shrink-0 ${
variant === 'destructive' ? 'text-red-600' :
variant === 'warning' ? 'text-yellow-600' :
'text-primary'
}`}>
<AlertTriangle className="h-6 w-6" />
</div>
<div className="flex-1">
<h2 className="text-lg font-semibold text-foreground mb-2">
{title}
</h2>
<p className="text-sm text-muted-foreground">
{description}
</p>
</div>
</div>
{/* Actions */}
<div className="flex gap-3 p-6 pt-4 border-t border-border">
<button
onClick={onCancel}
className="flex-1 bg-card text-foreground py-2.5 px-4 rounded-md hover:bg-accent font-medium border border-input transition-colors"
style={{ minHeight: '44px' }}
>
{cancelLabel}
</button>
<button
onClick={() => {
onConfirm();
onCancel();
}}
className={`flex-1 py-2.5 px-4 rounded-md font-medium transition-colors ${getConfirmButtonStyles()}`}
style={{ minHeight: '44px' }}
>
{confirmLabel}
</button>
</div>
</div>
</div>
);
}

View File

@@ -1,6 +1,7 @@
import { useState, useEffect, useRef } from 'react'; import { useState, useEffect, useRef } from 'react';
import { X, Send, Loader2 } from 'lucide-react'; import { X, Send, Loader2 } from 'lucide-react';
import { useDriverMessages, useSendMessage, useMarkMessagesAsRead } from '../hooks/useSignalMessages'; import { useDriverMessages, useSendMessage, useMarkMessagesAsRead } from '../hooks/useSignalMessages';
import { useFormattedDate } from '@/hooks/useFormattedDate';
interface Driver { interface Driver {
id: string; id: string;
@@ -18,6 +19,7 @@ export function DriverChatModal({ driver, isOpen, onClose }: DriverChatModalProp
const [message, setMessage] = useState(''); const [message, setMessage] = useState('');
const messagesEndRef = useRef<HTMLDivElement>(null); const messagesEndRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null); const inputRef = useRef<HTMLTextAreaElement>(null);
const { formatDateTime } = useFormattedDate();
const { data: messages, isLoading } = useDriverMessages(driver?.id || null, isOpen); const { data: messages, isLoading } = useDriverMessages(driver?.id || null, isOpen);
const sendMessage = useSendMessage(); const sendMessage = useSendMessage();
@@ -66,22 +68,6 @@ export function DriverChatModal({ driver, isOpen, onClose }: DriverChatModalProp
} }
}; };
const formatTime = (timestamp: string) => {
const date = new Date(timestamp);
const now = new Date();
const isToday = date.toDateString() === now.toDateString();
if (isToday) {
return date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
}
return date.toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: '2-digit'
});
};
return ( return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50"> <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
<div <div
@@ -126,7 +112,7 @@ export function DriverChatModal({ driver, isOpen, onClose }: DriverChatModalProp
<p className={`text-[10px] mt-1 ${ <p className={`text-[10px] mt-1 ${
msg.direction === 'OUTBOUND' ? 'text-primary-foreground/70' : 'text-muted-foreground/70' msg.direction === 'OUTBOUND' ? 'text-primary-foreground/70' : 'text-muted-foreground/70'
}`}> }`}>
{formatTime(msg.timestamp)} {formatDateTime(msg.timestamp)}
</p> </p>
</div> </div>
</div> </div>

View File

@@ -1,5 +1,6 @@
import { useState } from 'react'; import { useState } from 'react';
import { X } from 'lucide-react'; import { X } from 'lucide-react';
import { DEPARTMENT_LABELS } from '@/lib/enum-labels';
interface DriverFormProps { interface DriverFormProps {
driver?: Driver | null; driver?: Driver | null;
@@ -112,8 +113,11 @@ export function DriverForm({ driver, onSubmit, onCancel, isSubmitting }: DriverF
className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary" className="w-full px-3 py-2 border border-input rounded-md bg-background text-foreground focus:outline-none focus:ring-2 focus:ring-primary"
> >
<option value="">Select Department</option> <option value="">Select Department</option>
<option value="OFFICE_OF_DEVELOPMENT">Office of Development</option> {Object.entries(DEPARTMENT_LABELS).map(([value, label]) => (
<option value="ADMIN">Admin</option> <option key={value} value={value}>
{label}
</option>
))}
</select> </select>
</div> </div>

View File

@@ -0,0 +1,147 @@
import { X, Navigation, Battery, Compass, Clock } from 'lucide-react';
import { MapContainer, TileLayer, Marker } from 'react-leaflet';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { formatDistanceToNow } from 'date-fns';
import type { DriverLocation } from '@/types/gps';
interface DriverLocationModalProps {
driverLocation: DriverLocation | null;
isOpen: boolean;
onClose: () => void;
}
// Custom driver marker icon (same as GpsTracking page)
const createDriverIcon = () => {
return L.divIcon({
className: 'custom-driver-marker',
html: `
<div style="
background-color: #22c55e;
width: 32px;
height: 32px;
border-radius: 50%;
border: 3px solid white;
box-shadow: 0 2px 4px rgba(0,0,0,0.3);
display: flex;
align-items: center;
justify-content: center;
">
<svg width="16" height="16" viewBox="0 0 24 24" fill="white">
<path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/>
</svg>
</div>
`,
iconSize: [32, 32],
iconAnchor: [16, 32],
popupAnchor: [0, -32],
});
};
function getCourseDirection(course: number | null): string {
if (course === null || course === undefined) return 'N/A';
const directions = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'];
const index = Math.round(course / 45) % 8;
return `${directions[index]} (${Math.round(course)}°)`;
}
export function DriverLocationModal({ driverLocation, isOpen, onClose }: DriverLocationModalProps) {
if (!isOpen || !driverLocation) return null;
const hasLocation = driverLocation.location !== null;
return (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div className="bg-card border border-border rounded-lg shadow-lg w-full max-w-lg overflow-hidden">
{/* Header */}
<div className="flex justify-between items-center p-4 border-b border-border">
<div>
<h3 className="text-lg font-semibold text-foreground">{driverLocation.driverName}</h3>
{driverLocation.driverPhone && (
<p className="text-sm text-muted-foreground">{driverLocation.driverPhone}</p>
)}
</div>
<button
onClick={onClose}
className="text-muted-foreground hover:text-foreground transition-colors p-1 rounded hover:bg-accent"
>
<X className="h-5 w-5" />
</button>
</div>
{/* Map */}
{hasLocation ? (
<>
<div className="h-[300px]">
<MapContainer
key={driverLocation.driverId}
center={[driverLocation.location!.latitude, driverLocation.location!.longitude]}
zoom={16}
style={{ height: '100%', width: '100%' }}
zoomControl={true}
>
<TileLayer
attribution='Tiles &copy; Esri'
url="https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}"
maxZoom={19}
/>
<Marker
position={[driverLocation.location!.latitude, driverLocation.location!.longitude]}
icon={createDriverIcon()}
/>
</MapContainer>
</div>
{/* Info Grid */}
<div className="p-4 grid grid-cols-2 gap-3">
<div className="flex items-center gap-2">
<Navigation className="h-4 w-4 text-blue-500 flex-shrink-0" />
<div>
<p className="text-xs text-muted-foreground">Speed</p>
<p className="text-sm font-medium text-foreground">
{driverLocation.location!.speed?.toFixed(1) || '0'} mph
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Compass className="h-4 w-4 text-indigo-500 flex-shrink-0" />
<div>
<p className="text-xs text-muted-foreground">Heading</p>
<p className="text-sm font-medium text-foreground">
{getCourseDirection(driverLocation.location!.course)}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Battery className="h-4 w-4 text-green-500 flex-shrink-0" />
<div>
<p className="text-xs text-muted-foreground">Battery</p>
<p className="text-sm font-medium text-foreground">
{driverLocation.location!.battery !== null
? `${Math.round(driverLocation.location!.battery)}%`
: 'N/A'}
</p>
</div>
</div>
<div className="flex items-center gap-2">
<Clock className="h-4 w-4 text-gray-500 flex-shrink-0" />
<div>
<p className="text-xs text-muted-foreground">Last Seen</p>
<p className="text-sm font-medium text-foreground">
{formatDistanceToNow(new Date(driverLocation.location!.timestamp), { addSuffix: true })}
</p>
</div>
</div>
</div>
</>
) : (
<div className="p-8 text-center text-muted-foreground">
<Navigation className="h-10 w-10 mx-auto mb-3 opacity-30" />
<p className="text-sm">No location data available for this driver.</p>
<p className="text-xs mt-1">The driver may not have reported their position yet.</p>
</div>
)}
</div>
</div>
);
}

View File

@@ -3,6 +3,7 @@ import { api } from '@/lib/api';
import { X, Calendar, Clock, MapPin, Car, User, ChevronLeft, ChevronRight } from 'lucide-react'; import { X, Calendar, Clock, MapPin, Car, User, ChevronLeft, ChevronRight } from 'lucide-react';
import { Driver } from '@/types'; import { Driver } from '@/types';
import { useState } from 'react'; import { useState } from 'react';
import { useFormattedDate } from '@/hooks/useFormattedDate';
interface ScheduleEvent { interface ScheduleEvent {
id: string; id: string;
@@ -36,6 +37,7 @@ interface DriverScheduleModalProps {
export function DriverScheduleModal({ driver, isOpen, onClose }: DriverScheduleModalProps) { export function DriverScheduleModal({ driver, isOpen, onClose }: DriverScheduleModalProps) {
const [selectedDate, setSelectedDate] = useState(new Date()); const [selectedDate, setSelectedDate] = useState(new Date());
const { formatDate, formatTime } = useFormattedDate();
const dateString = selectedDate.toISOString().split('T')[0]; const dateString = selectedDate.toISOString().split('T')[0];
@@ -85,23 +87,6 @@ export function DriverScheduleModal({ driver, isOpen, onClose }: DriverScheduleM
const isToday = selectedDate.toDateString() === new Date().toDateString(); const isToday = selectedDate.toDateString() === new Date().toDateString();
const formatTime = (dateString: string) => {
return new Date(dateString).toLocaleTimeString('en-US', {
hour: 'numeric',
minute: '2-digit',
hour12: true,
});
};
const formatDate = (date: Date) => {
return date.toLocaleDateString('en-US', {
weekday: 'long',
month: 'long',
day: 'numeric',
year: 'numeric',
});
};
const getStatusColor = (status: string) => { const getStatusColor = (status: string) => {
switch (status) { switch (status) {
case 'COMPLETED': case 'COMPLETED':

View File

@@ -1,10 +1,13 @@
import { useState, useEffect } from 'react'; import { useState, useMemo } from 'react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { X, AlertTriangle, Users, Car } from 'lucide-react'; import { X, AlertTriangle, Users, Car, Link2 } from 'lucide-react';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { ScheduleEvent, VIP, Driver, Vehicle } from '@/types'; import { ScheduleEvent, VIP, Driver, Vehicle } from '@/types';
import { formatDateTime } from '@/lib/utils'; import { useFormattedDate } from '@/hooks/useFormattedDate';
import { toDatetimeLocal } from '@/lib/utils';
import { EVENT_TYPE_LABELS, EVENT_STATUS_LABELS } from '@/lib/enum-labels';
import { queryKeys } from '@/lib/query-keys';
interface EventFormProps { interface EventFormProps {
event?: ScheduleEvent | null; event?: ScheduleEvent | null;
@@ -27,6 +30,7 @@ export interface EventFormData {
status: string; status: string;
driverId?: string; driverId?: string;
vehicleId?: string; vehicleId?: string;
masterEventId?: string;
forceAssign?: boolean; forceAssign?: boolean;
} }
@@ -38,17 +42,7 @@ interface ScheduleConflict {
} }
export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraActions }: EventFormProps) { export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraActions }: EventFormProps) {
// Helper to convert ISO datetime to datetime-local format const { formatDateTime } = useFormattedDate();
const toDatetimeLocal = (isoString: string | null | undefined) => {
if (!isoString) return '';
const date = new Date(isoString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
};
const [formData, setFormData] = useState<EventFormData>({ const [formData, setFormData] = useState<EventFormData>({
vipIds: event?.vipIds || [], vipIds: event?.vipIds || [],
@@ -63,6 +57,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
status: event?.status || 'SCHEDULED', status: event?.status || 'SCHEDULED',
driverId: event?.driverId || '', driverId: event?.driverId || '',
vehicleId: event?.vehicleId || '', vehicleId: event?.vehicleId || '',
masterEventId: event?.masterEventId || '',
}); });
const [showConflictDialog, setShowConflictDialog] = useState(false); const [showConflictDialog, setShowConflictDialog] = useState(false);
@@ -73,7 +68,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
// Fetch VIPs for selection // Fetch VIPs for selection
const { data: vips } = useQuery<VIP[]>({ const { data: vips } = useQuery<VIP[]>({
queryKey: ['vips'], queryKey: queryKeys.vips.all,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/vips'); const { data } = await api.get('/vips');
return data; return data;
@@ -82,7 +77,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
// Fetch Drivers for dropdown // Fetch Drivers for dropdown
const { data: drivers } = useQuery<Driver[]>({ const { data: drivers } = useQuery<Driver[]>({
queryKey: ['drivers'], queryKey: queryKeys.drivers.all,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/drivers'); const { data } = await api.get('/drivers');
return data; return data;
@@ -91,16 +86,37 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
// Fetch Vehicles for dropdown // Fetch Vehicles for dropdown
const { data: vehicles } = useQuery<Vehicle[]>({ const { data: vehicles } = useQuery<Vehicle[]>({
queryKey: ['vehicles'], queryKey: queryKeys.vehicles.all,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/vehicles'); const { data } = await api.get('/vehicles');
return data; return data;
}, },
}); });
// Get selected vehicle capacity // Fetch all events (for master event selector)
const { data: allEvents } = useQuery<ScheduleEvent[]>({
queryKey: queryKeys.events.all,
queryFn: async () => {
const { data } = await api.get('/events');
return data;
},
});
// Filter to itinerary items (non-transport events) for master event dropdown
const masterEventOptions = useMemo(() => {
if (!allEvents) return [];
return allEvents.filter(e =>
e.type !== 'TRANSPORT' &&
e.status !== 'CANCELLED' &&
e.id !== event?.id // Exclude self
);
}, [allEvents, event?.id]);
// Get selected vehicle capacity (using party sizes)
const selectedVehicle = vehicles?.find(v => v.id === formData.vehicleId); const selectedVehicle = vehicles?.find(v => v.id === formData.vehicleId);
const seatsUsed = formData.vipIds.length; const seatsUsed = vips
?.filter(v => formData.vipIds.includes(v.id))
.reduce((sum, v) => sum + (v.partySize || 1), 0) || 0;
const seatsAvailable = selectedVehicle ? selectedVehicle.seatCapacity : 0; const seatsAvailable = selectedVehicle ? selectedVehicle.seatCapacity : 0;
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
@@ -117,6 +133,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
description: formData.description || undefined, description: formData.description || undefined,
driverId: formData.driverId || undefined, driverId: formData.driverId || undefined,
vehicleId: formData.vehicleId || undefined, vehicleId: formData.vehicleId || undefined,
masterEventId: formData.masterEventId || undefined,
}; };
// Store for potential retry // Store for potential retry
@@ -193,10 +210,12 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
}); });
}; };
const selectedVipNames = vips const selectedVipNames = useMemo(() => {
return vips
?.filter(vip => formData.vipIds.includes(vip.id)) ?.filter(vip => formData.vipIds.includes(vip.id))
.map(vip => vip.name) .map(vip => vip.partySize > 1 ? `${vip.name} (+${vip.partySize - 1})` : vip.name)
.join(', ') || 'None selected'; .join(', ') || 'None selected';
}, [vips, formData.vipIds]);
return ( return (
<> <>
@@ -216,6 +235,42 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
</div> </div>
<form onSubmit={handleSubmit} className="p-6 space-y-4"> <form onSubmit={handleSubmit} className="p-6 space-y-4">
{/* Master Event Selector (link transport to itinerary item) */}
{formData.type === 'TRANSPORT' && masterEventOptions.length > 0 && (
<div>
<label className="block text-sm font-medium text-foreground mb-1">
<Link2 className="inline h-4 w-4 mr-1" />
Linked Itinerary Item (optional)
</label>
<select
name="masterEventId"
value={formData.masterEventId}
onChange={(e) => {
const selectedId = e.target.value;
setFormData(prev => ({ ...prev, masterEventId: selectedId }));
// Auto-fill VIPs from the selected master event
if (selectedId) {
const masterEvent = allEvents?.find(ev => ev.id === selectedId);
if (masterEvent?.vipIds && masterEvent.vipIds.length > 0) {
setFormData(prev => ({ ...prev, masterEventId: selectedId, vipIds: masterEvent.vipIds }));
}
}
}}
className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
>
<option value="">No linked event</option>
{masterEventOptions.map(ev => (
<option key={ev.id} value={ev.id}>
{ev.title} ({ev.type}) {formatDateTime(ev.startTime)}
</option>
))}
</select>
<p className="mt-1 text-xs text-muted-foreground">
Link this transport to a shared activity. VIPs will auto-populate from the linked event.
</p>
</div>
)}
{/* VIP Multi-Select */} {/* VIP Multi-Select */}
<div> <div>
<label className="block text-sm font-medium text-foreground mb-2"> <label className="block text-sm font-medium text-foreground mb-2">
@@ -238,6 +293,9 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
/> />
<span className="ml-3 text-base text-foreground"> <span className="ml-3 text-base text-foreground">
{vip.name} {vip.name}
{vip.partySize > 1 && (
<span className="text-xs text-blue-600 dark:text-blue-400 ml-1.5 font-medium">+{vip.partySize - 1}</span>
)}
{vip.organization && ( {vip.organization && (
<span className="text-sm text-muted-foreground ml-2">({vip.organization})</span> <span className="text-sm text-muted-foreground ml-2">({vip.organization})</span>
)} )}
@@ -348,8 +406,8 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
</select> </select>
{selectedVehicle && ( {selectedVehicle && (
<div className={`mt-2 text-sm ${seatsUsed > seatsAvailable ? 'text-red-600 font-medium' : 'text-muted-foreground'}`}> <div className={`mt-2 text-sm ${seatsUsed > seatsAvailable ? 'text-red-600 font-medium' : 'text-muted-foreground'}`}>
Capacity: {seatsUsed}/{seatsAvailable} seats used Capacity: {seatsUsed}/{seatsAvailable} seats (incl. entourage)
{seatsUsed > seatsAvailable && ' ⚠️ OVER CAPACITY'} {seatsUsed > seatsAvailable && ' OVER CAPACITY'}
</div> </div>
)} )}
</div> </div>
@@ -387,11 +445,11 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
onChange={handleChange} onChange={handleChange}
className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary" className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
> >
<option value="TRANSPORT">Transport</option> {Object.entries(EVENT_TYPE_LABELS).map(([value, label]) => (
<option value="MEETING">Meeting</option> <option key={value} value={value}>
<option value="EVENT">Event</option> {label}
<option value="MEAL">Meal</option> </option>
<option value="ACCOMMODATION">Accommodation</option> ))}
</select> </select>
</div> </div>
<div> <div>
@@ -405,10 +463,11 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
onChange={handleChange} onChange={handleChange}
className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary" className="w-full px-3 py-2 bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
> >
<option value="SCHEDULED">Scheduled</option> {Object.entries(EVENT_STATUS_LABELS).map(([value, label]) => (
<option value="IN_PROGRESS">In Progress</option> <option key={value} value={value}>
<option value="COMPLETED">Completed</option> {label}
<option value="CANCELLED">Cancelled</option> </option>
))}
</select> </select>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,467 @@
import { useState } from 'react';
import {
Plane,
RefreshCw,
Edit3,
Trash2,
AlertTriangle,
Clock,
ChevronDown,
ChevronUp,
Users,
CheckCircle,
Link2,
XCircle,
} from 'lucide-react';
import { Flight, Journey, Layover } from '@/types';
import { FlightProgressBar } from './FlightProgressBar';
import { useRefreshFlight } from '@/hooks/useFlights';
import { formatLayoverDuration } from '@/lib/journeyUtils';
import { useFormattedDate } from '@/hooks/useFormattedDate';
interface FlightCardProps {
flight?: Flight;
journey?: Journey;
onEdit?: (flight: Flight) => void;
onDelete?: (flight: Flight) => void;
}
function getStatusDotColor(flight: Flight): string {
const status = flight.status?.toLowerCase();
const delay = flight.arrivalDelay || flight.departureDelay || 0;
if (status === 'cancelled') return 'bg-red-500';
if (status === 'diverted' || status === 'incident') return 'bg-red-500';
if (status === 'landed') return 'bg-emerald-500';
if (status === 'active') return delay > 15 ? 'bg-amber-500 animate-pulse' : 'bg-purple-500 animate-pulse';
if (delay > 30) return 'bg-orange-500';
if (delay > 15) return 'bg-amber-500';
return 'bg-blue-500';
}
function getAlertBanner(flight: Flight): { message: string; color: string } | null {
const status = flight.status?.toLowerCase();
const delay = Math.max(flight.arrivalDelay || 0, flight.departureDelay || 0);
if (status === 'cancelled') return { message: 'FLIGHT CANCELLED', color: 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400' };
if (status === 'diverted') return { message: 'FLIGHT DIVERTED', color: 'bg-orange-500/10 border-orange-500/30 text-orange-700 dark:text-orange-400' };
if (status === 'incident') return { message: 'INCIDENT REPORTED', color: 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400' };
if (delay > 60) return { message: `DELAYED ${delay} MINUTES`, color: 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400' };
if (delay > 30) return { message: `Delayed ${delay} min`, color: 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400' };
return null;
}
function formatRelativeTime(isoString: string | null): string {
if (!isoString) return 'Never';
const diff = Date.now() - new Date(isoString).getTime();
const minutes = Math.floor(diff / 60000);
if (minutes < 1) return 'Just now';
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
return `${Math.floor(hours / 24)}d ago`;
}
function getSegmentStatusIcon(flight: Flight) {
const status = flight.status?.toLowerCase();
if (status === 'landed' || flight.actualArrival) {
return <CheckCircle className="w-3.5 h-3.5 text-emerald-500" />;
}
if (status === 'active') {
return <Plane className="w-3.5 h-3.5 text-purple-500" />;
}
if (status === 'cancelled' || status === 'diverted') {
return <XCircle className="w-3.5 h-3.5 text-red-500" />;
}
return <Clock className="w-3.5 h-3.5 text-muted-foreground" />;
}
function LayoverRow({ layover }: { layover: Layover }) {
const riskColors = {
none: 'text-muted-foreground',
ok: 'text-muted-foreground',
warning: 'bg-amber-50 dark:bg-amber-950/20 text-amber-700 dark:text-amber-400',
critical: 'bg-red-50 dark:bg-red-950/20 text-red-700 dark:text-red-400',
missed: 'bg-red-100 dark:bg-red-950/30 text-red-800 dark:text-red-300',
};
const isBadge = layover.risk === 'warning' || layover.risk === 'critical' || layover.risk === 'missed';
return (
<div className={`flex items-center gap-2 px-4 py-1.5 text-xs ${isBadge ? riskColors[layover.risk] : ''}`}>
<div className="flex items-center gap-1.5 ml-6">
<div className="w-px h-3 bg-border" />
<Link2 className="w-3 h-3 text-muted-foreground/50" />
</div>
<div className="flex items-center gap-2 flex-1">
<span className={isBadge ? 'font-medium' : 'text-muted-foreground'}>
{layover.risk === 'missed' ? (
<>CONNECTION MISSED at {layover.airport} - arrived {formatLayoverDuration(layover.effectiveMinutes)}</>
) : (
<>{formatLayoverDuration(layover.scheduledMinutes)} layover at {layover.airport}</>
)}
</span>
{layover.risk === 'warning' && layover.effectiveMinutes !== layover.scheduledMinutes && (
<span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-amber-100 dark:bg-amber-900/30 text-amber-800 dark:text-amber-300 text-[10px] font-semibold">
<AlertTriangle className="w-2.5 h-2.5" />
now {formatLayoverDuration(layover.effectiveMinutes)}
</span>
)}
{layover.risk === 'critical' && (
<span className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-red-100 dark:bg-red-900/30 text-red-800 dark:text-red-300 text-[10px] font-semibold">
<AlertTriangle className="w-2.5 h-2.5" />
only {formatLayoverDuration(layover.effectiveMinutes)} remaining
</span>
)}
</div>
</div>
);
}
// ============================================================
// SINGLE FLIGHT CARD (original behavior)
// ============================================================
function SingleFlightCard({ flight, onEdit, onDelete }: { flight: Flight; onEdit?: (f: Flight) => void; onDelete?: (f: Flight) => void }) {
const [expanded, setExpanded] = useState(false);
const refreshMutation = useRefreshFlight();
const alert = getAlertBanner(flight);
const dotColor = getStatusDotColor(flight);
const { formatDateTime } = useFormattedDate();
return (
<div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden transition-shadow hover:shadow-medium">
{alert && (
<div className={`px-4 py-1.5 text-xs font-semibold border-b flex items-center gap-2 ${alert.color}`}>
<AlertTriangle className="w-3.5 h-3.5" />
{alert.message}
</div>
)}
<div className="px-4 pt-3 pb-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5">
<div className={`w-2.5 h-2.5 rounded-full ${dotColor}`} />
<div className="flex items-center gap-2">
<span className="font-bold text-foreground">{flight.flightNumber}</span>
{flight.airlineName && (
<span className="text-xs text-muted-foreground">{flight.airlineName}</span>
)}
</div>
{flight.vip && (
<div className="flex items-center gap-1 text-sm text-muted-foreground">
<span className="text-muted-foreground/50">|</span>
<span className="font-medium text-foreground/80">{flight.vip.name}</span>
{flight.vip.partySize > 1 && (
<span className="flex items-center gap-0.5 text-xs text-muted-foreground">
<Users className="w-3 h-3" />
+{flight.vip.partySize - 1}
</span>
)}
</div>
)}
</div>
<div className="flex items-center gap-1">
<button
onClick={() => refreshMutation.mutate(flight.id)}
disabled={refreshMutation.isPending}
className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50"
title="Refresh from API"
>
<RefreshCw className={`w-4 h-4 ${refreshMutation.isPending ? 'animate-spin' : ''}`} />
</button>
{onEdit && (
<button onClick={() => onEdit(flight)} className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-foreground" title="Edit flight">
<Edit3 className="w-4 h-4" />
</button>
)}
{onDelete && (
<button onClick={() => onDelete(flight)} className="p-1.5 rounded-md hover:bg-accent transition-colors text-muted-foreground hover:text-red-500" title="Delete flight">
<Trash2 className="w-4 h-4" />
</button>
)}
</div>
</div>
</div>
<div className="px-4">
<FlightProgressBar flight={flight} />
</div>
<div className="px-4 pb-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full flex items-center justify-between py-1 text-xs text-muted-foreground hover:text-foreground transition-colors"
>
<div className="flex items-center gap-3">
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
Updated {formatRelativeTime(flight.lastPolledAt)}
</span>
{flight.pollCount > 0 && (
<span>{flight.pollCount} poll{flight.pollCount !== 1 ? 's' : ''}</span>
)}
<span className="px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
{flight.trackingPhase.replace(/_/g, ' ')}
</span>
</div>
{expanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />}
</button>
{expanded && (
<div className="pt-2 pb-1 border-t border-border/50 space-y-2 text-xs">
<div className="grid grid-cols-2 gap-4">
<div>
<div className="font-medium text-foreground mb-1">Departure</div>
<div className="space-y-0.5 text-muted-foreground">
{flight.scheduledDeparture && <div>Scheduled: {formatDateTime(flight.scheduledDeparture)}</div>}
{flight.estimatedDeparture && <div>Estimated: {formatDateTime(flight.estimatedDeparture)}</div>}
{flight.actualDeparture && <div className="text-foreground">Actual: {formatDateTime(flight.actualDeparture)}</div>}
{flight.departureDelay != null && flight.departureDelay > 0 && (
<div className="text-amber-600 dark:text-amber-400">Delay: {flight.departureDelay} min</div>
)}
{flight.departureTerminal && <div>Terminal: {flight.departureTerminal}</div>}
{flight.departureGate && <div>Gate: {flight.departureGate}</div>}
</div>
</div>
<div>
<div className="font-medium text-foreground mb-1">Arrival</div>
<div className="space-y-0.5 text-muted-foreground">
{flight.scheduledArrival && <div>Scheduled: {formatDateTime(flight.scheduledArrival)}</div>}
{flight.estimatedArrival && <div>Estimated: {formatDateTime(flight.estimatedArrival)}</div>}
{flight.actualArrival && <div className="text-foreground">Actual: {formatDateTime(flight.actualArrival)}</div>}
{flight.arrivalDelay != null && flight.arrivalDelay > 0 && (
<div className="text-amber-600 dark:text-amber-400">Delay: {flight.arrivalDelay} min</div>
)}
{flight.arrivalTerminal && <div>Terminal: {flight.arrivalTerminal}</div>}
{flight.arrivalGate && <div>Gate: {flight.arrivalGate}</div>}
{flight.arrivalBaggage && <div>Baggage: {flight.arrivalBaggage}</div>}
</div>
</div>
</div>
{flight.aircraftType && (
<div className="text-muted-foreground">Aircraft: {flight.aircraftType}</div>
)}
</div>
)}
</div>
</div>
);
}
// ============================================================
// MULTI-SEGMENT JOURNEY CARD
// ============================================================
function JourneyCard({ journey, onEdit, onDelete }: { journey: Journey; onEdit?: (f: Flight) => void; onDelete?: (f: Flight) => void }) {
const [expandedSeg, setExpandedSeg] = useState<number | null>(null);
const refreshMutation = useRefreshFlight();
const currentFlight = journey.flights[journey.currentSegmentIndex];
const dotColor = getStatusDotColor(currentFlight);
const vip = journey.vip || currentFlight?.vip;
const { formatDateTime } = useFormattedDate();
// Route chain: BWI -> ORD -> SLC
const routeChain = [journey.origin, ...journey.flights.slice(1).map(f => f.departureAirport), journey.destination]
.filter((v, i, a) => a.indexOf(v) === i); // dedupe
// Connection risk banner
const worstLayover = journey.layovers.reduce<Layover | null>((worst, l) => {
if (!worst) return l;
if (l.risk === 'missed') return l;
if (l.risk === 'critical' && worst.risk !== 'missed') return l;
if (l.risk === 'warning' && worst.risk !== 'missed' && worst.risk !== 'critical') return l;
return worst;
}, null);
const connectionBanner = worstLayover && (worstLayover.risk === 'warning' || worstLayover.risk === 'critical' || worstLayover.risk === 'missed')
? {
message: worstLayover.risk === 'missed'
? `CONNECTION MISSED at ${worstLayover.airport}`
: worstLayover.risk === 'critical'
? `CONNECTION AT RISK - only ${formatLayoverDuration(worstLayover.effectiveMinutes)} at ${worstLayover.airport}`
: `Connection tight - ${formatLayoverDuration(worstLayover.effectiveMinutes)} at ${worstLayover.airport}`,
color: worstLayover.risk === 'missed'
? 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400'
: worstLayover.risk === 'critical'
? 'bg-red-500/10 border-red-500/30 text-red-700 dark:text-red-400'
: 'bg-amber-500/10 border-amber-500/30 text-amber-700 dark:text-amber-400',
}
: null;
return (
<div className="bg-card border border-border rounded-lg shadow-soft overflow-hidden transition-shadow hover:shadow-medium">
{/* Connection risk banner */}
{connectionBanner && (
<div className={`px-4 py-1.5 text-xs font-semibold border-b flex items-center gap-2 ${connectionBanner.color}`}>
<AlertTriangle className="w-3.5 h-3.5" />
{connectionBanner.message}
</div>
)}
{/* Journey header */}
<div className="px-4 pt-3 pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2.5">
<div className={`w-2.5 h-2.5 rounded-full ${dotColor}`} />
{vip && (
<div className="flex items-center gap-1.5">
<span className="font-bold text-foreground">{vip.name}</span>
{vip.partySize > 1 && (
<span className="flex items-center gap-0.5 text-xs text-muted-foreground">
<Users className="w-3 h-3" />
+{vip.partySize - 1}
</span>
)}
</div>
)}
</div>
{/* Route chain */}
<div className="flex items-center gap-1 text-xs text-muted-foreground">
{routeChain.map((code, i) => (
<span key={i} className="flex items-center gap-1">
{i > 0 && <span className="text-muted-foreground/40">{'→'}</span>}
<span className={i === 0 || i === routeChain.length - 1 ? 'font-bold text-foreground' : ''}>{code}</span>
</span>
))}
<span className="ml-1 px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
{journey.flights.length} legs
</span>
</div>
</div>
</div>
{/* Segment stack */}
{journey.flights.map((seg, i) => {
const isExpanded = expandedSeg === i;
const isCurrent = i === journey.currentSegmentIndex;
return (
<div key={seg.id}>
{/* Layover row between segments */}
{i > 0 && journey.layovers[i - 1] && (
<LayoverRow layover={journey.layovers[i - 1]} />
)}
{/* Segment row */}
<div className={`px-4 py-2 ${isCurrent ? 'bg-accent/30' : ''}`}>
<div className="flex items-center gap-2">
{/* Leg label + status icon */}
<div className="flex items-center gap-1.5 min-w-[60px]">
<span className="text-[10px] font-semibold text-muted-foreground uppercase">Leg {i + 1}</span>
{getSegmentStatusIcon(seg)}
</div>
{/* Compact progress bar */}
<div className="flex-1">
<FlightProgressBar flight={seg} compact />
</div>
{/* Flight number + actions */}
<div className="flex items-center gap-1.5 flex-shrink-0">
<span className="text-xs font-medium text-muted-foreground">{seg.flightNumber}</span>
<button
onClick={() => refreshMutation.mutate(seg.id)}
disabled={refreshMutation.isPending}
className="p-1 rounded hover:bg-accent transition-colors text-muted-foreground hover:text-foreground disabled:opacity-50"
title="Refresh"
>
<RefreshCw className={`w-3 h-3 ${refreshMutation.isPending ? 'animate-spin' : ''}`} />
</button>
<button
onClick={() => setExpandedSeg(isExpanded ? null : i)}
className="p-1 rounded hover:bg-accent transition-colors text-muted-foreground"
>
{isExpanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
</button>
</div>
</div>
{/* Terminal/gate info for current segment */}
{isCurrent && (seg.arrivalTerminal || seg.arrivalGate || seg.arrivalBaggage) && (
<div className="flex gap-3 mt-1 ml-[68px] text-[10px] text-muted-foreground">
{seg.arrivalTerminal && <span>Terminal {seg.arrivalTerminal}</span>}
{seg.arrivalGate && <span>Gate {seg.arrivalGate}</span>}
{seg.arrivalBaggage && <span>Baggage {seg.arrivalBaggage}</span>}
</div>
)}
{/* Expanded details */}
{isExpanded && (
<div className="mt-2 pt-2 border-t border-border/50 text-xs">
<div className="grid grid-cols-2 gap-4">
<div>
<div className="font-medium text-foreground mb-1">Departure</div>
<div className="space-y-0.5 text-muted-foreground">
{seg.scheduledDeparture && <div>Scheduled: {formatDateTime(seg.scheduledDeparture)}</div>}
{seg.actualDeparture && <div className="text-foreground">Actual: {formatDateTime(seg.actualDeparture)}</div>}
{seg.departureDelay != null && seg.departureDelay > 0 && (
<div className="text-amber-600 dark:text-amber-400">Delay: {seg.departureDelay} min</div>
)}
{seg.departureTerminal && <div>Terminal: {seg.departureTerminal}</div>}
{seg.departureGate && <div>Gate: {seg.departureGate}</div>}
</div>
</div>
<div>
<div className="font-medium text-foreground mb-1">Arrival</div>
<div className="space-y-0.5 text-muted-foreground">
{seg.scheduledArrival && <div>Scheduled: {formatDateTime(seg.scheduledArrival)}</div>}
{seg.actualArrival && <div className="text-foreground">Actual: {formatDateTime(seg.actualArrival)}</div>}
{seg.arrivalDelay != null && seg.arrivalDelay > 0 && (
<div className="text-amber-600 dark:text-amber-400">Delay: {seg.arrivalDelay} min</div>
)}
{seg.arrivalTerminal && <div>Terminal: {seg.arrivalTerminal}</div>}
{seg.arrivalGate && <div>Gate: {seg.arrivalGate}</div>}
{seg.arrivalBaggage && <div>Baggage: {seg.arrivalBaggage}</div>}
</div>
</div>
</div>
<div className="flex items-center gap-3 mt-2">
{onEdit && (
<button onClick={() => onEdit(seg)} className="text-xs text-blue-600 hover:text-blue-800 dark:text-blue-400">Edit</button>
)}
{onDelete && (
<button onClick={() => onDelete(seg)} className="text-xs text-red-600 hover:text-red-800 dark:text-red-400">Delete</button>
)}
</div>
</div>
)}
</div>
</div>
);
})}
{/* Footer */}
<div className="px-4 py-1.5 border-t border-border/50 text-xs text-muted-foreground flex items-center gap-3">
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
Updated {formatRelativeTime(currentFlight?.lastPolledAt)}
</span>
<span className="px-1.5 py-0.5 rounded bg-muted text-[10px] uppercase tracking-wider font-medium">
{journey.effectiveStatus}
</span>
</div>
</div>
);
}
// ============================================================
// EXPORT: Routes to single or journey card
// ============================================================
export function FlightCard({ flight, journey, onEdit, onDelete }: FlightCardProps) {
if (journey) {
// Multi-segment journeys always use JourneyCard, single-segment journeys too when passed as journey
if (journey.isMultiSegment) {
return <JourneyCard journey={journey} onEdit={onEdit} onDelete={onDelete} />;
}
// Single-segment journey: render as single flight card
return <SingleFlightCard flight={journey.flights[0]} onEdit={onEdit} onDelete={onDelete} />;
}
if (flight) {
return <SingleFlightCard flight={flight} onEdit={onEdit} onDelete={onDelete} />;
}
return null;
}

View File

@@ -0,0 +1,237 @@
import { useMemo, useEffect, useState } from 'react';
import { Plane } from 'lucide-react';
import { Flight } from '@/types';
import { useFormattedDate } from '@/hooks/useFormattedDate';
interface FlightProgressBarProps {
flight: Flight;
compact?: boolean; // For mini version in dashboard/command center
}
function calculateProgress(flight: Flight): number {
const status = flight.status?.toLowerCase();
// Terminal states
if (status === 'landed' || flight.actualArrival) return 100;
if (status === 'cancelled' || status === 'diverted' || status === 'incident') return 0;
// Not departed yet
if (status === 'scheduled' || (!flight.actualDeparture && !status?.includes('active'))) {
return 0;
}
// In flight - calculate based on time elapsed
const departureTime = flight.actualDeparture || flight.estimatedDeparture || flight.scheduledDeparture;
const arrivalTime = flight.estimatedArrival || flight.scheduledArrival;
if (!departureTime || !arrivalTime) return status === 'active' ? 50 : 0;
const now = Date.now();
const dep = new Date(departureTime).getTime();
const arr = new Date(arrivalTime).getTime();
if (now <= dep) return 0;
if (now >= arr) return 95; // Past ETA but not confirmed landed
const totalDuration = arr - dep;
const elapsed = now - dep;
return Math.min(95, Math.max(5, Math.round((elapsed / totalDuration) * 100)));
}
function getTrackColor(flight: Flight): string {
const status = flight.status?.toLowerCase();
const delay = flight.arrivalDelay || flight.departureDelay || 0;
if (status === 'cancelled') return 'bg-red-500';
if (status === 'diverted' || status === 'incident') return 'bg-red-500';
if (status === 'landed') return delay > 15 ? 'bg-amber-500' : 'bg-emerald-500';
if (status === 'active') return delay > 15 ? 'bg-amber-500' : 'bg-purple-500';
if (delay > 30) return 'bg-orange-500';
if (delay > 15) return 'bg-amber-500';
return 'bg-blue-500';
}
function getTrackBgColor(flight: Flight): string {
const status = flight.status?.toLowerCase();
if (status === 'cancelled') return 'bg-red-500/20';
if (status === 'diverted' || status === 'incident') return 'bg-red-500/20';
if (status === 'landed') return 'bg-emerald-500/20';
if (status === 'active') return 'bg-purple-500/20';
return 'bg-muted';
}
export function FlightProgressBar({ flight, compact = false }: FlightProgressBarProps) {
const { formatTime } = useFormattedDate();
const [progress, setProgress] = useState(() => calculateProgress(flight));
const status = flight.status?.toLowerCase();
const isActive = status === 'active';
const isLanded = status === 'landed' || !!flight.actualArrival;
const isCancelled = status === 'cancelled' || status === 'diverted' || status === 'incident';
// Update progress periodically for active flights
useEffect(() => {
if (!isActive) {
setProgress(calculateProgress(flight));
return;
}
setProgress(calculateProgress(flight));
const interval = setInterval(() => {
setProgress(calculateProgress(flight));
}, 30000); // Update every 30s for active flights
return () => clearInterval(interval);
}, [flight, isActive]);
const trackColor = useMemo(() => getTrackColor(flight), [flight]);
const trackBgColor = useMemo(() => getTrackBgColor(flight), [flight]);
const departureTime = flight.actualDeparture || flight.estimatedDeparture || flight.scheduledDeparture;
const arrivalTime = flight.actualArrival || flight.estimatedArrival || flight.scheduledArrival;
const hasDelay = (flight.departureDelay || 0) > 0 || (flight.arrivalDelay || 0) > 0;
if (compact) {
return (
<div className="w-full">
<div className="flex items-center gap-2 text-xs">
<span className="font-bold text-foreground">{flight.departureAirport}</span>
<div className="flex-1 relative h-1.5 rounded-full overflow-hidden">
<div className={`absolute inset-0 ${trackBgColor} rounded-full`} />
<div
className={`absolute inset-y-0 left-0 ${trackColor} rounded-full transition-all duration-1000`}
style={{ width: `${progress}%` }}
/>
{isActive && (
<Plane
className="absolute top-1/2 -translate-y-1/2 w-3 h-3 text-purple-500 transition-all duration-1000"
style={{ left: `calc(${progress}% - 6px)` }}
/>
)}
</div>
<span className="font-bold text-foreground">{flight.arrivalAirport}</span>
</div>
</div>
);
}
return (
<div className="w-full py-2">
{/* Airport codes and progress track */}
<div className="flex items-center gap-3">
{/* Departure airport */}
<div className="text-center min-w-[48px]">
<div className="text-lg font-bold text-foreground">{flight.departureAirport}</div>
</div>
{/* Progress track */}
<div className="flex-1 relative">
{/* Track background */}
<div className={`h-2 rounded-full ${trackBgColor} relative overflow-visible`}>
{/* Filled progress */}
<div
className={`absolute inset-y-0 left-0 rounded-full ${trackColor} transition-all duration-1000 ease-in-out`}
style={{ width: `${progress}%` }}
/>
{/* Departure dot */}
<div className={`absolute left-0 top-1/2 -translate-y-1/2 -translate-x-1/2 w-3 h-3 rounded-full border-2 border-background ${progress > 0 ? trackColor : 'bg-muted-foreground/40'}`} />
{/* Arrival dot */}
<div className={`absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2 w-3 h-3 rounded-full border-2 border-background ${progress >= 100 ? trackColor : 'bg-muted-foreground/40'}`} />
{/* Airplane icon */}
{!isCancelled && (
<div
className="absolute top-1/2 -translate-y-1/2 transition-all duration-1000 ease-in-out z-10"
style={{ left: `${Math.max(2, Math.min(98, progress))}%`, transform: `translateX(-50%) translateY(-50%)` }}
>
<div className={`${isActive ? 'animate-bounce-subtle' : ''}`}>
<Plane
className={`w-5 h-5 ${
isLanded ? 'text-emerald-500' :
isActive ? 'text-purple-500' :
'text-muted-foreground'
} drop-shadow-sm`}
style={{ transform: 'rotate(0deg)' }}
/>
</div>
</div>
)}
{/* Cancelled X */}
{isCancelled && (
<div className="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 text-red-500 font-bold text-sm">
&#x2715;
</div>
)}
</div>
</div>
{/* Arrival airport */}
<div className="text-center min-w-[48px]">
<div className="text-lg font-bold text-foreground">{flight.arrivalAirport}</div>
</div>
</div>
{/* Time and detail row */}
<div className="flex justify-between mt-2 text-xs">
{/* Departure details */}
<div className="text-left">
{departureTime && (
<div className="flex items-center gap-1">
{hasDelay && flight.scheduledDeparture && flight.scheduledDeparture !== departureTime ? (
<>
<span className="line-through text-muted-foreground">{formatTime(flight.scheduledDeparture)}</span>
<span className="text-amber-600 dark:text-amber-400 font-medium">{formatTime(departureTime)}</span>
</>
) : (
<span className="text-muted-foreground">{formatTime(departureTime)}</span>
)}
</div>
)}
{(flight.departureTerminal || flight.departureGate) && (
<div className="text-muted-foreground mt-0.5">
{flight.departureTerminal && <span>T{flight.departureTerminal}</span>}
{flight.departureTerminal && flight.departureGate && <span> </span>}
{flight.departureGate && <span>Gate {flight.departureGate}</span>}
</div>
)}
</div>
{/* Center: flight duration or status */}
<div className="text-center text-muted-foreground">
{isActive && flight.aircraftType && (
<span>{flight.aircraftType}</span>
)}
{isLanded && <span className="text-emerald-600 dark:text-emerald-400 font-medium">Landed</span>}
{isCancelled && <span className="text-red-600 dark:text-red-400 font-medium capitalize">{status}</span>}
</div>
{/* Arrival details */}
<div className="text-right">
{arrivalTime && (
<div className="flex items-center justify-end gap-1">
{hasDelay && flight.scheduledArrival && flight.scheduledArrival !== arrivalTime ? (
<>
<span className="line-through text-muted-foreground">{formatTime(flight.scheduledArrival)}</span>
<span className="text-amber-600 dark:text-amber-400 font-medium">{formatTime(arrivalTime)}</span>
</>
) : (
<span className="text-muted-foreground">
{isLanded ? '' : 'ETA '}{formatTime(arrivalTime)}
</span>
)}
</div>
)}
{(flight.arrivalTerminal || flight.arrivalGate || flight.arrivalBaggage) && (
<div className="text-muted-foreground mt-0.5">
{flight.arrivalTerminal && <span>T{flight.arrivalTerminal}</span>}
{flight.arrivalGate && <span> Gate {flight.arrivalGate}</span>}
{flight.arrivalBaggage && <span> Bag {flight.arrivalBaggage}</span>}
</div>
)}
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,37 @@
import type { DriverLocation } from '@/types/gps';
interface GpsIndicatorDotProps {
driverLocation: DriverLocation | undefined;
onClick: (loc: DriverLocation) => void;
className?: string;
}
const TEN_MINUTES = 10 * 60 * 1000;
export function GpsIndicatorDot({ driverLocation, onClick, className = '' }: GpsIndicatorDotProps) {
// Don't render if driver has no GPS enrollment
if (!driverLocation) return null;
const isRecentlyActive = driverLocation.lastActive &&
(Date.now() - new Date(driverLocation.lastActive).getTime()) < TEN_MINUTES;
return (
<button
onClick={(e) => {
e.stopPropagation();
e.preventDefault();
onClick(driverLocation);
}}
className={`inline-flex items-center justify-center p-0.5 rounded-full transition-all hover:scale-125 ${className}`}
title={isRecentlyActive ? 'GPS active - click to view location' : 'GPS inactive - click for last known location'}
>
<span
className={`block h-2.5 w-2.5 rounded-full ${
isRecentlyActive
? 'bg-green-500 animate-pulse shadow-[0_0_6px_rgba(34,197,94,0.6)]'
: 'bg-gray-400'
}`}
/>
</button>
);
}

View File

@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { api } from '@/lib/api'; import { api } from '@/lib/api';
import { ChevronDown, AlertTriangle, X } from 'lucide-react'; import { ChevronDown, AlertTriangle, X } from 'lucide-react';
import { formatDateTime } from '@/lib/utils'; import { useFormattedDate } from '@/hooks/useFormattedDate';
interface Driver { interface Driver {
id: string; id: string;
@@ -32,6 +32,7 @@ export function InlineDriverSelector({
currentDriverName, currentDriverName,
onDriverChange, onDriverChange,
}: InlineDriverSelectorProps) { }: InlineDriverSelectorProps) {
const { formatDateTime } = useFormattedDate();
const queryClient = useQueryClient(); const queryClient = useQueryClient();
const [isOpen, setIsOpen] = useState(false); const [isOpen, setIsOpen] = useState(false);
const [showConflictDialog, setShowConflictDialog] = useState(false); const [showConflictDialog, setShowConflictDialog] = useState(false);

View File

@@ -21,6 +21,8 @@ import {
LogOut, LogOut,
Phone, Phone,
AlertCircle, AlertCircle,
FileText,
HelpCircle,
} from 'lucide-react'; } from 'lucide-react';
import { UserMenu } from '@/components/UserMenu'; import { UserMenu } from '@/components/UserMenu';
import { AppearanceMenu } from '@/components/AppearanceMenu'; import { AppearanceMenu } from '@/components/AppearanceMenu';
@@ -59,6 +61,22 @@ export function Layout({ children }: LayoutProps) {
return () => document.removeEventListener('mousedown', handleClickOutside); return () => document.removeEventListener('mousedown', handleClickOutside);
}, []); }, []);
// Fetch feature flags from backend (which optional services are configured)
const { data: features } = useQuery<{
copilot: boolean;
flightTracking: boolean;
signalMessaging: boolean;
gpsTracking: boolean;
}>({
queryKey: ['features'],
queryFn: async () => {
const { data } = await api.get('/settings/features');
return data;
},
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
enabled: !!backendUser, // Only fetch when authenticated
});
// Check if user is a driver (limited access) // Check if user is a driver (limited access)
const isDriverRole = backendUser?.role === 'DRIVER'; const isDriverRole = backendUser?.role === 'DRIVER';
@@ -78,8 +96,10 @@ export function Layout({ children }: LayoutProps) {
// Admin dropdown items (nested under Admin) // Admin dropdown items (nested under Admin)
const adminItems = [ const adminItems = [
{ name: 'Users', href: '/users', icon: UserCog }, { name: 'Users', href: '/users', icon: UserCog },
{ name: 'Reports', href: '/reports', icon: FileText },
{ name: 'GPS Tracking', href: '/gps-tracking', icon: Radio }, { name: 'GPS Tracking', href: '/gps-tracking', icon: Radio },
{ name: 'Admin Tools', href: '/admin-tools', icon: Settings }, { name: 'Admin Tools', href: '/admin-tools', icon: Settings },
{ name: 'Help Guide', href: '/help', icon: HelpCircle },
]; ];
// Filter navigation based on role and CASL permissions // Filter navigation based on role and CASL permissions
@@ -405,8 +425,8 @@ export function Layout({ children }: LayoutProps) {
{children} {children}
</main> </main>
{/* AI Copilot - floating chat (only for Admins and Coordinators) */} {/* AI Copilot - floating chat (only if backend has API key and user is Admin/Coordinator) */}
{backendUser && (backendUser.role === 'ADMINISTRATOR' || backendUser.role === 'COORDINATOR') && ( {features?.copilot && backendUser && (backendUser.role === 'ADMINISTRATOR' || backendUser.role === 'COORDINATOR') && (
<AICopilot /> <AICopilot />
)} )}
</div> </div>

View File

@@ -0,0 +1,36 @@
import { ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react';
interface SortableHeaderProps<T extends string> {
column: T;
label: string;
currentSort: {
key: string;
direction: 'asc' | 'desc';
};
onSort: (key: T) => void;
className?: string;
}
export function SortableHeader<T extends string>({ column, label, currentSort, onSort, className = '' }: SortableHeaderProps<T>) {
const isActive = currentSort.key === column;
return (
<th
className={`px-6 py-3 text-left text-xs font-medium text-muted-foreground uppercase tracking-wider cursor-pointer hover:bg-accent transition-colors select-none ${className}`}
onClick={() => onSort(column)}
>
<div className="flex items-center gap-2">
{label}
{isActive ? (
currentSort.direction === 'asc' ? (
<ArrowUp className="h-4 w-4 text-primary" />
) : (
<ArrowDown className="h-4 w-4 text-primary" />
)
) : (
<ArrowUpDown className="h-4 w-4 text-muted-foreground/50" />
)}
</div>
</th>
);
}

View File

@@ -1,5 +1,7 @@
import { useState } from 'react'; import { useState } from 'react';
import { X } from 'lucide-react'; import { X, ChevronDown, ChevronUp, ClipboardList } from 'lucide-react';
import { toDatetimeLocal } from '@/lib/utils';
import { DEPARTMENT_LABELS, ARRIVAL_MODE_LABELS } from '@/lib/enum-labels';
interface VIPFormProps { interface VIPFormProps {
vip?: VIP | null; vip?: VIP | null;
@@ -17,7 +19,13 @@ interface VIP {
expectedArrival: string | null; expectedArrival: string | null;
airportPickup: boolean; airportPickup: boolean;
venueTransport: boolean; venueTransport: boolean;
partySize: number;
notes: string | null; notes: string | null;
isRosterOnly: boolean;
phone: string | null;
email: string | null;
emergencyContactName: string | null;
emergencyContactPhone: string | null;
} }
export interface VIPFormData { export interface VIPFormData {
@@ -28,22 +36,16 @@ export interface VIPFormData {
expectedArrival?: string; expectedArrival?: string;
airportPickup?: boolean; airportPickup?: boolean;
venueTransport?: boolean; venueTransport?: boolean;
partySize?: number;
notes?: string; notes?: string;
isRosterOnly?: boolean;
phone?: string;
email?: string;
emergencyContactName?: string;
emergencyContactPhone?: string;
} }
export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps) { export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps) {
// Helper to convert ISO datetime to datetime-local format
const toDatetimeLocal = (isoString: string | null) => {
if (!isoString) return '';
const date = new Date(isoString);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
};
const [formData, setFormData] = useState<VIPFormData>({ const [formData, setFormData] = useState<VIPFormData>({
name: vip?.name || '', name: vip?.name || '',
organization: vip?.organization || '', organization: vip?.organization || '',
@@ -52,9 +54,19 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
expectedArrival: toDatetimeLocal(vip?.expectedArrival || null), expectedArrival: toDatetimeLocal(vip?.expectedArrival || null),
airportPickup: vip?.airportPickup ?? false, airportPickup: vip?.airportPickup ?? false,
venueTransport: vip?.venueTransport ?? false, venueTransport: vip?.venueTransport ?? false,
partySize: vip?.partySize ?? 1,
notes: vip?.notes || '', notes: vip?.notes || '',
isRosterOnly: vip?.isRosterOnly ?? false,
phone: vip?.phone || '',
email: vip?.email || '',
emergencyContactName: vip?.emergencyContactName || '',
emergencyContactPhone: vip?.emergencyContactPhone || '',
}); });
const [showRosterFields, setShowRosterFields] = useState(
vip?.isRosterOnly || vip?.phone || vip?.email || vip?.emergencyContactName ? true : false
);
const handleSubmit = (e: React.FormEvent) => { const handleSubmit = (e: React.FormEvent) => {
e.preventDefault(); e.preventDefault();
@@ -66,6 +78,10 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
? new Date(formData.expectedArrival).toISOString() ? new Date(formData.expectedArrival).toISOString()
: undefined, : undefined,
notes: formData.notes || undefined, notes: formData.notes || undefined,
phone: formData.phone || undefined,
email: formData.email || undefined,
emergencyContactName: formData.emergencyContactName || undefined,
emergencyContactPhone: formData.emergencyContactPhone || undefined,
}; };
onSubmit(cleanedData); onSubmit(cleanedData);
@@ -80,6 +96,8 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
[name]: [name]:
type === 'checkbox' type === 'checkbox'
? (e.target as HTMLInputElement).checked ? (e.target as HTMLInputElement).checked
: type === 'number'
? parseInt(value) || 1
: value, : value,
})); }));
}; };
@@ -133,6 +151,26 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
/> />
</div> </div>
{/* Party Size */}
<div>
<label className="block text-sm font-medium text-foreground mb-2">
Party Size (VIP + companions)
</label>
<input
type="number"
name="partySize"
min={1}
max={50}
value={formData.partySize}
onChange={handleChange}
className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }}
/>
<p className="mt-1 text-xs text-muted-foreground">
Total seats needed: the VIP plus any handlers, spouses, or entourage
</p>
</div>
{/* Department */} {/* Department */}
<div> <div>
<label className="block text-sm font-medium text-foreground mb-2"> <label className="block text-sm font-medium text-foreground mb-2">
@@ -146,8 +184,11 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary" className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }} style={{ minHeight: '44px' }}
> >
<option value="OFFICE_OF_DEVELOPMENT">Office of Development</option> {Object.entries(DEPARTMENT_LABELS).map(([value, label]) => (
<option value="ADMIN">Admin</option> <option key={value} value={value}>
{label}
</option>
))}
</select> </select>
</div> </div>
@@ -164,8 +205,11 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary" className="w-full px-4 py-3 text-base bg-background text-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }} style={{ minHeight: '44px' }}
> >
<option value="FLIGHT">Flight</option> {Object.entries(ARRIVAL_MODE_LABELS).map(([value, label]) => (
<option value="SELF_DRIVING">Self Driving</option> <option key={value} value={value}>
{label}
</option>
))}
</select> </select>
</div> </div>
@@ -213,6 +257,118 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
</label> </label>
</div> </div>
{/* Roster & Contact Info Section */}
<div className="border border-border rounded-lg overflow-hidden">
<button
type="button"
onClick={() => setShowRosterFields(!showRosterFields)}
className="w-full flex items-center justify-between p-4 bg-muted/30 hover:bg-muted/50 transition-colors"
>
<div className="flex items-center gap-2">
<ClipboardList className="h-4 w-4 text-muted-foreground" />
<span className="font-medium text-foreground">Contact & Emergency Info</span>
{formData.isRosterOnly && (
<span className="px-2 py-0.5 text-xs bg-amber-100 dark:bg-amber-950 text-amber-700 dark:text-amber-300 rounded">
Roster Only
</span>
)}
</div>
{showRosterFields ? (
<ChevronUp className="h-4 w-4 text-muted-foreground" />
) : (
<ChevronDown className="h-4 w-4 text-muted-foreground" />
)}
</button>
{showRosterFields && (
<div className="p-4 space-y-4 border-t border-border">
{/* Roster Only Toggle */}
<label className="flex items-center cursor-pointer" style={{ minHeight: '28px' }}>
<input
type="checkbox"
name="isRosterOnly"
checked={formData.isRosterOnly}
onChange={handleChange}
className="h-5 w-5 text-primary border-input rounded focus:ring-primary"
/>
<span className="ml-3 text-base text-foreground">
Roster only (accountability tracking, no active coordination)
</span>
</label>
<p className="text-xs text-muted-foreground -mt-2 ml-8">
Check this for VIPs who are attending but don't need transportation services
</p>
{/* VIP Contact Info */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4 pt-2">
<div>
<label className="block text-sm font-medium text-foreground mb-2">
Phone
</label>
<input
type="tel"
name="phone"
value={formData.phone}
onChange={handleChange}
placeholder="555-123-4567"
className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }}
/>
</div>
<div>
<label className="block text-sm font-medium text-foreground mb-2">
Email
</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
placeholder="vip@example.com"
className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }}
/>
</div>
</div>
{/* Emergency Contact */}
<div className="pt-2">
<h4 className="text-sm font-medium text-foreground mb-3">Emergency Contact</h4>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-muted-foreground mb-2">
Name
</label>
<input
type="text"
name="emergencyContactName"
value={formData.emergencyContactName}
onChange={handleChange}
placeholder="Jane Doe"
className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }}
/>
</div>
<div>
<label className="block text-sm font-medium text-muted-foreground mb-2">
Phone
</label>
<input
type="tel"
name="emergencyContactPhone"
value={formData.emergencyContactPhone}
onChange={handleChange}
placeholder="555-987-6543"
className="w-full px-4 py-3 text-base bg-background text-foreground placeholder:text-muted-foreground border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
style={{ minHeight: '44px' }}
/>
</div>
</div>
</div>
</div>
)}
</div>
{/* Notes */} {/* Notes */}
<div> <div>
<label className="block text-sm font-medium text-foreground mb-2"> <label className="block text-sm font-medium text-foreground mb-2">

View File

@@ -1,6 +1,6 @@
import { createContext, useContext, useEffect, useState, ReactNode } from 'react'; import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
import { useAuth0 } from '@auth0/auth0-react'; import { useAuth0 } from '@auth0/auth0-react';
import { api } from '@/lib/api'; import { api, setTokenGetter } from '@/lib/api';
interface BackendUser { interface BackendUser {
id: string; id: string;
@@ -40,9 +40,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const [fetchingUser, setFetchingUser] = useState(false); const [fetchingUser, setFetchingUser] = useState(false);
const [authError, setAuthError] = useState<string | null>(null); const [authError, setAuthError] = useState<string | null>(null);
// Set up token and fetch backend user profile // Wire up the API token getter so axios can fetch fresh tokens
useEffect(() => {
if (isAuthenticated) {
setTokenGetter(() => getAccessTokenSilently());
}
return () => setTokenGetter(null);
}, [isAuthenticated, getAccessTokenSilently]);
// Fetch backend user profile after authentication
useEffect(() => { useEffect(() => {
// Wait for Auth0 to finish loading before fetching token
if (isAuthenticated && !isLoading && !fetchingUser && !backendUser) { if (isAuthenticated && !isLoading && !fetchingUser && !backendUser) {
setFetchingUser(true); setFetchingUser(true);
setAuthError(null); setAuthError(null);
@@ -53,42 +60,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setFetchingUser(false); setFetchingUser(false);
}, 10000); // 10 second timeout }, 10000); // 10 second timeout
getAccessTokenSilently() // Fetch backend user profile (api interceptor handles token automatically)
.then(async (token) => { api.get('/auth/profile')
.then((response) => {
clearTimeout(timeoutId); clearTimeout(timeoutId);
console.log('[AUTH] Got access token, fetching user profile');
localStorage.setItem('auth0_token', token);
// Fetch backend user profile
try {
const response = await api.get('/auth/profile');
console.log('[AUTH] User profile fetched successfully:', response.data.email); console.log('[AUTH] User profile fetched successfully:', response.data.email);
setBackendUser(response.data); setBackendUser(response.data);
setAuthError(null); setAuthError(null);
} catch (error: any) { })
.catch((error: any) => {
clearTimeout(timeoutId);
console.error('[AUTH] Failed to fetch user profile:', error); console.error('[AUTH] Failed to fetch user profile:', error);
setBackendUser(null); setBackendUser(null);
// Set specific error message // Handle specific errors
if (error.response?.status === 401) { if (error.response?.status === 401) {
setAuthError('Your account is pending approval or your session has expired'); setAuthError('Your account is pending approval or your session has expired');
} else { } else if (error.error === 'missing_refresh_token' || error.message?.includes('Missing Refresh Token')) {
setAuthError('Failed to load user profile - please try logging in again');
}
}
})
.catch((error) => {
clearTimeout(timeoutId);
console.error('[AUTH] Failed to get token:', error);
setBackendUser(null);
// Handle specific Auth0 errors
if (error.error === 'missing_refresh_token' || error.message?.includes('Missing Refresh Token')) {
setAuthError('Session expired - please log in again'); setAuthError('Session expired - please log in again');
} else if (error.error === 'login_required') { } else if (error.error === 'login_required') {
setAuthError('Login required'); setAuthError('Login required');
} else { } else {
setAuthError('Authentication failed - please try logging in again'); setAuthError('Failed to load user profile - please try logging in again');
} }
}) })
.finally(() => { .finally(() => {
@@ -99,7 +92,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
}, [isAuthenticated, isLoading]); }, [isAuthenticated, isLoading]);
const handleLogout = () => { const handleLogout = () => {
localStorage.removeItem('auth0_token'); setTokenGetter(null);
auth0Logout({ logoutParams: { returnTo: window.location.origin } }); auth0Logout({ logoutParams: { returnTo: window.location.origin } });
}; };

View File

@@ -0,0 +1,71 @@
import { createContext, useContext, type ReactNode } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import toast from 'react-hot-toast';
interface TimezoneContextValue {
timezone: string;
isLoading: boolean;
setTimezone: (tz: string) => void;
}
const TimezoneContext = createContext<TimezoneContextValue>({
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
isLoading: false,
setTimezone: () => {},
});
export function TimezoneProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient();
const { data, isLoading } = useQuery<{ timezone: string }>({
queryKey: ['settings', 'timezone'],
queryFn: async () => {
const { data } = await api.get('/settings/timezone');
return data;
},
staleTime: 5 * 60 * 1000, // 5 minutes
});
const mutation = useMutation({
mutationFn: async (timezone: string) => {
const { data } = await api.patch('/settings/timezone', { timezone });
return data;
},
onSuccess: (data) => {
queryClient.setQueryData(['settings', 'timezone'], data);
toast.success('Timezone updated');
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to update timezone');
},
});
const timezone = data?.timezone || Intl.DateTimeFormat().resolvedOptions().timeZone;
return (
<TimezoneContext.Provider
value={{
timezone,
isLoading,
setTimezone: (tz: string) => mutation.mutate(tz),
}}
>
{children}
</TimezoneContext.Provider>
);
}
/**
* Get the app-wide timezone string
*/
export function useTimezone(): string {
return useContext(TimezoneContext).timezone;
}
/**
* Get the full timezone context (timezone, isLoading, setTimezone)
*/
export function useTimezoneContext(): TimezoneContextValue {
return useContext(TimezoneContext);
}

View File

@@ -0,0 +1,66 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';
import { Flight, FlightBudget } from '@/types';
import toast from 'react-hot-toast';
import { queryKeys } from '@/lib/query-keys';
export function useFlights() {
return useQuery<Flight[]>({
queryKey: queryKeys.flights.all,
queryFn: async () => {
const { data } = await api.get('/flights');
return data;
},
refetchInterval: 60000, // Refresh from DB every 60s (free, no API cost)
});
}
export function useFlightBudget() {
return useQuery<FlightBudget>({
queryKey: queryKeys.flights.budget,
queryFn: async () => {
const { data } = await api.get('/flights/tracking/budget');
return data;
},
refetchInterval: 300000, // Every 5 min
});
}
export function useRefreshFlight() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async (flightId: string) => {
const { data } = await api.post(`/flights/${flightId}/refresh`);
return data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: queryKeys.flights.all });
queryClient.invalidateQueries({ queryKey: queryKeys.flights.budget });
const status = data.status || 'unknown';
toast.success(`Flight updated: ${data.flightNumber} (${status})`);
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to refresh flight');
},
});
}
export function useRefreshActiveFlights() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async () => {
const { data } = await api.post('/flights/refresh-active');
return data;
},
onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: queryKeys.flights.all });
queryClient.invalidateQueries({ queryKey: queryKeys.flights.budget });
toast.success(`Refreshed ${data.refreshed} flights (${data.budgetRemaining} API calls remaining)`);
},
onError: (error: any) => {
toast.error(error.response?.data?.message || 'Failed to refresh flights');
},
});
}

View File

@@ -0,0 +1,28 @@
import { useCallback } from 'react';
import { useTimezone } from '@/contexts/TimezoneContext';
import { formatDate as fmtDate, formatDateTime as fmtDateTime, formatTime as fmtTime } from '@/lib/utils';
/**
* Returns format functions pre-bound with the app-wide timezone.
* Use this in components instead of importing formatDate/DateTime/Time directly.
*/
export function useFormattedDate() {
const timezone = useTimezone();
const formatDate = useCallback(
(date: string | Date) => fmtDate(date, timezone),
[timezone],
);
const formatDateTime = useCallback(
(date: string | Date) => fmtDateTime(date, timezone),
[timezone],
);
const formatTime = useCallback(
(date: string | Date) => fmtTime(date, timezone),
[timezone],
);
return { formatDate, formatDateTime, formatTime, timezone };
}

View File

@@ -8,8 +8,10 @@ import type {
GpsSettings, GpsSettings,
EnrollmentResponse, EnrollmentResponse,
MyGpsStatus, MyGpsStatus,
DeviceQrInfo,
} from '@/types/gps'; } from '@/types/gps';
import toast from 'react-hot-toast'; import toast from 'react-hot-toast';
import { queryKeys } from '@/lib/query-keys';
// ============================================ // ============================================
// Admin GPS Hooks // Admin GPS Hooks
@@ -20,7 +22,7 @@ import toast from 'react-hot-toast';
*/ */
export function useGpsStatus() { export function useGpsStatus() {
return useQuery<GpsStatus>({ return useQuery<GpsStatus>({
queryKey: ['gps', 'status'], queryKey: queryKeys.gps.status,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/status'); const { data } = await api.get('/gps/status');
return data; return data;
@@ -34,7 +36,7 @@ export function useGpsStatus() {
*/ */
export function useGpsSettings() { export function useGpsSettings() {
return useQuery<GpsSettings>({ return useQuery<GpsSettings>({
queryKey: ['gps', 'settings'], queryKey: queryKeys.gps.settings,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/settings'); const { data } = await api.get('/gps/settings');
return data; return data;
@@ -54,8 +56,8 @@ export function useUpdateGpsSettings() {
return data; return data;
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['gps', 'settings'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.settings });
queryClient.invalidateQueries({ queryKey: ['gps', 'status'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.status });
toast.success('GPS settings updated'); toast.success('GPS settings updated');
}, },
onError: (error: any) => { onError: (error: any) => {
@@ -69,7 +71,7 @@ export function useUpdateGpsSettings() {
*/ */
export function useGpsDevices() { export function useGpsDevices() {
return useQuery<GpsDevice[]>({ return useQuery<GpsDevice[]>({
queryKey: ['gps', 'devices'], queryKey: queryKeys.gps.devices,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/devices'); const { data } = await api.get('/gps/devices');
return data; return data;
@@ -79,48 +81,30 @@ export function useGpsDevices() {
} }
/** /**
* Get all active driver locations (for map) * Get QR code info for an enrolled device (on demand)
*/
export function useDeviceQr(driverId: string | null) {
return useQuery<DeviceQrInfo>({
queryKey: driverId ? queryKeys.gps.deviceQr(driverId) : ['gps', 'devices', null, 'qr'],
queryFn: async () => {
const { data } = await api.get(`/gps/devices/${driverId}/qr`);
return data;
},
enabled: !!driverId,
});
}
/**
* Get all active driver locations (used by CommandCenter)
*/ */
export function useDriverLocations() { export function useDriverLocations() {
return useQuery<DriverLocation[]>({ return useQuery<DriverLocation[]>({
queryKey: ['gps', 'locations'], queryKey: queryKeys.gps.locations.all,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/locations'); const { data } = await api.get('/gps/locations');
return data; return data;
}, },
refetchInterval: 30000, // Refresh every 30 seconds refetchInterval: 15000, // Refresh every 15 seconds
});
}
/**
* Get a specific driver's location
*/
export function useDriverLocation(driverId: string) {
return useQuery<DriverLocation>({
queryKey: ['gps', 'locations', driverId],
queryFn: async () => {
const { data } = await api.get(`/gps/locations/${driverId}`);
return data;
},
enabled: !!driverId,
refetchInterval: 30000,
});
}
/**
* Get driver stats
*/
export function useDriverStats(driverId: string, from?: string, to?: string) {
return useQuery<DriverStats>({
queryKey: ['gps', 'stats', driverId, from, to],
queryFn: async () => {
const params = new URLSearchParams();
if (from) params.append('from', from);
if (to) params.append('to', to);
const { data } = await api.get(`/gps/stats/${driverId}?${params.toString()}`);
return data;
},
enabled: !!driverId,
}); });
} }
@@ -136,9 +120,9 @@ export function useEnrollDriver() {
return data; return data;
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['gps', 'devices'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.devices });
queryClient.invalidateQueries({ queryKey: ['gps', 'status'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.status });
queryClient.invalidateQueries({ queryKey: ['drivers'] }); queryClient.invalidateQueries({ queryKey: queryKeys.drivers.all });
if (data.signalMessageSent) { if (data.signalMessageSent) {
toast.success('Driver enrolled! Setup instructions sent via Signal.'); toast.success('Driver enrolled! Setup instructions sent via Signal.');
} else { } else {
@@ -163,10 +147,10 @@ export function useUnenrollDriver() {
return data; return data;
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['gps', 'devices'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.devices });
queryClient.invalidateQueries({ queryKey: ['gps', 'status'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.status });
queryClient.invalidateQueries({ queryKey: ['gps', 'locations'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.locations.all });
queryClient.invalidateQueries({ queryKey: ['drivers'] }); queryClient.invalidateQueries({ queryKey: queryKeys.drivers.all });
toast.success('Driver unenrolled from GPS tracking'); toast.success('Driver unenrolled from GPS tracking');
}, },
onError: (error: any) => { onError: (error: any) => {
@@ -184,7 +168,7 @@ export function useUnenrollDriver() {
*/ */
export function useMyGpsStatus() { export function useMyGpsStatus() {
return useQuery<MyGpsStatus>({ return useQuery<MyGpsStatus>({
queryKey: ['gps', 'me'], queryKey: queryKeys.gps.me.status,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/me'); const { data } = await api.get('/gps/me');
return data; return data;
@@ -197,7 +181,7 @@ export function useMyGpsStatus() {
*/ */
export function useMyGpsStats(from?: string, to?: string) { export function useMyGpsStats(from?: string, to?: string) {
return useQuery<DriverStats>({ return useQuery<DriverStats>({
queryKey: ['gps', 'me', 'stats', from, to], queryKey: queryKeys.gps.me.stats(from, to),
queryFn: async () => { queryFn: async () => {
const params = new URLSearchParams(); const params = new URLSearchParams();
if (from) params.append('from', from); if (from) params.append('from', from);
@@ -213,7 +197,7 @@ export function useMyGpsStats(from?: string, to?: string) {
*/ */
export function useMyLocation() { export function useMyLocation() {
return useQuery<DriverLocation>({ return useQuery<DriverLocation>({
queryKey: ['gps', 'me', 'location'], queryKey: queryKeys.gps.me.location,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/me/location'); const { data } = await api.get('/gps/me/location');
return data; return data;
@@ -234,7 +218,7 @@ export function useUpdateGpsConsent() {
return data; return data;
}, },
onSuccess: (data) => { onSuccess: (data) => {
queryClient.invalidateQueries({ queryKey: ['gps', 'me'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.me.status });
toast.success(data.message); toast.success(data.message);
}, },
onError: (error: any) => { onError: (error: any) => {
@@ -252,7 +236,7 @@ export function useUpdateGpsConsent() {
*/ */
export function useTraccarSetupStatus() { export function useTraccarSetupStatus() {
return useQuery<{ needsSetup: boolean; isAvailable: boolean }>({ return useQuery<{ needsSetup: boolean; isAvailable: boolean }>({
queryKey: ['gps', 'traccar', 'status'], queryKey: queryKeys.gps.traccar.status,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/traccar/status'); const { data } = await api.get('/gps/traccar/status');
return data; return data;
@@ -272,8 +256,8 @@ export function useTraccarSetup() {
return data; return data;
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['gps', 'traccar', 'status'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.traccar.status });
queryClient.invalidateQueries({ queryKey: ['gps', 'status'] }); queryClient.invalidateQueries({ queryKey: queryKeys.gps.status });
toast.success('Traccar setup complete!'); toast.success('Traccar setup complete!');
}, },
onError: (error: any) => { onError: (error: any) => {
@@ -305,7 +289,7 @@ export function useSyncAdminsToTraccar() {
*/ */
export function useTraccarAdminUrl() { export function useTraccarAdminUrl() {
return useQuery<{ url: string; directAccess: boolean }>({ return useQuery<{ url: string; directAccess: boolean }>({
queryKey: ['gps', 'traccar', 'admin-url'], queryKey: queryKeys.gps.traccar.adminUrl,
queryFn: async () => { queryFn: async () => {
const { data } = await api.get('/gps/traccar/admin-url'); const { data } = await api.get('/gps/traccar/admin-url');
return data; return data;

Some files were not shown because too many files have changed in this diff Show More