Compare commits
31 Commits
1e162b4f7c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 139cb4aebe | |||
| 14c6c9506f | |||
| 53eb82c4d2 | |||
| b80ffd3ca1 | |||
| cc3375ef85 | |||
| cb4a070ad9 | |||
| 12b9361ae0 | |||
| 33fda57cc6 | |||
| d93919910b | |||
| 4dbb899409 | |||
| 3bc9cd0bca | |||
| f2b3f34a72 | |||
| 806b67954e | |||
| a4d360aae9 | |||
| 0f0f1cbf38 | |||
| 74a292ea93 | |||
| b35c14fddc | |||
| 934464bf8e | |||
| 8e88880838 | |||
| 5f4c474e37 | |||
| a6b639d5f4 | |||
| 8e8bbad3fc | |||
| 714cac5d10 | |||
| ca2b341f01 | |||
| 0d7306e0aa | |||
| 21fb193d01 | |||
| 858793d698 | |||
| 16c0fb65a6 | |||
| 42bab25766 | |||
| ec7c5a6802 | |||
| a0d0cbc8f6 |
40
backend/.env
@@ -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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"
|
||||
@@ -6,19 +6,19 @@ NODE_ENV=development
|
||||
FRONTEND_URL=http://localhost:5173
|
||||
|
||||
# ============================================
|
||||
# Database Configuration
|
||||
# Database Configuration (required)
|
||||
# ============================================
|
||||
# Port 5433 is used to avoid conflicts with local PostgreSQL
|
||||
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
|
||||
REDIS_URL="redis://localhost:6380"
|
||||
|
||||
# ============================================
|
||||
# Auth0 Configuration
|
||||
# Auth0 Configuration (required)
|
||||
# ============================================
|
||||
# Get these from your Auth0 dashboard:
|
||||
# 1. Create Application (Single Page Application)
|
||||
@@ -29,6 +29,16 @@ AUTH0_AUDIENCE="https://your-api-identifier"
|
||||
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=
|
||||
|
||||
39
backend/package-lock.json
generated
@@ -11,7 +11,6 @@
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.72.1",
|
||||
"@casl/ability": "^6.8.0",
|
||||
"@casl/prisma": "^1.6.1",
|
||||
"@nestjs/axios": "^4.0.1",
|
||||
"@nestjs/common": "^10.3.0",
|
||||
"@nestjs/config": "^3.1.1",
|
||||
@@ -21,11 +20,13 @@
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.3.0",
|
||||
"@nestjs/schedule": "^4.1.2",
|
||||
"@nestjs/throttler": "^6.5.0",
|
||||
"@prisma/client": "^5.8.1",
|
||||
"@types/pdfkit": "^0.17.4",
|
||||
"axios": "^1.6.5",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.0",
|
||||
"helmet": "^8.1.0",
|
||||
"ics": "^3.8.1",
|
||||
"ioredis": "^5.3.2",
|
||||
"jwks-rsa": "^3.1.0",
|
||||
@@ -783,7 +784,6 @@
|
||||
"resolved": "https://registry.npmjs.org/@casl/ability/-/ability-6.8.0.tgz",
|
||||
"integrity": "sha512-Ipt4mzI4gSgnomFdaPjaLgY2MWuXqAEZLrU6qqWBB7khGiBBuuEp6ytYDnq09bRXqcjaeeHiaCvCGFbBA2SpvA==",
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"@ucast/mongo2js": "^1.3.0"
|
||||
},
|
||||
@@ -791,20 +791,6 @@
|
||||
"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": {
|
||||
"version": "1.5.0",
|
||||
"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": {
|
||||
"version": "1.8.0",
|
||||
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.8.0.tgz",
|
||||
@@ -2134,7 +2131,6 @@
|
||||
"integrity": "sha512-M0SVXfyHnQREBKxCgyo7sffrKttwE6R8PMq330MIUF0pTwjUhLbW84pFDlf06B27XyCR++VtjugEnIHdr07SVA==",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=16.13"
|
||||
},
|
||||
@@ -5866,6 +5862,15 @@
|
||||
"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": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz",
|
||||
|
||||
@@ -26,7 +26,6 @@
|
||||
"dependencies": {
|
||||
"@anthropic-ai/sdk": "^0.72.1",
|
||||
"@casl/ability": "^6.8.0",
|
||||
"@casl/prisma": "^1.6.1",
|
||||
"@nestjs/axios": "^4.0.1",
|
||||
"@nestjs/common": "^10.3.0",
|
||||
"@nestjs/config": "^3.1.1",
|
||||
@@ -36,11 +35,13 @@
|
||||
"@nestjs/passport": "^10.0.3",
|
||||
"@nestjs/platform-express": "^10.3.0",
|
||||
"@nestjs/schedule": "^4.1.2",
|
||||
"@nestjs/throttler": "^6.5.0",
|
||||
"@prisma/client": "^5.8.1",
|
||||
"@types/pdfkit": "^0.17.4",
|
||||
"axios": "^1.6.5",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.14.0",
|
||||
"helmet": "^8.1.0",
|
||||
"ics": "^3.8.1",
|
||||
"ioredis": "^5.3.2",
|
||||
"jwks-rsa": "^3.1.0",
|
||||
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- AlterEnum
|
||||
ALTER TYPE "Department" ADD VALUE 'OTHER';
|
||||
@@ -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");
|
||||
@@ -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");
|
||||
@@ -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;
|
||||
@@ -50,7 +50,18 @@ model VIP {
|
||||
expectedArrival DateTime? // For self-driving arrivals
|
||||
airportPickup Boolean @default(false)
|
||||
venueTransport Boolean @default(false)
|
||||
partySize Int @default(1) // Total people: VIP + entourage
|
||||
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[]
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -62,6 +73,7 @@ model VIP {
|
||||
enum Department {
|
||||
OFFICE_OF_DEVELOPMENT
|
||||
ADMIN
|
||||
OTHER
|
||||
}
|
||||
|
||||
enum ArrivalMode {
|
||||
@@ -86,13 +98,70 @@ model Flight {
|
||||
scheduledArrival DateTime?
|
||||
actualDeparture 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())
|
||||
updatedAt DateTime @updatedAt
|
||||
|
||||
@@map("flights")
|
||||
@@index([vipId])
|
||||
@@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?
|
||||
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
|
||||
notes String? @db.Text
|
||||
|
||||
@@ -331,6 +405,7 @@ model GpsDevice {
|
||||
|
||||
// Location history
|
||||
locationHistory GpsLocationHistory[]
|
||||
trips GpsTrip[]
|
||||
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
@@ -346,7 +421,7 @@ model GpsLocationHistory {
|
||||
latitude Float
|
||||
longitude Float
|
||||
altitude Float?
|
||||
speed Float? // km/h
|
||||
speed Float? // mph (converted from knots during sync)
|
||||
course Float? // Bearing in degrees
|
||||
accuracy Float? // Meters
|
||||
battery Float? // Battery percentage (0-100)
|
||||
@@ -356,10 +431,49 @@ model GpsLocationHistory {
|
||||
createdAt DateTime @default(now())
|
||||
|
||||
@@map("gps_location_history")
|
||||
@@index([deviceId, timestamp])
|
||||
@@unique([deviceId, timestamp]) // Prevent duplicate position records
|
||||
@@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 {
|
||||
id String @id @default(uuid())
|
||||
|
||||
|
||||
@@ -3,145 +3,157 @@ import { PrismaClient, Role, Department, ArrivalMode, EventType, EventStatus, Ve
|
||||
const prisma = new PrismaClient();
|
||||
|
||||
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.flight.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.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: {
|
||||
auth0Id: 'auth0|admin-sample-id',
|
||||
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',
|
||||
name: 'Black Suburban #1',
|
||||
type: VehicleType.SUV,
|
||||
licensePlate: 'ABC-1234',
|
||||
licensePlate: 'BSA-001',
|
||||
seatCapacity: 6,
|
||||
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({
|
||||
data: {
|
||||
name: 'White Sprinter Van',
|
||||
name: 'White 15-Passenger Van',
|
||||
type: VehicleType.VAN,
|
||||
licensePlate: 'XYZ-5678',
|
||||
seatCapacity: 12,
|
||||
licensePlate: 'BSA-003',
|
||||
seatCapacity: 14,
|
||||
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: {
|
||||
name: 'Blue Camry',
|
||||
type: VehicleType.SEDAN,
|
||||
licensePlate: 'DEF-9012',
|
||||
name: 'Golf Cart A',
|
||||
type: VehicleType.GOLF_CART,
|
||||
licensePlate: 'GC-A',
|
||||
seatCapacity: 4,
|
||||
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: {
|
||||
name: 'Gray Charter Bus',
|
||||
type: VehicleType.BUS,
|
||||
licensePlate: 'BUS-0001',
|
||||
seatCapacity: 40,
|
||||
name: 'Golf Cart B',
|
||||
type: VehicleType.GOLF_CART,
|
||||
licensePlate: 'GC-B',
|
||||
seatCapacity: 4,
|
||||
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');
|
||||
|
||||
// Create sample drivers
|
||||
const driver1 = await prisma.driver.create({
|
||||
const charterBus = await prisma.vehicle.create({
|
||||
data: {
|
||||
name: 'John Smith',
|
||||
phone: '+1 (555) 123-4567',
|
||||
department: Department.OFFICE_OF_DEVELOPMENT,
|
||||
name: 'Charter Bus',
|
||||
type: VehicleType.BUS,
|
||||
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: {
|
||||
name: 'Jane Doe',
|
||||
phone: '+1 (555) 987-6543',
|
||||
name: 'Tom Bradley',
|
||||
phone: '+1 (555) 100-0001',
|
||||
department: Department.ADMIN,
|
||||
},
|
||||
});
|
||||
|
||||
const driver3 = await prisma.driver.create({
|
||||
const driverMaria = await prisma.driver.create({
|
||||
data: {
|
||||
name: 'Amanda Washington',
|
||||
phone: '+1 (555) 234-5678',
|
||||
department: Department.OFFICE_OF_DEVELOPMENT,
|
||||
},
|
||||
});
|
||||
|
||||
const driver4 = await prisma.driver.create({
|
||||
data: {
|
||||
name: 'Michael Thompson',
|
||||
phone: '+1 (555) 876-5432',
|
||||
name: 'Maria Gonzalez',
|
||||
phone: '+1 (555) 100-0002',
|
||||
department: Department.ADMIN,
|
||||
},
|
||||
});
|
||||
|
||||
console.log('✅ Created sample drivers');
|
||||
|
||||
// Create sample VIPs
|
||||
const vip1 = await prisma.vIP.create({
|
||||
const driverKevin = await prisma.driver.create({
|
||||
data: {
|
||||
name: 'Dr. Robert Johnson',
|
||||
organization: 'Tech Corporation',
|
||||
name: 'Kevin Park',
|
||||
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,
|
||||
arrivalMode: ArrivalMode.FLIGHT,
|
||||
airportPickup: 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: {
|
||||
create: [
|
||||
{
|
||||
flightNumber: 'AA123',
|
||||
flightDate: new Date('2026-02-15'),
|
||||
flightNumber: 'UA1142',
|
||||
flightDate: new Date('2026-02-05'),
|
||||
segment: 1,
|
||||
departureAirport: 'JFK',
|
||||
arrivalAirport: 'LAX',
|
||||
scheduledDeparture: new Date('2026-02-15T08:00:00'),
|
||||
scheduledArrival: new Date('2026-02-15T11:30:00'),
|
||||
departureAirport: 'IAD',
|
||||
arrivalAirport: 'DEN',
|
||||
scheduledDeparture: new Date('2026-02-05T07:00:00'),
|
||||
scheduledArrival: new Date('2026-02-05T09:15:00'),
|
||||
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: {
|
||||
name: 'Ms. Sarah Williams',
|
||||
organization: 'Global Foundation',
|
||||
name: 'Patricia Hawkins',
|
||||
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,
|
||||
arrivalMode: ArrivalMode.SELF_DRIVING,
|
||||
expectedArrival: new Date('2026-02-16T14:00:00'),
|
||||
expectedArrival: new Date('2026-02-05T13:00:00'),
|
||||
airportPickup: false,
|
||||
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: {
|
||||
name: 'Emily Richardson (Harvard University)',
|
||||
organization: 'Harvard University',
|
||||
department: Department.OFFICE_OF_DEVELOPMENT,
|
||||
arrivalMode: ArrivalMode.FLIGHT,
|
||||
airportPickup: true,
|
||||
name: 'Susan O\'Malley',
|
||||
organization: 'Denver Area Council BSA',
|
||||
department: Department.ADMIN,
|
||||
arrivalMode: ArrivalMode.SELF_DRIVING,
|
||||
expectedArrival: new Date('2026-02-05T08:00:00'),
|
||||
airportPickup: false,
|
||||
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: {
|
||||
name: 'David Chen (Stanford)',
|
||||
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],
|
||||
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipGovMartinez.id, vipSusan.id],
|
||||
title: 'Opening Ceremony',
|
||||
location: 'Main Stage',
|
||||
startTime: new Date('2026-02-15T10:00:00'),
|
||||
endTime: new Date('2026-02-15T11:30:00'),
|
||||
description: 'Welcome and opening remarks',
|
||||
location: 'Main Arena',
|
||||
startTime: new Date(jamboreeDay1.getTime() + 10 * 60 * 60 * 1000), // 10:00 AM
|
||||
endTime: new Date(jamboreeDay1.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
|
||||
description: 'National anthem, color guard, welcome remarks by Chief Scout Executive. All VIPs seated in reserved section.',
|
||||
type: EventType.EVENT,
|
||||
status: EventStatus.SCHEDULED,
|
||||
},
|
||||
});
|
||||
|
||||
// Lunch - Day 1 (all VIPs)
|
||||
await prisma.scheduleEvent.create({
|
||||
const vipLuncheon = await prisma.scheduleEvent.create({
|
||||
data: {
|
||||
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id],
|
||||
title: 'Lunch - Day 1',
|
||||
location: 'Main Dining Hall',
|
||||
startTime: new Date('2026-02-15T12:00:00'),
|
||||
endTime: new Date('2026-02-15T13:30:00'),
|
||||
description: 'Day 1 lunch for all attendees',
|
||||
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipGovMartinez.id, vipSusan.id],
|
||||
title: 'VIP Luncheon',
|
||||
location: 'Eagle Lodge Private Dining',
|
||||
startTime: new Date(jamboreeDay1.getTime() + 12 * 60 * 60 * 1000), // 12:00 PM
|
||||
endTime: new Date(jamboreeDay1.getTime() + 13.5 * 60 * 60 * 1000), // 1:30 PM
|
||||
description: 'Private luncheon for VIP guests and BSA leadership. Seated service.',
|
||||
type: EventType.MEAL,
|
||||
status: EventStatus.SCHEDULED,
|
||||
},
|
||||
});
|
||||
|
||||
// Campfire Night (all VIPs)
|
||||
await prisma.scheduleEvent.create({
|
||||
const keynoteAddress = await prisma.scheduleEvent.create({
|
||||
data: {
|
||||
vipIds: [vip1.id, vip2.id, vip3.id, vip4.id],
|
||||
title: 'Campfire Night',
|
||||
location: 'Camp Amphitheater',
|
||||
startTime: new Date('2026-02-15T20:00:00'),
|
||||
endTime: new Date('2026-02-15T22:00:00'),
|
||||
description: 'Evening campfire and networking',
|
||||
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
|
||||
title: 'Keynote Address — Dr. Baker',
|
||||
location: 'Main Arena',
|
||||
startTime: new Date(jamboreeDay1.getTime() + 14 * 60 * 60 * 1000), // 2:00 PM
|
||||
endTime: new Date(jamboreeDay1.getTime() + 15.5 * 60 * 60 * 1000), // 3:30 PM
|
||||
description: 'Dr. Angela Baker delivers keynote on "Adventure and Discovery." VIPs in reserved front section.',
|
||||
type: EventType.EVENT,
|
||||
status: EventStatus.SCHEDULED,
|
||||
notes: 'Gov. Martinez departs before keynote — not attending this one.',
|
||||
},
|
||||
});
|
||||
|
||||
// Private meeting - just Dr. Johnson and Ms. Williams
|
||||
await prisma.scheduleEvent.create({
|
||||
const donorMeeting = await prisma.scheduleEvent.create({
|
||||
data: {
|
||||
vipIds: [vip1.id, vip2.id],
|
||||
title: 'Donor Meeting',
|
||||
location: 'Conference Room A',
|
||||
startTime: new Date('2026-02-15T14:00:00'),
|
||||
endTime: new Date('2026-02-15T15:00:00'),
|
||||
description: 'Private meeting with development team',
|
||||
vipIds: [vipJames.id, vipPatricia.id, vipRoger.id],
|
||||
title: 'Donor Strategy Meeting',
|
||||
location: 'Eagle Lodge Conference Room',
|
||||
startTime: new Date(jamboreeDay1.getTime() + 16 * 60 * 60 * 1000), // 4:00 PM
|
||||
endTime: new Date(jamboreeDay1.getTime() + 17 * 60 * 60 * 1000), // 5:00 PM
|
||||
description: 'Private meeting: Whitfield Foundation partnership discussion with BSA leadership.',
|
||||
type: EventType.MEETING,
|
||||
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!');
|
||||
console.log('\nSample Users:');
|
||||
console.log('- Admin: admin@example.com');
|
||||
console.log('- Coordinator: coordinator@example.com');
|
||||
console.log('\nSample VIPs:');
|
||||
console.log('- Dr. Robert Johnson (Flight arrival)');
|
||||
console.log('- Ms. Sarah Williams (Self-driving)');
|
||||
console.log('- Emily Richardson (Harvard University)');
|
||||
console.log('- David Chen (Stanford)');
|
||||
console.log('\nSample Drivers:');
|
||||
console.log('- John Smith');
|
||||
console.log('- Jane Doe');
|
||||
console.log('- Amanda Washington');
|
||||
console.log('- Michael Thompson');
|
||||
console.log('\nSample Vehicles:');
|
||||
console.log('- Black Suburban (SUV, 6 seats)');
|
||||
console.log('- White Sprinter Van (Van, 12 seats)');
|
||||
console.log('- Blue Camry (Sedan, 4 seats)');
|
||||
console.log('- Gray Charter Bus (Bus, 40 seats)');
|
||||
console.log('\nSchedule Tasks (Multi-VIP Examples):');
|
||||
console.log('- 3 VIPs sharing SUV to Campfire (3/6 seats)');
|
||||
console.log('- 2 VIPs sharing sedan to Lunch (2/4 seats)');
|
||||
console.log('- 4 VIPs in van to Conference (4/12 seats)');
|
||||
console.log('- 1 VIP solo in sedan from Airport (1/4 seats)');
|
||||
// Day 2 shared events
|
||||
const eagleScoutCeremony = await prisma.scheduleEvent.create({
|
||||
data: {
|
||||
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipSusan.id],
|
||||
title: 'Eagle Scout Recognition Ceremony',
|
||||
location: 'Main Arena',
|
||||
startTime: new Date(jamboreeDay2.getTime() + 9 * 60 * 60 * 1000), // 9:00 AM
|
||||
endTime: new Date(jamboreeDay2.getTime() + 11 * 60 * 60 * 1000), // 11:00 AM
|
||||
description: 'Honoring 200+ new Eagle Scouts. James Whitfield giving remarks as Eagle Scout alumnus.',
|
||||
type: EventType.EVENT,
|
||||
status: EventStatus.SCHEDULED,
|
||||
},
|
||||
});
|
||||
|
||||
const farewellBrunch = await prisma.scheduleEvent.create({
|
||||
data: {
|
||||
vipIds: [vipRoger.id, vipPatricia.id, vipJames.id, vipDrBaker.id, vipSusan.id],
|
||||
title: 'Farewell Brunch',
|
||||
location: 'Eagle Lodge Private Dining',
|
||||
startTime: new Date(jamboreeDay2.getTime() + 11.5 * 60 * 60 * 1000), // 11:30 AM
|
||||
endTime: new Date(jamboreeDay2.getTime() + 13 * 60 * 60 * 1000), // 1:00 PM
|
||||
description: 'Final meal together before departures. Thank-you gifts distributed.',
|
||||
type: EventType.MEAL,
|
||||
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()
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { AppController } from './app.controller';
|
||||
import { AppService } from './app.service';
|
||||
import { PrismaModule } from './prisma/prisma.module';
|
||||
@@ -26,6 +27,12 @@ import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
||||
envFilePath: '.env',
|
||||
}),
|
||||
|
||||
// Rate limiting: 100 requests per 60 seconds per IP
|
||||
ThrottlerModule.forRoot([{
|
||||
ttl: 60000,
|
||||
limit: 100,
|
||||
}]),
|
||||
|
||||
// Core modules
|
||||
PrismaModule,
|
||||
AuthModule,
|
||||
@@ -51,6 +58,11 @@ import { JwtAuthGuard } from './auth/guards/jwt-auth.guard';
|
||||
provide: APP_GUARD,
|
||||
useClass: JwtAuthGuard,
|
||||
},
|
||||
// Apply rate limiting globally
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
],
|
||||
})
|
||||
export class AppModule {}
|
||||
|
||||
@@ -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 { Role, User, VIP, Driver, ScheduleEvent, Flight, Vehicle } from '@prisma/client';
|
||||
|
||||
|
||||
@@ -18,51 +18,55 @@ export class AuthService {
|
||||
const name = payload[`${namespace}/name`] || payload.name || 'Unknown User';
|
||||
const picture = payload[`${namespace}/picture`] || payload.picture;
|
||||
|
||||
// Check if user exists
|
||||
let user = await this.prisma.user.findUnique({
|
||||
// Check if user exists (soft-deleted users automatically excluded by middleware)
|
||||
let user = await this.prisma.user.findFirst({
|
||||
where: { auth0Id },
|
||||
include: { driver: true },
|
||||
});
|
||||
|
||||
if (!user) {
|
||||
// Check if this is the first user (auto-approve as admin)
|
||||
const approvedUserCount = await this.prisma.user.count({
|
||||
where: { isApproved: true, deletedAt: null },
|
||||
});
|
||||
const isFirstUser = approvedUserCount === 0;
|
||||
// Use serializable transaction to prevent race condition
|
||||
// where two simultaneous registrations both become admin
|
||||
user = await this.prisma.$transaction(async (tx) => {
|
||||
const approvedUserCount = await tx.user.count({
|
||||
where: { isApproved: true },
|
||||
});
|
||||
const isFirstUser = approvedUserCount === 0;
|
||||
|
||||
this.logger.log(
|
||||
`Creating new user: ${email} (approvedUserCount: ${approvedUserCount}, isFirstUser: ${isFirstUser})`,
|
||||
);
|
||||
this.logger.log(
|
||||
`Creating new user: ${email} (approvedUserCount: ${approvedUserCount}, isFirstUser: ${isFirstUser})`,
|
||||
);
|
||||
|
||||
// Create new user
|
||||
// First user is auto-approved as ADMINISTRATOR
|
||||
// Subsequent users default to DRIVER and require approval
|
||||
user = await this.prisma.user.create({
|
||||
data: {
|
||||
auth0Id,
|
||||
email,
|
||||
name,
|
||||
picture,
|
||||
role: isFirstUser ? Role.ADMINISTRATOR : Role.DRIVER,
|
||||
isApproved: isFirstUser, // Auto-approve first user only
|
||||
},
|
||||
include: { driver: true },
|
||||
});
|
||||
// First user is auto-approved as ADMINISTRATOR
|
||||
// Subsequent users default to DRIVER and require approval
|
||||
const newUser = await tx.user.create({
|
||||
data: {
|
||||
auth0Id,
|
||||
email,
|
||||
name,
|
||||
picture,
|
||||
role: isFirstUser ? Role.ADMINISTRATOR : Role.DRIVER,
|
||||
isApproved: isFirstUser,
|
||||
},
|
||||
include: { driver: true },
|
||||
});
|
||||
|
||||
this.logger.log(
|
||||
`User created: ${user.email} with role ${user.role} (approved: ${user.isApproved})`,
|
||||
);
|
||||
this.logger.log(
|
||||
`User created: ${newUser.email} with role ${newUser.role} (approved: ${newUser.isApproved})`,
|
||||
);
|
||||
|
||||
return newUser;
|
||||
}, { isolationLevel: 'Serializable' });
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user profile
|
||||
* Get current user profile (soft-deleted users automatically excluded by middleware)
|
||||
*/
|
||||
async getCurrentUser(auth0Id: string) {
|
||||
return this.prisma.user.findUnique({
|
||||
return this.prisma.user.findFirst({
|
||||
where: { auth0Id },
|
||||
include: { driver: true },
|
||||
});
|
||||
|
||||
1
backend/src/common/pipes/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './parse-boolean.pipe';
|
||||
49
backend/src/common/pipes/parse-boolean.pipe.ts
Normal 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`,
|
||||
);
|
||||
}
|
||||
}
|
||||
99
backend/src/common/utils/date.utils.ts
Normal 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;
|
||||
}
|
||||
78
backend/src/common/utils/hard-delete.utils.ts
Normal 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);
|
||||
}
|
||||
7
backend/src/common/utils/index.ts
Normal 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';
|
||||
462
backend/src/copilot/copilot-fleet.service.ts
Normal 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.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
304
backend/src/copilot/copilot-reports.service.ts
Normal 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.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
1282
backend/src/copilot/copilot-schedule.service.ts
Normal file
275
backend/src/copilot/copilot-vip.service.ts
Normal 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 },
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CopilotController } from './copilot.controller';
|
||||
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 { SignalModule } from '../signal/signal.module';
|
||||
import { DriversModule } from '../drivers/drivers.module';
|
||||
@@ -8,6 +12,12 @@ import { DriversModule } from '../drivers/drivers.module';
|
||||
@Module({
|
||||
imports: [PrismaModule, SignalModule, DriversModule],
|
||||
controllers: [CopilotController],
|
||||
providers: [CopilotService],
|
||||
providers: [
|
||||
CopilotService,
|
||||
CopilotVipService,
|
||||
CopilotScheduleService,
|
||||
CopilotFleetService,
|
||||
CopilotReportsService,
|
||||
],
|
||||
})
|
||||
export class CopilotModule {}
|
||||
|
||||
13
backend/src/drivers/decorators/current-driver.decorator.ts
Normal 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;
|
||||
},
|
||||
);
|
||||
1
backend/src/drivers/decorators/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './current-driver.decorator';
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
Param,
|
||||
Query,
|
||||
UseGuards,
|
||||
UseInterceptors,
|
||||
NotFoundException,
|
||||
} from '@nestjs/common';
|
||||
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 { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { CurrentDriver } from './decorators';
|
||||
import { ResolveDriverInterceptor } from './interceptors';
|
||||
import { Role } from '@prisma/client';
|
||||
import { CreateDriverDto, UpdateDriverDto } from './dto';
|
||||
import { toDateString } from '../common/utils/date.utils';
|
||||
import { ParseBooleanPipe } from '../common/pipes';
|
||||
|
||||
@Controller('drivers')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@@ -41,11 +46,8 @@ export class DriversController {
|
||||
|
||||
@Get('me')
|
||||
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
async getMyDriverProfile(@CurrentUser() user: any) {
|
||||
const driver = await this.driversService.findByUserId(user.id);
|
||||
if (!driver) {
|
||||
throw new NotFoundException('Driver profile not found for current user');
|
||||
}
|
||||
@UseInterceptors(ResolveDriverInterceptor)
|
||||
getMyDriverProfile(@CurrentDriver() driver: any) {
|
||||
return driver;
|
||||
}
|
||||
|
||||
@@ -55,22 +57,19 @@ export class DriversController {
|
||||
*/
|
||||
@Get('me/schedule/ics')
|
||||
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
@UseInterceptors(ResolveDriverInterceptor)
|
||||
async getMyScheduleICS(
|
||||
@CurrentUser() user: any,
|
||||
@CurrentDriver() driver: any,
|
||||
@Query('date') dateStr?: 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();
|
||||
// Default to full schedule (true) unless explicitly set to false
|
||||
const fullSchedule = fullScheduleStr !== 'false';
|
||||
const icsContent = await this.scheduleExportService.generateICS(driver.id, date, fullSchedule);
|
||||
const filename = fullSchedule
|
||||
? `full-schedule-${new Date().toISOString().split('T')[0]}.ics`
|
||||
: `schedule-${date.toISOString().split('T')[0]}.ics`;
|
||||
? `full-schedule-${toDateString(new Date())}.ics`
|
||||
: `schedule-${toDateString(date)}.ics`;
|
||||
return { ics: icsContent, filename };
|
||||
}
|
||||
|
||||
@@ -80,22 +79,19 @@ export class DriversController {
|
||||
*/
|
||||
@Get('me/schedule/pdf')
|
||||
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
@UseInterceptors(ResolveDriverInterceptor)
|
||||
async getMySchedulePDF(
|
||||
@CurrentUser() user: any,
|
||||
@CurrentDriver() driver: any,
|
||||
@Query('date') dateStr?: 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();
|
||||
// Default to full schedule (true) unless explicitly set to false
|
||||
const fullSchedule = fullScheduleStr !== 'false';
|
||||
const pdfBuffer = await this.scheduleExportService.generatePDF(driver.id, date, fullSchedule);
|
||||
const filename = fullSchedule
|
||||
? `full-schedule-${new Date().toISOString().split('T')[0]}.pdf`
|
||||
: `schedule-${date.toISOString().split('T')[0]}.pdf`;
|
||||
? `full-schedule-${toDateString(new Date())}.pdf`
|
||||
: `schedule-${toDateString(date)}.pdf`;
|
||||
return { pdf: pdfBuffer.toString('base64'), filename };
|
||||
}
|
||||
|
||||
@@ -105,14 +101,11 @@ export class DriversController {
|
||||
*/
|
||||
@Post('me/send-schedule')
|
||||
@Roles(Role.DRIVER, Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
@UseInterceptors(ResolveDriverInterceptor)
|
||||
async sendMySchedule(
|
||||
@CurrentUser() user: any,
|
||||
@CurrentDriver() driver: any,
|
||||
@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 format = body.format || 'both';
|
||||
// Default to full schedule (true) unless explicitly set to false
|
||||
@@ -122,11 +115,8 @@ export class DriversController {
|
||||
|
||||
@Patch('me')
|
||||
@Roles(Role.DRIVER)
|
||||
async updateMyProfile(@CurrentUser() user: any, @Body() updateDriverDto: UpdateDriverDto) {
|
||||
const driver = await this.driversService.findByUserId(user.id);
|
||||
if (!driver) {
|
||||
throw new NotFoundException('Driver profile not found for current user');
|
||||
}
|
||||
@UseInterceptors(ResolveDriverInterceptor)
|
||||
updateMyProfile(@CurrentDriver() driver: any, @Body() updateDriverDto: UpdateDriverDto) {
|
||||
return this.driversService.update(driver.id, updateDriverDto);
|
||||
}
|
||||
|
||||
@@ -219,9 +209,9 @@ export class DriversController {
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
remove(
|
||||
@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, isHardDelete);
|
||||
return this.driversService.remove(id, hard, user?.role);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateDriverDto, UpdateDriverDto } from './dto';
|
||||
import { executeHardDelete } from '../common/utils';
|
||||
|
||||
@Injectable()
|
||||
export class DriversService {
|
||||
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) {}
|
||||
|
||||
async create(createDriverDto: CreateDriverDto) {
|
||||
@@ -19,30 +28,15 @@ export class DriversService {
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.driver.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: {
|
||||
user: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { vehicle: true, driver: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
include: this.driverInclude,
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(id: string) {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
user: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { vehicle: true, driver: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
where: { id },
|
||||
include: this.driverInclude,
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -54,15 +48,8 @@ export class DriversService {
|
||||
|
||||
async findByUserId(userId: string) {
|
||||
return this.prisma.driver.findFirst({
|
||||
where: { userId, deletedAt: null },
|
||||
include: {
|
||||
user: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { vehicle: true, driver: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
where: { userId },
|
||||
include: this.driverInclude,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,20 +65,20 @@ export class DriversService {
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: string, hardDelete = false) {
|
||||
const driver = await this.findOne(id);
|
||||
|
||||
if (hardDelete) {
|
||||
this.logger.log(`Hard deleting driver: ${driver.name}`);
|
||||
return this.prisma.driver.delete({
|
||||
where: { id: driver.id },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(`Soft deleting driver: ${driver.name}`);
|
||||
return this.prisma.driver.update({
|
||||
where: { id: driver.id },
|
||||
data: { deletedAt: new Date() },
|
||||
async remove(id: string, hardDelete = false, userRole?: string) {
|
||||
return executeHardDelete({
|
||||
id,
|
||||
hardDelete,
|
||||
userRole,
|
||||
findOne: (id) => this.findOne(id),
|
||||
performHardDelete: (id) => this.prisma.driver.delete({ where: { id } }),
|
||||
performSoftDelete: (id) =>
|
||||
this.prisma.driver.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
}),
|
||||
entityName: 'Driver',
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
1
backend/src/drivers/interceptors/index.ts
Normal file
@@ -0,0 +1 @@
|
||||
export * from './resolve-driver.interceptor';
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SignalService } from '../signal/signal.service';
|
||||
import * as ics from 'ics';
|
||||
import * as PDFDocument from 'pdfkit';
|
||||
import { toDateString, startOfDay } from '../common/utils/date.utils';
|
||||
|
||||
interface ScheduleEventWithDetails {
|
||||
id: string;
|
||||
@@ -36,8 +37,7 @@ export class ScheduleExportService {
|
||||
driverId: string,
|
||||
date: Date,
|
||||
): Promise<ScheduleEventWithDetails[]> {
|
||||
const startOfDay = new Date(date);
|
||||
startOfDay.setHours(0, 0, 0, 0);
|
||||
const dayStart = startOfDay(date);
|
||||
|
||||
const endOfDay = new Date(date);
|
||||
endOfDay.setHours(23, 59, 59, 999);
|
||||
@@ -45,9 +45,8 @@ export class ScheduleExportService {
|
||||
const events = await this.prisma.scheduleEvent.findMany({
|
||||
where: {
|
||||
driverId,
|
||||
deletedAt: null,
|
||||
startTime: {
|
||||
gte: startOfDay,
|
||||
gte: dayStart,
|
||||
lte: endOfDay,
|
||||
},
|
||||
status: {
|
||||
@@ -71,13 +70,11 @@ export class ScheduleExportService {
|
||||
async getDriverFullSchedule(
|
||||
driverId: string,
|
||||
): Promise<ScheduleEventWithDetails[]> {
|
||||
const now = new Date();
|
||||
now.setHours(0, 0, 0, 0); // Start of today
|
||||
const now = startOfDay(new Date()); // Start of today
|
||||
|
||||
const events = await this.prisma.scheduleEvent.findMany({
|
||||
where: {
|
||||
driverId,
|
||||
deletedAt: null,
|
||||
endTime: {
|
||||
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> {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id: driverId, deletedAt: null },
|
||||
where: { id: driverId },
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -211,7 +208,7 @@ export class ScheduleExportService {
|
||||
*/
|
||||
async generatePDF(driverId: string, date: Date, fullSchedule = false): Promise<Buffer> {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id: driverId, deletedAt: null },
|
||||
where: { id: driverId },
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -358,7 +355,7 @@ export class ScheduleExportService {
|
||||
fullSchedule = false,
|
||||
): Promise<{ success: boolean; message: string }> {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id: driverId, deletedAt: null },
|
||||
where: { id: driverId },
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -411,8 +408,8 @@ export class ScheduleExportService {
|
||||
const icsContent = await this.generateICS(driverId, date, fullSchedule);
|
||||
const icsBase64 = Buffer.from(icsContent).toString('base64');
|
||||
const filename = fullSchedule
|
||||
? `full-schedule-${new Date().toISOString().split('T')[0]}.ics`
|
||||
: `schedule-${date.toISOString().split('T')[0]}.ics`;
|
||||
? `full-schedule-${toDateString(new Date())}.ics`
|
||||
: `schedule-${toDateString(date)}.ics`;
|
||||
|
||||
await this.signalService.sendMessageWithAttachment(
|
||||
fromNumber,
|
||||
@@ -435,8 +432,8 @@ export class ScheduleExportService {
|
||||
const pdfBuffer = await this.generatePDF(driverId, date, fullSchedule);
|
||||
const pdfBase64 = pdfBuffer.toString('base64');
|
||||
const filename = fullSchedule
|
||||
? `full-schedule-${new Date().toISOString().split('T')[0]}.pdf`
|
||||
: `schedule-${date.toISOString().split('T')[0]}.pdf`;
|
||||
? `full-schedule-${toDateString(new Date())}.pdf`
|
||||
: `schedule-${toDateString(date)}.pdf`;
|
||||
|
||||
await this.signalService.sendMessageWithAttachment(
|
||||
fromNumber,
|
||||
|
||||
@@ -55,4 +55,8 @@ export class CreateEventDto {
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
vehicleId?: string;
|
||||
|
||||
@IsUUID()
|
||||
@IsOptional()
|
||||
masterEventId?: string;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,6 @@ export class EventStatusService implements OnModuleInit, OnModuleDestroy {
|
||||
startTime: { lte: twentyMinutesFromNow, gt: now },
|
||||
reminder20MinSent: false,
|
||||
driverId: { not: null },
|
||||
deletedAt: null,
|
||||
},
|
||||
include: {
|
||||
driver: true,
|
||||
@@ -110,7 +109,6 @@ export class EventStatusService implements OnModuleInit, OnModuleDestroy {
|
||||
startTime: { lte: fiveMinutesFromNow, gt: now },
|
||||
reminder5MinSent: false,
|
||||
driverId: { not: null },
|
||||
deletedAt: null,
|
||||
},
|
||||
include: {
|
||||
driver: true,
|
||||
@@ -218,7 +216,6 @@ Reply:
|
||||
where: {
|
||||
status: EventStatus.SCHEDULED,
|
||||
startTime: { lte: now },
|
||||
deletedAt: null,
|
||||
},
|
||||
include: {
|
||||
driver: true,
|
||||
@@ -264,7 +261,6 @@ Reply:
|
||||
where: {
|
||||
status: EventStatus.IN_PROGRESS,
|
||||
endTime: { lte: gracePeriodAgo },
|
||||
deletedAt: null,
|
||||
},
|
||||
include: {
|
||||
driver: true,
|
||||
@@ -347,7 +343,6 @@ Reply with 1, 2, or 3`;
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: {
|
||||
phone: { contains: driverPhone.replace(/\D/g, '').slice(-10) },
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -360,7 +355,6 @@ Reply with 1, 2, or 3`;
|
||||
where: {
|
||||
driverId: driver.id,
|
||||
status: EventStatus.IN_PROGRESS,
|
||||
deletedAt: null,
|
||||
},
|
||||
include: { vehicle: true },
|
||||
});
|
||||
|
||||
@@ -13,8 +13,10 @@ import { EventsService } from './events.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Role } from '@prisma/client';
|
||||
import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto';
|
||||
import { ParseBooleanPipe } from '../common/pipes';
|
||||
|
||||
@Controller('events')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@@ -58,9 +60,9 @@ export class EventsController {
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
remove(
|
||||
@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, isHardDelete);
|
||||
return this.eventsService.remove(id, hard, user?.role);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,15 +2,28 @@ import {
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Logger,
|
||||
} from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateEventDto, UpdateEventDto, UpdateEventStatusDto } from './dto';
|
||||
import { executeHardDelete } from '../common/utils';
|
||||
|
||||
@Injectable()
|
||||
export class EventsService {
|
||||
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) {}
|
||||
|
||||
async create(createEventDto: CreateEventDto) {
|
||||
@@ -21,7 +34,6 @@ export class EventsService {
|
||||
const vips = await this.prisma.vIP.findMany({
|
||||
where: {
|
||||
id: { in: createEventDto.vipIds },
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -34,7 +46,7 @@ export class EventsService {
|
||||
if (createEventDto.vehicleId && createEventDto.vipIds) {
|
||||
await this.checkVehicleCapacity(
|
||||
createEventDto.vehicleId,
|
||||
createEventDto.vipIds.length,
|
||||
createEventDto.vipIds,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -68,10 +80,7 @@ export class EventsService {
|
||||
startTime: new Date(createEventDto.startTime),
|
||||
endTime: new Date(createEventDto.endTime),
|
||||
},
|
||||
include: {
|
||||
driver: true,
|
||||
vehicle: true,
|
||||
},
|
||||
include: this.eventInclude,
|
||||
});
|
||||
|
||||
return this.enrichEventWithVips(event);
|
||||
@@ -79,24 +88,45 @@ export class EventsService {
|
||||
|
||||
async findAll() {
|
||||
const events = await this.prisma.scheduleEvent.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: {
|
||||
driver: true,
|
||||
vehicle: true,
|
||||
},
|
||||
include: this.eventInclude,
|
||||
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) {
|
||||
const event = await this.prisma.scheduleEvent.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
driver: true,
|
||||
vehicle: true,
|
||||
},
|
||||
where: { id },
|
||||
include: this.eventInclude,
|
||||
});
|
||||
|
||||
if (!event) {
|
||||
@@ -114,7 +144,6 @@ export class EventsService {
|
||||
const vips = await this.prisma.vIP.findMany({
|
||||
where: {
|
||||
id: { in: updateEventDto.vipIds },
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -125,12 +154,10 @@ export class EventsService {
|
||||
|
||||
// Check vehicle capacity if vehicle or VIPs are being updated
|
||||
const vehicleId = updateEventDto.vehicleId || event.vehicleId;
|
||||
const vipCount = updateEventDto.vipIds
|
||||
? updateEventDto.vipIds.length
|
||||
: event.vipIds.length;
|
||||
const vipIds = updateEventDto.vipIds || event.vipIds;
|
||||
|
||||
if (vehicleId && vipCount > 0 && !updateEventDto.forceAssign) {
|
||||
await this.checkVehicleCapacity(vehicleId, vipCount);
|
||||
if (vehicleId && vipIds.length > 0 && !updateEventDto.forceAssign) {
|
||||
await this.checkVehicleCapacity(vehicleId, vipIds);
|
||||
}
|
||||
|
||||
// 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({
|
||||
where: { id: event.id },
|
||||
data: updateData,
|
||||
include: {
|
||||
driver: true,
|
||||
vehicle: true,
|
||||
},
|
||||
include: this.eventInclude,
|
||||
});
|
||||
|
||||
return this.enrichEventWithVips(updatedEvent);
|
||||
@@ -206,52 +230,56 @@ export class EventsService {
|
||||
const updatedEvent = await this.prisma.scheduleEvent.update({
|
||||
where: { id: event.id },
|
||||
data: { status: updateEventStatusDto.status },
|
||||
include: {
|
||||
driver: true,
|
||||
vehicle: true,
|
||||
},
|
||||
include: this.eventInclude,
|
||||
});
|
||||
|
||||
return this.enrichEventWithVips(updatedEvent);
|
||||
}
|
||||
|
||||
async remove(id: string, hardDelete = false) {
|
||||
const event = await this.findOne(id);
|
||||
|
||||
if (hardDelete) {
|
||||
this.logger.log(`Hard deleting event: ${event.title}`);
|
||||
return this.prisma.scheduleEvent.delete({
|
||||
where: { id: event.id },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(`Soft deleting event: ${event.title}`);
|
||||
return this.prisma.scheduleEvent.update({
|
||||
where: { id: event.id },
|
||||
data: { deletedAt: new Date() },
|
||||
async remove(id: string, hardDelete = false, userRole?: string) {
|
||||
return executeHardDelete({
|
||||
id,
|
||||
hardDelete,
|
||||
userRole,
|
||||
findOne: (id) => this.findOne(id),
|
||||
performHardDelete: (id) =>
|
||||
this.prisma.scheduleEvent.delete({ where: { id } }),
|
||||
performSoftDelete: (id) =>
|
||||
this.prisma.scheduleEvent.update({
|
||||
where: { id },
|
||||
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({
|
||||
where: { id: vehicleId, deletedAt: null },
|
||||
where: { id: vehicleId },
|
||||
});
|
||||
|
||||
if (!vehicle) {
|
||||
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(
|
||||
`Vehicle capacity exceeded: ${vipCount} VIPs > ${vehicle.seatCapacity} seats`,
|
||||
`Vehicle capacity exceeded: ${totalPeople} people > ${vehicle.seatCapacity} seats`,
|
||||
);
|
||||
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,
|
||||
requested: vipCount,
|
||||
requested: totalPeople,
|
||||
exceeded: true,
|
||||
});
|
||||
}
|
||||
@@ -269,7 +297,6 @@ export class EventsService {
|
||||
return this.prisma.scheduleEvent.findMany({
|
||||
where: {
|
||||
driverId,
|
||||
deletedAt: null,
|
||||
id: excludeEventId ? { not: excludeEventId } : undefined,
|
||||
OR: [
|
||||
{
|
||||
@@ -310,7 +337,6 @@ export class EventsService {
|
||||
const vips = await this.prisma.vIP.findMany({
|
||||
where: {
|
||||
id: { in: event.vipIds },
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
466
backend/src/flights/flight-tracking.service.ts
Normal 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;
|
||||
}
|
||||
}
|
||||
@@ -10,16 +10,21 @@ import {
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { FlightsService } from './flights.service';
|
||||
import { FlightTrackingService } from './flight-tracking.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { Role } from '@prisma/client';
|
||||
import { CreateFlightDto, UpdateFlightDto } from './dto';
|
||||
import { ParseBooleanPipe } from '../common/pipes';
|
||||
|
||||
@Controller('flights')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
export class FlightsController {
|
||||
constructor(private readonly flightsService: FlightsService) {}
|
||||
constructor(
|
||||
private readonly flightsService: FlightsService,
|
||||
private readonly flightTrackingService: FlightTrackingService,
|
||||
) {}
|
||||
|
||||
@Post()
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
@@ -33,6 +38,20 @@ export class FlightsController {
|
||||
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')
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
getFlightStatus(
|
||||
@@ -54,6 +73,12 @@ export class FlightsController {
|
||||
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')
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
update(@Param('id') id: string, @Body() updateFlightDto: UpdateFlightDto) {
|
||||
@@ -64,9 +89,8 @@ export class FlightsController {
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
remove(
|
||||
@Param('id') id: string,
|
||||
@Query('hard') hard?: string,
|
||||
@Query('hard', ParseBooleanPipe) hard: boolean,
|
||||
) {
|
||||
const isHardDelete = hard === 'true';
|
||||
return this.flightsService.remove(id, isHardDelete);
|
||||
return this.flightsService.remove(id, hard);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@ import { Module } from '@nestjs/common';
|
||||
import { HttpModule } from '@nestjs/axios';
|
||||
import { FlightsController } from './flights.controller';
|
||||
import { FlightsService } from './flights.service';
|
||||
import { FlightTrackingService } from './flight-tracking.service';
|
||||
|
||||
@Module({
|
||||
imports: [HttpModule],
|
||||
controllers: [FlightsController],
|
||||
providers: [FlightsService],
|
||||
exports: [FlightsService],
|
||||
providers: [FlightsService, FlightTrackingService],
|
||||
exports: [FlightsService, FlightTrackingService],
|
||||
})
|
||||
export class FlightsModule {}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ConfigService } from '@nestjs/config';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateFlightDto, UpdateFlightDto } from './dto';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { convertOptionalDates } from '../common/utils/date.utils';
|
||||
|
||||
@Injectable()
|
||||
export class FlightsService {
|
||||
@@ -24,17 +25,16 @@ export class FlightsService {
|
||||
`Creating flight: ${createFlightDto.flightNumber} for VIP ${createFlightDto.vipId}`,
|
||||
);
|
||||
|
||||
return this.prisma.flight.create({
|
||||
data: {
|
||||
const data = convertOptionalDates(
|
||||
{
|
||||
...createFlightDto,
|
||||
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 },
|
||||
});
|
||||
}
|
||||
@@ -71,24 +71,13 @@ export class FlightsService {
|
||||
|
||||
this.logger.log(`Updating flight ${id}: ${flight.flightNumber}`);
|
||||
|
||||
const updateData: any = { ...updateFlightDto };
|
||||
const dto = updateFlightDto as any; // Type assertion to work around PartialType
|
||||
|
||||
if (dto.flightDate) {
|
||||
updateData.flightDate = new Date(dto.flightDate);
|
||||
}
|
||||
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);
|
||||
}
|
||||
const updateData = convertOptionalDates(updateFlightDto, [
|
||||
'flightDate',
|
||||
'scheduledDeparture',
|
||||
'scheduledArrival',
|
||||
'actualDeparture',
|
||||
'actualArrival',
|
||||
]);
|
||||
|
||||
return this.prisma.flight.update({
|
||||
where: { id: flight.id },
|
||||
|
||||
@@ -33,6 +33,7 @@ export class DriverStatsDto {
|
||||
averageSpeedMph: number;
|
||||
totalTrips: number;
|
||||
totalDrivingMinutes: number;
|
||||
distanceMethod?: string; // 'osrm' or 'haversine'
|
||||
};
|
||||
recentLocations: LocationDataDto[];
|
||||
}
|
||||
|
||||
@@ -78,6 +78,15 @@ export class GpsController {
|
||||
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
|
||||
*/
|
||||
@@ -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')
|
||||
@Roles(Role.ADMINISTRATOR)
|
||||
@@ -108,34 +117,6 @@ export class GpsController {
|
||||
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
|
||||
// ============================================
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
BadRequestException,
|
||||
OnModuleInit,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Cron, CronExpression } from '@nestjs/schedule';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { SignalService } from '../signal/signal.service';
|
||||
@@ -27,6 +28,7 @@ export class GpsService implements OnModuleInit {
|
||||
private prisma: PrismaService,
|
||||
private traccarClient: TraccarClientService,
|
||||
private signalService: SignalService,
|
||||
private configService: ConfigService,
|
||||
) {}
|
||||
|
||||
async onModuleInit() {
|
||||
@@ -141,6 +143,7 @@ export class GpsService implements OnModuleInit {
|
||||
success: boolean;
|
||||
deviceIdentifier: string;
|
||||
serverUrl: string;
|
||||
qrCodeUrl: string;
|
||||
instructions: string;
|
||||
signalMessageSent?: boolean;
|
||||
}> {
|
||||
@@ -192,6 +195,23 @@ export class GpsService implements OnModuleInit {
|
||||
const serverUrl = this.traccarClient.getDeviceServerUrl();
|
||||
const settings = await this.getSettings();
|
||||
|
||||
// Build QR code URL for Traccar Client app
|
||||
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', actualDeviceId);
|
||||
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();
|
||||
|
||||
this.logger.log(`QR code URL for driver: ${qrCodeUrl}`);
|
||||
|
||||
const instructions = `
|
||||
GPS Tracking Setup Instructions for ${driver.name}:
|
||||
|
||||
@@ -199,15 +219,21 @@ GPS Tracking Setup Instructions for ${driver.name}:
|
||||
- iOS: https://apps.apple.com/app/traccar-client/id843156974
|
||||
- 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}
|
||||
- Server URL: ${serverUrl}
|
||||
- Location accuracy: Highest
|
||||
- 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();
|
||||
|
||||
let signalMessageSent = false;
|
||||
@@ -232,13 +258,58 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
deviceIdentifier: actualDeviceId, // Return what Traccar actually stored
|
||||
deviceIdentifier: actualDeviceId,
|
||||
serverUrl,
|
||||
qrCodeUrl,
|
||||
instructions,
|
||||
signalMessageSent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
@@ -314,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[]> {
|
||||
const devices = await this.prisma.gpsDevice.findMany({
|
||||
where: {
|
||||
isActive: true,
|
||||
driver: {
|
||||
deletedAt: null,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
driver: {
|
||||
@@ -370,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> {
|
||||
const device = await this.prisma.gpsDevice.findUnique({
|
||||
@@ -420,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(
|
||||
driverId: string,
|
||||
@@ -447,58 +606,54 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
const to = toDate || new Date();
|
||||
const from = fromDate || new Date(to.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
|
||||
// Get summary from Traccar
|
||||
let totalMiles = 0;
|
||||
const totalMiles = await this.calculateDistanceFromHistory(device.id, from, to);
|
||||
|
||||
// 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 topSpeedTimestamp: Date | null = null;
|
||||
let totalTrips = 0;
|
||||
let totalDrivingMinutes = 0;
|
||||
let currentTripStart: Date | null = null;
|
||||
let totalTrips = 0;
|
||||
|
||||
try {
|
||||
const summary = await this.traccarClient.getSummaryReport(
|
||||
device.traccarDeviceId,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
for (const pos of allPositions) {
|
||||
const speedMph = pos.speed || 0;
|
||||
|
||||
if (summary.length > 0) {
|
||||
const report = summary[0];
|
||||
// Distance is in meters, convert to miles
|
||||
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);
|
||||
if (speedMph > topSpeedMph) {
|
||||
topSpeedMph = speedMph;
|
||||
topSpeedTimestamp = pos.timestamp;
|
||||
}
|
||||
|
||||
// Get trips for additional stats
|
||||
const trips = await this.traccarClient.getTripReport(
|
||||
device.traccarDeviceId,
|
||||
from,
|
||||
to,
|
||||
);
|
||||
totalTrips = trips.length;
|
||||
|
||||
// Find top speed timestamp from positions
|
||||
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);
|
||||
if (speedMph > 5) {
|
||||
if (!currentTripStart) {
|
||||
currentTripStart = pos.timestamp;
|
||||
totalTrips++;
|
||||
}
|
||||
} else if (currentTripStart) {
|
||||
const tripDurationMs = pos.timestamp.getTime() - currentTripStart.getTime();
|
||||
totalDrivingMinutes += tripDurationMs / 60000;
|
||||
currentTripStart = null;
|
||||
}
|
||||
topSpeedMph = maxSpeed;
|
||||
} catch (error) {
|
||||
this.logger.warn(`Failed to fetch stats from Traccar: ${error}`);
|
||||
}
|
||||
|
||||
// Get recent locations from our database
|
||||
// Close last trip if still driving
|
||||
if (currentTripStart && allPositions.length > 0) {
|
||||
const lastPos = allPositions[allPositions.length - 1];
|
||||
const tripDurationMs = lastPos.timestamp.getTime() - currentTripStart.getTime();
|
||||
totalDrivingMinutes += tripDurationMs / 60000;
|
||||
}
|
||||
|
||||
// Get recent locations for display (last 100)
|
||||
const recentLocations = await this.prisma.gpsLocationHistory.findMany({
|
||||
where: {
|
||||
deviceId: device.id,
|
||||
@@ -511,6 +666,11 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
take: 100,
|
||||
});
|
||||
|
||||
const averageSpeedMph =
|
||||
totalDrivingMinutes > 0
|
||||
? totalMiles / (totalDrivingMinutes / 60)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
driverId,
|
||||
driverName: device.driver.name,
|
||||
@@ -522,11 +682,9 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
totalMiles: Math.round(totalMiles * 10) / 10,
|
||||
topSpeedMph: Math.round(topSpeedMph),
|
||||
topSpeedTimestamp,
|
||||
averageSpeedMph: totalDrivingMinutes > 0
|
||||
? Math.round((totalMiles / (totalDrivingMinutes / 60)) * 10) / 10
|
||||
: 0,
|
||||
averageSpeedMph: Math.round(averageSpeedMph * 10) / 10,
|
||||
totalTrips,
|
||||
totalDrivingMinutes,
|
||||
totalDrivingMinutes: Math.round(totalDrivingMinutes),
|
||||
},
|
||||
recentLocations: recentLocations.map((loc) => ({
|
||||
latitude: loc.latitude,
|
||||
@@ -545,7 +703,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
* Sync positions from Traccar to our database (for history/stats)
|
||||
* Called periodically via cron job
|
||||
*/
|
||||
@Cron(CronExpression.EVERY_MINUTE)
|
||||
@Cron(CronExpression.EVERY_30_SECONDS)
|
||||
async syncPositions(): Promise<void> {
|
||||
const devices = await this.prisma.gpsDevice.findMany({
|
||||
where: {
|
||||
@@ -553,39 +711,65 @@ 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 positions = await this.traccarClient.getAllPositions();
|
||||
const now = new Date();
|
||||
this.logger.log(`[GPS Sync] Starting sync for ${devices.length} active devices`);
|
||||
|
||||
for (const device of devices) {
|
||||
const position = positions.find((p) => p.deviceId === device.traccarDeviceId);
|
||||
if (!position) continue;
|
||||
for (const device of devices) {
|
||||
try {
|
||||
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({
|
||||
where: { id: device.id },
|
||||
data: { lastActive: new Date(position.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),
|
||||
},
|
||||
data: { lastActive: new Date(latestPosition.deviceTime) },
|
||||
});
|
||||
} catch (error) {
|
||||
this.logger.error(`[GPS Sync] Failed to sync positions for device ${device.traccarDeviceId}: ${error}`);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error(`Failed to sync positions: ${error}`);
|
||||
}
|
||||
|
||||
this.logger.log('[GPS Sync] Sync completed');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -612,11 +796,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
// Traccar User Sync (VIP Admin -> Traccar Admin)
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Generate a secure password for Traccar user
|
||||
*/
|
||||
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';
|
||||
return crypto
|
||||
.createHmac('sha256', secret)
|
||||
@@ -625,11 +805,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
.substring(0, 24);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a secure token for Traccar auto-login
|
||||
*/
|
||||
private generateTraccarToken(userId: string): string {
|
||||
// Generate deterministic token for auto-login
|
||||
const secret = process.env.JWT_SECRET || 'vip-coordinator-traccar-token';
|
||||
return crypto
|
||||
.createHmac('sha256', secret + '-token')
|
||||
@@ -638,9 +814,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
.substring(0, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync a VIP user to Traccar
|
||||
*/
|
||||
async syncUserToTraccar(user: User): Promise<boolean> {
|
||||
if (!user.email) return false;
|
||||
|
||||
@@ -654,7 +827,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
user.name || user.email,
|
||||
password,
|
||||
isAdmin,
|
||||
token, // Include token for auto-login
|
||||
token,
|
||||
);
|
||||
|
||||
this.logger.log(`Synced user ${user.email} to Traccar (admin: ${isAdmin})`);
|
||||
@@ -665,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 }> {
|
||||
const admins = await this.prisma.user.findMany({
|
||||
where: {
|
||||
role: 'ADMINISTRATOR',
|
||||
isApproved: true,
|
||||
deletedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -690,9 +859,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
return { synced, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get auto-login URL for Traccar (for admin users)
|
||||
*/
|
||||
async getTraccarAutoLoginUrl(user: User): Promise<{
|
||||
url: string;
|
||||
directAccess: boolean;
|
||||
@@ -701,30 +867,22 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
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);
|
||||
|
||||
// Get the token for auto-login
|
||||
const token = this.generateTraccarToken(user.id);
|
||||
const baseUrl = this.traccarClient.getTraccarUrl();
|
||||
|
||||
// Return URL with token parameter for auto-login
|
||||
// Traccar supports ?token=xxx for direct authentication
|
||||
return {
|
||||
url: `${baseUrl}?token=${token}`,
|
||||
directAccess: true,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get Traccar session cookie for a user (for proxy/iframe auth)
|
||||
*/
|
||||
async getTraccarSessionForUser(user: User): Promise<string | null> {
|
||||
if (user.role !== 'ADMINISTRATOR') {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Ensure user is synced
|
||||
await this.syncUserToTraccar(user);
|
||||
|
||||
const password = this.generateTraccarPassword(user.id);
|
||||
@@ -733,9 +891,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
return session?.cookie || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Traccar needs initial setup
|
||||
*/
|
||||
async checkTraccarSetup(): Promise<{
|
||||
needsSetup: boolean;
|
||||
isAvailable: boolean;
|
||||
@@ -749,11 +904,7 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
return { needsSetup, isAvailable };
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform initial Traccar setup
|
||||
*/
|
||||
async performTraccarSetup(adminEmail: string): Promise<boolean> {
|
||||
// Generate a secure password for the service account
|
||||
const servicePassword = crypto.randomBytes(16).toString('hex');
|
||||
|
||||
const success = await this.traccarClient.performInitialSetup(
|
||||
@@ -762,7 +913,6 @@ Note: GPS tracking is only active during shift hours (${settings.shiftStartHour}
|
||||
);
|
||||
|
||||
if (success) {
|
||||
// Save the service account credentials to settings
|
||||
await this.updateSettings({
|
||||
traccarAdminUser: adminEmail,
|
||||
traccarAdminPassword: servicePassword,
|
||||
|
||||
@@ -53,8 +53,8 @@ export class TraccarClientService implements OnModuleInit {
|
||||
private client: AxiosInstance;
|
||||
private readonly baseUrl: string;
|
||||
private sessionCookie: string | null = null;
|
||||
private adminUser: string = 'admin';
|
||||
private adminPassword: string = 'admin';
|
||||
private adminUser: string = '';
|
||||
private adminPassword: string = '';
|
||||
|
||||
constructor(private configService: ConfigService) {
|
||||
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
|
||||
*/
|
||||
async authenticate(): Promise<boolean> {
|
||||
if (!this.adminUser || !this.adminPassword) {
|
||||
this.logger.warn('Traccar credentials not configured - skipping authentication');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await this.client.post(
|
||||
'/api/session',
|
||||
@@ -316,7 +321,7 @@ export class TraccarClientService implements OnModuleInit {
|
||||
deviceId: number,
|
||||
from: Date,
|
||||
to: Date,
|
||||
): Promise<any[]> {
|
||||
): Promise<TraccarTrip[]> {
|
||||
const fromStr = from.toISOString();
|
||||
const toStr = to.toISOString();
|
||||
return this.request('get', `/api/reports/trips?deviceId=${deviceId}&from=${fromStr}&to=${toStr}`);
|
||||
@@ -562,3 +567,27 @@ export interface TraccarUser {
|
||||
token: string | null;
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import { ValidationPipe, Logger } from '@nestjs/common';
|
||||
import { json, urlencoded } from 'express';
|
||||
import helmet from 'helmet';
|
||||
import { AppModule } from './app.module';
|
||||
import { AllExceptionsFilter, HttpExceptionFilter } from './common/filters';
|
||||
|
||||
@@ -9,6 +10,9 @@ async function bootstrap() {
|
||||
|
||||
const app = await NestFactory.create(AppModule);
|
||||
|
||||
// Security headers
|
||||
app.use(helmet());
|
||||
|
||||
// Increase body size limit for PDF attachments (base64 encoded)
|
||||
app.use(json({ limit: '5mb' }));
|
||||
app.use(urlencoded({ extended: true, limit: '5mb' }));
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Injectable, OnModuleInit, OnModuleDestroy, Logger } from '@nestjs/common';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
// Models that have soft delete (deletedAt field)
|
||||
const SOFT_DELETE_MODELS = ['User', 'VIP', 'Driver', 'ScheduleEvent', 'Vehicle'];
|
||||
|
||||
@Injectable()
|
||||
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(PrismaService.name);
|
||||
@@ -9,18 +12,69 @@ export class PrismaService extends PrismaClient implements OnModuleInit, OnModul
|
||||
super({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
});
|
||||
|
||||
// Apply soft-delete middleware
|
||||
this.applySoftDeleteMiddleware();
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
try {
|
||||
await this.$connect();
|
||||
this.logger.log('✅ Database connected successfully');
|
||||
this.logger.log('✅ Soft-delete middleware active for: ' + SOFT_DELETE_MODELS.join(', '));
|
||||
} catch (error) {
|
||||
this.logger.error('❌ Database connection failed', 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() {
|
||||
await this.$disconnect();
|
||||
this.logger.log('Database disconnected');
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
MaxFileSizeValidator,
|
||||
FileTypeValidator,
|
||||
} from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { SettingsService } from './settings.service';
|
||||
import { UpdatePdfSettingsDto } from './dto/update-pdf-settings.dto';
|
||||
@@ -22,7 +23,41 @@ import { CanUpdate } from '../auth/decorators/check-ability.decorator';
|
||||
@Controller('settings')
|
||||
@UseGuards(JwtAuthGuard, AbilitiesGuard)
|
||||
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')
|
||||
@CanUpdate('Settings') // Admin-only (Settings subject is admin-only)
|
||||
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
@@ -6,16 +6,18 @@ import {
|
||||
Body,
|
||||
Param,
|
||||
Query,
|
||||
Req,
|
||||
UseGuards,
|
||||
Logger,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
import { Request, Response } from 'express';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { Public } from '../auth/decorators/public.decorator';
|
||||
import { MessagesService, SendMessageDto } from './messages.service';
|
||||
import { toDateString } from '../common/utils/date.utils';
|
||||
|
||||
// DTO for incoming Signal webhook
|
||||
interface SignalWebhookPayload {
|
||||
@@ -105,7 +107,14 @@ export class MessagesController {
|
||||
*/
|
||||
@Public()
|
||||
@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));
|
||||
|
||||
try {
|
||||
@@ -146,7 +155,7 @@ export class MessagesController {
|
||||
async exportMessages(@Res() res: Response) {
|
||||
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-Disposition', `attachment; filename="${filename}"`);
|
||||
|
||||
@@ -36,7 +36,7 @@ export class MessagesService {
|
||||
*/
|
||||
async getMessagesForDriver(driverId: string, limit: number = 50) {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id: driverId, deletedAt: null },
|
||||
where: { id: driverId },
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -55,7 +55,7 @@ export class MessagesService {
|
||||
*/
|
||||
async sendMessage(dto: SendMessageDto) {
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: { id: dto.driverId, deletedAt: null },
|
||||
where: { id: dto.driverId },
|
||||
});
|
||||
|
||||
if (!driver) {
|
||||
@@ -113,7 +113,6 @@ export class MessagesService {
|
||||
// Find driver by phone number
|
||||
const driver = await this.prisma.driver.findFirst({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
OR: [
|
||||
{ phone: fromNumber },
|
||||
{ phone: normalizedPhone },
|
||||
@@ -172,7 +171,6 @@ export class MessagesService {
|
||||
where: {
|
||||
driverId: driver.id,
|
||||
status: EventStatus.IN_PROGRESS,
|
||||
deletedAt: null,
|
||||
},
|
||||
include: { vehicle: true },
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { IsString, IsEnum, IsOptional } from 'class-validator';
|
||||
import { IsString, IsEnum, IsOptional, IsBoolean } from 'class-validator';
|
||||
import { Role } from '@prisma/client';
|
||||
|
||||
export class UpdateUserDto {
|
||||
@@ -9,4 +9,8 @@ export class UpdateUserDto {
|
||||
@IsEnum(Role)
|
||||
@IsOptional()
|
||||
role?: Role;
|
||||
|
||||
@IsBoolean()
|
||||
@IsOptional()
|
||||
isAlsoDriver?: boolean;
|
||||
}
|
||||
|
||||
@@ -11,7 +11,6 @@ export class UsersService {
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.user.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: { driver: true },
|
||||
orderBy: { createdAt: 'desc' },
|
||||
});
|
||||
@@ -19,7 +18,7 @@ export class UsersService {
|
||||
|
||||
async findOne(id: string) {
|
||||
const user = await this.prisma.user.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
where: { id },
|
||||
include: { driver: true },
|
||||
});
|
||||
|
||||
@@ -35,36 +34,75 @@ export class UsersService {
|
||||
|
||||
this.logger.log(`Updating user ${id}: ${JSON.stringify(updateUserDto)}`);
|
||||
|
||||
// Handle role change and Driver record synchronization
|
||||
if (updateUserDto.role && updateUserDto.role !== user.role) {
|
||||
// If changing TO DRIVER role, create a Driver record if one doesn't exist
|
||||
if (updateUserDto.role === Role.DRIVER && !user.driver) {
|
||||
const { isAlsoDriver, ...prismaData } = updateUserDto;
|
||||
const effectiveRole = updateUserDto.role || user.role;
|
||||
|
||||
const hasActiveDriver = user.driver && !user.driver.deletedAt;
|
||||
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(
|
||||
`Creating Driver record for user ${user.email} (role change to DRIVER)`,
|
||||
);
|
||||
await this.prisma.driver.create({
|
||||
data: {
|
||||
name: user.name || user.email,
|
||||
phone: user.email, // Use email as placeholder for phone
|
||||
phone: user.email,
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// If changing FROM DRIVER role to something else, remove the Driver record
|
||||
if (user.role === Role.DRIVER && updateUserDto.role !== Role.DRIVER && user.driver) {
|
||||
// When promoting FROM DRIVER to Admin/Coordinator, keep the driver record
|
||||
// (admin can explicitly uncheck the driver box later if they want)
|
||||
|
||||
// Handle "Also a Driver" toggle (independent of role)
|
||||
if (isAlsoDriver === true && !hasActiveDriver) {
|
||||
if (hasSoftDeletedDriver) {
|
||||
this.logger.log(
|
||||
`Removing Driver record for user ${user.email} (role change from DRIVER to ${updateUserDto.role})`,
|
||||
`Restoring soft-deleted Driver record for user ${user.email} (isAlsoDriver toggled on)`,
|
||||
);
|
||||
await this.prisma.driver.delete({
|
||||
where: { id: user.driver.id },
|
||||
await this.prisma.driver.update({
|
||||
where: { id: user.driver!.id },
|
||||
data: { deletedAt: null, name: user.name || user.email },
|
||||
});
|
||||
} else {
|
||||
this.logger.log(
|
||||
`Creating Driver record for user ${user.email} (isAlsoDriver toggled on)`,
|
||||
);
|
||||
await this.prisma.driver.create({
|
||||
data: {
|
||||
name: user.name || user.email,
|
||||
phone: user.email,
|
||||
userId: user.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (isAlsoDriver === false && hasActiveDriver && effectiveRole !== Role.DRIVER) {
|
||||
// Only allow removing driver record if user is NOT in the DRIVER role
|
||||
this.logger.log(
|
||||
`Soft-deleting Driver record for user ${user.email} (isAlsoDriver toggled off)`,
|
||||
);
|
||||
await this.prisma.driver.update({
|
||||
where: { id: user.driver!.id },
|
||||
data: { deletedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
return this.prisma.user.update({
|
||||
where: { id: user.id },
|
||||
data: updateUserDto,
|
||||
data: prismaData,
|
||||
include: { driver: true },
|
||||
});
|
||||
}
|
||||
@@ -97,7 +135,6 @@ export class UsersService {
|
||||
async getPendingUsers() {
|
||||
return this.prisma.user.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
isApproved: false,
|
||||
},
|
||||
orderBy: { createdAt: 'asc' },
|
||||
|
||||
@@ -13,8 +13,10 @@ import { VehiclesService } from './vehicles.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from '../auth/guards/roles.guard';
|
||||
import { Roles } from '../auth/decorators/roles.decorator';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import { Role } from '@prisma/client';
|
||||
import { CreateVehicleDto, UpdateVehicleDto } from './dto';
|
||||
import { ParseBooleanPipe } from '../common/pipes';
|
||||
|
||||
@Controller('vehicles')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@@ -56,8 +58,11 @@ export class VehiclesController {
|
||||
|
||||
@Delete(':id')
|
||||
@Roles(Role.ADMINISTRATOR, Role.COORDINATOR)
|
||||
remove(@Param('id') id: string, @Query('hard') hard?: string) {
|
||||
const isHardDelete = hard === 'true';
|
||||
return this.vehiclesService.remove(id, isHardDelete);
|
||||
remove(
|
||||
@Param('id') id: string,
|
||||
@Query('hard', ParseBooleanPipe) hard: boolean,
|
||||
@CurrentUser() user?: any,
|
||||
) {
|
||||
return this.vehiclesService.remove(id, hard, user?.role);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,20 @@
|
||||
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateVehicleDto, UpdateVehicleDto } from './dto';
|
||||
import { executeHardDelete } from '../common/utils';
|
||||
|
||||
@Injectable()
|
||||
export class VehiclesService {
|
||||
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) {}
|
||||
|
||||
async create(createVehicleDto: CreateVehicleDto) {
|
||||
@@ -13,27 +22,13 @@ export class VehiclesService {
|
||||
|
||||
return this.prisma.vehicle.create({
|
||||
data: createVehicleDto,
|
||||
include: {
|
||||
currentDriver: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { driver: true, vehicle: true },
|
||||
},
|
||||
},
|
||||
include: this.vehicleInclude,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.vehicle.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: {
|
||||
currentDriver: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { driver: true, vehicle: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
include: this.vehicleInclude,
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
}
|
||||
@@ -41,7 +36,6 @@ export class VehiclesService {
|
||||
async findAvailable() {
|
||||
return this.prisma.vehicle.findMany({
|
||||
where: {
|
||||
deletedAt: null,
|
||||
status: 'AVAILABLE',
|
||||
},
|
||||
include: {
|
||||
@@ -53,15 +47,8 @@ export class VehiclesService {
|
||||
|
||||
async findOne(id: string) {
|
||||
const vehicle = await this.prisma.vehicle.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
currentDriver: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { driver: true, vehicle: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
where: { id },
|
||||
include: this.vehicleInclude,
|
||||
});
|
||||
|
||||
if (!vehicle) {
|
||||
@@ -79,30 +66,24 @@ export class VehiclesService {
|
||||
return this.prisma.vehicle.update({
|
||||
where: { id: vehicle.id },
|
||||
data: updateVehicleDto,
|
||||
include: {
|
||||
currentDriver: true,
|
||||
events: {
|
||||
where: { deletedAt: null },
|
||||
include: { driver: true, vehicle: true },
|
||||
},
|
||||
},
|
||||
include: this.vehicleInclude,
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: string, hardDelete = false) {
|
||||
const vehicle = await this.findOne(id);
|
||||
|
||||
if (hardDelete) {
|
||||
this.logger.log(`Hard deleting vehicle: ${vehicle.name}`);
|
||||
return this.prisma.vehicle.delete({
|
||||
where: { id: vehicle.id },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(`Soft deleting vehicle: ${vehicle.name}`);
|
||||
return this.prisma.vehicle.update({
|
||||
where: { id: vehicle.id },
|
||||
data: { deletedAt: new Date() },
|
||||
async remove(id: string, hardDelete = false, userRole?: string) {
|
||||
return executeHardDelete({
|
||||
id,
|
||||
hardDelete,
|
||||
userRole,
|
||||
findOne: (id) => this.findOne(id),
|
||||
performHardDelete: (id) => this.prisma.vehicle.delete({ where: { id } }),
|
||||
performSoftDelete: (id) =>
|
||||
this.prisma.vehicle.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
}),
|
||||
entityName: 'Vehicle',
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -110,24 +91,33 @@ export class VehiclesService {
|
||||
* Get vehicle utilization statistics
|
||||
*/
|
||||
async getUtilization() {
|
||||
const vehicles = await this.findAll();
|
||||
const now = new Date();
|
||||
|
||||
const stats = vehicles.map((vehicle) => {
|
||||
const upcomingEvents = vehicle.events.filter(
|
||||
(event) => new Date(event.startTime) > new Date(),
|
||||
);
|
||||
|
||||
return {
|
||||
id: vehicle.id,
|
||||
name: vehicle.name,
|
||||
type: vehicle.type,
|
||||
seatCapacity: vehicle.seatCapacity,
|
||||
status: vehicle.status,
|
||||
upcomingTrips: upcomingEvents.length,
|
||||
currentDriver: vehicle.currentDriver?.name,
|
||||
};
|
||||
// Fetch vehicles with only upcoming events (filtered at database level)
|
||||
const vehicles = await this.prisma.vehicle.findMany({
|
||||
include: {
|
||||
currentDriver: true,
|
||||
events: {
|
||||
where: {
|
||||
startTime: { gt: now }, // Only fetch upcoming events
|
||||
},
|
||||
include: { driver: true, vehicle: true },
|
||||
orderBy: { startTime: 'asc' },
|
||||
},
|
||||
},
|
||||
orderBy: { name: 'asc' },
|
||||
});
|
||||
|
||||
const stats = vehicles.map((vehicle) => ({
|
||||
id: vehicle.id,
|
||||
name: vehicle.name,
|
||||
type: vehicle.type,
|
||||
seatCapacity: vehicle.seatCapacity,
|
||||
status: vehicle.status,
|
||||
upcomingTrips: vehicle.events.length, // Already filtered at DB level
|
||||
currentDriver: vehicle.currentDriver?.name,
|
||||
}));
|
||||
|
||||
return {
|
||||
totalVehicles: vehicles.length,
|
||||
available: vehicles.filter((v) => v.status === 'AVAILABLE').length,
|
||||
|
||||
@@ -4,6 +4,9 @@ import {
|
||||
IsOptional,
|
||||
IsBoolean,
|
||||
IsDateString,
|
||||
IsInt,
|
||||
IsEmail,
|
||||
Min,
|
||||
} from 'class-validator';
|
||||
import { Department, ArrivalMode } from '@prisma/client';
|
||||
|
||||
@@ -33,7 +36,35 @@ export class CreateVipDto {
|
||||
@IsOptional()
|
||||
venueTransport?: boolean;
|
||||
|
||||
@IsInt()
|
||||
@IsOptional()
|
||||
@Min(1)
|
||||
partySize?: number;
|
||||
|
||||
@IsString()
|
||||
@IsOptional()
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,9 @@ import { VipsService } from './vips.service';
|
||||
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
|
||||
import { AbilitiesGuard } from '../auth/guards/abilities.guard';
|
||||
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 { ParseBooleanPipe } from '../common/pipes';
|
||||
|
||||
@Controller('vips')
|
||||
@UseGuards(JwtAuthGuard, AbilitiesGuard)
|
||||
@@ -48,10 +50,9 @@ export class VipsController {
|
||||
@CanDelete('VIP')
|
||||
remove(
|
||||
@Param('id') id: string,
|
||||
@Query('hard') hard?: string,
|
||||
@Query('hard', ParseBooleanPipe) hard: boolean,
|
||||
@CurrentUser() user?: any,
|
||||
) {
|
||||
// Only administrators can hard delete
|
||||
const isHardDelete = hard === 'true';
|
||||
return this.vipsService.remove(id, isHardDelete);
|
||||
return this.vipsService.remove(id, hard, user?.role);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable, NotFoundException, Logger } from '@nestjs/common';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { CreateVipDto, UpdateVipDto } from './dto';
|
||||
import { executeHardDelete } from '../common/utils';
|
||||
|
||||
@Injectable()
|
||||
export class VipsService {
|
||||
@@ -21,7 +22,6 @@ export class VipsService {
|
||||
|
||||
async findAll() {
|
||||
return this.prisma.vIP.findMany({
|
||||
where: { deletedAt: null },
|
||||
include: {
|
||||
flights: true,
|
||||
},
|
||||
@@ -31,7 +31,7 @@ export class VipsService {
|
||||
|
||||
async findOne(id: string) {
|
||||
const vip = await this.prisma.vIP.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
where: { id },
|
||||
include: {
|
||||
flights: true,
|
||||
},
|
||||
@@ -58,20 +58,20 @@ export class VipsService {
|
||||
});
|
||||
}
|
||||
|
||||
async remove(id: string, hardDelete = false) {
|
||||
const vip = await this.findOne(id);
|
||||
|
||||
if (hardDelete) {
|
||||
this.logger.log(`Hard deleting VIP: ${vip.name}`);
|
||||
return this.prisma.vIP.delete({
|
||||
where: { id: vip.id },
|
||||
});
|
||||
}
|
||||
|
||||
this.logger.log(`Soft deleting VIP: ${vip.name}`);
|
||||
return this.prisma.vIP.update({
|
||||
where: { id: vip.id },
|
||||
data: { deletedAt: new Date() },
|
||||
async remove(id: string, hardDelete = false, userRole?: string) {
|
||||
return executeHardDelete({
|
||||
id,
|
||||
hardDelete,
|
||||
userRole,
|
||||
findOne: (id) => this.findOne(id),
|
||||
performHardDelete: (id) => this.prisma.vIP.delete({ where: { id } }),
|
||||
performSoftDelete: (id) =>
|
||||
this.prisma.vIP.update({
|
||||
where: { id },
|
||||
data: { deletedAt: new Date() },
|
||||
}),
|
||||
entityName: 'VIP',
|
||||
logger: this.logger,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ services:
|
||||
|
||||
# Traccar GPS Tracking Server
|
||||
traccar:
|
||||
image: traccar/traccar:latest
|
||||
image: traccar/traccar:6.11
|
||||
container_name: vip-traccar
|
||||
ports:
|
||||
- "8082:8082" # Web UI & API
|
||||
@@ -80,6 +80,7 @@ services:
|
||||
DATABASE_URL: postgresql://postgres:changeme@postgres:5432/vip_coordinator
|
||||
REDIS_URL: redis://redis:6379
|
||||
SIGNAL_API_URL: http://signal-api:8080
|
||||
SIGNAL_WEBHOOK_SECRET: ${SIGNAL_WEBHOOK_SECRET:-}
|
||||
TRACCAR_API_URL: http://traccar:8082
|
||||
TRACCAR_DEVICE_PORT: 5055
|
||||
AUTH0_DOMAIN: ${AUTH0_DOMAIN}
|
||||
|
||||
630
docs/USER_GUIDE.md
Normal 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.
|
||||
|
||||

|
||||
|
||||
3. You will be redirected to the Auth0 login screen. Enter your email address and password, then click **Continue**.
|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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:
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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
|
||||
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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.
|
||||
|
||||

|
||||
|
||||
**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:
|
||||
|
||||

|
||||
|
||||
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
|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
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.
|
||||
|
||||

|
||||
|
||||
### 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.
|
||||
|
||||

|
||||
|
||||
### 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.
|
||||
|
||||

|
||||
|
||||
**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.*
|
||||
@@ -46,7 +46,7 @@ EXPOSE 80
|
||||
|
||||
# Health check
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost/ || exit 1
|
||||
CMD wget --no-verbose --tries=1 --spider http://127.0.0.1/ || exit 1
|
||||
|
||||
# Start nginx
|
||||
CMD ["nginx", "-g", "daemon off;"]
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>VIP Coordinator</title>
|
||||
<!-- Prevent FOUC (Flash of Unstyled Content) for theme -->
|
||||
|
||||
20
frontend/package-lock.json
generated
@@ -11,12 +11,12 @@
|
||||
"@auth0/auth0-react": "^2.2.4",
|
||||
"@casl/ability": "^6.8.0",
|
||||
"@casl/react": "^5.0.1",
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"@react-pdf/renderer": "^4.3.2",
|
||||
"@tanstack/react-query": "^5.17.19",
|
||||
"axios": "^1.6.5",
|
||||
"clsx": "^2.1.0",
|
||||
"date-fns": "^3.2.0",
|
||||
"fuse.js": "^7.1.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.309.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
@@ -912,15 +912,6 @@
|
||||
"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": {
|
||||
"version": "0.13.0",
|
||||
"resolved": "https://registry.npmjs.org/@humanwhocodes/config-array/-/config-array-0.13.0.tgz",
|
||||
@@ -3452,6 +3443,15 @@
|
||||
"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": {
|
||||
"version": "1.0.0-beta.2",
|
||||
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
|
||||
|
||||
@@ -18,12 +18,12 @@
|
||||
"@auth0/auth0-react": "^2.2.4",
|
||||
"@casl/ability": "^6.8.0",
|
||||
"@casl/react": "^5.0.1",
|
||||
"@heroicons/react": "^2.2.0",
|
||||
"@react-pdf/renderer": "^4.3.2",
|
||||
"@tanstack/react-query": "^5.17.19",
|
||||
"axios": "^1.6.5",
|
||||
"clsx": "^2.1.0",
|
||||
"date-fns": "^3.2.0",
|
||||
"fuse.js": "^7.1.0",
|
||||
"leaflet": "^1.9.4",
|
||||
"lucide-react": "^0.309.0",
|
||||
"qrcode.react": "^4.2.0",
|
||||
|
||||
12
frontend/public/favicon.svg
Normal file
@@ -0,0 +1,12 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stop-color="#3b82f6"/>
|
||||
<stop offset="100%" stop-color="#1d4ed8"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="32" height="32" rx="6" fill="url(#bg)"/>
|
||||
<g transform="translate(4,4)" fill="none" stroke="white" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 665 B |
BIN
frontend/public/help-assets/screenshots/01-login-page.png
Normal file
|
After Width: | Height: | Size: 468 KiB |
BIN
frontend/public/help-assets/screenshots/02-auth0-login.png
Normal file
|
After Width: | Height: | Size: 23 KiB |
BIN
frontend/public/help-assets/screenshots/03-dashboard.png
Normal file
|
After Width: | Height: | Size: 64 KiB |
BIN
frontend/public/help-assets/screenshots/04-war-room.png
Normal file
|
After Width: | Height: | Size: 70 KiB |
BIN
frontend/public/help-assets/screenshots/05-vip-list.png
Normal file
|
After Width: | Height: | Size: 82 KiB |
BIN
frontend/public/help-assets/screenshots/06-vip-edit-form.png
Normal file
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 93 KiB |
BIN
frontend/public/help-assets/screenshots/08-fleet-drivers.png
Normal file
|
After Width: | Height: | Size: 77 KiB |
BIN
frontend/public/help-assets/screenshots/09-fleet-vehicles.png
Normal file
|
After Width: | Height: | Size: 80 KiB |
BIN
frontend/public/help-assets/screenshots/10-activities.png
Normal file
|
After Width: | Height: | Size: 97 KiB |
BIN
frontend/public/help-assets/screenshots/11-flights.png
Normal file
|
After Width: | Height: | Size: 109 KiB |
BIN
frontend/public/help-assets/screenshots/12-reports.png
Normal file
|
After Width: | Height: | Size: 101 KiB |
BIN
frontend/public/help-assets/screenshots/13-users.png
Normal file
|
After Width: | Height: | Size: 71 KiB |
BIN
frontend/public/help-assets/screenshots/14-admin-tools.png
Normal file
|
After Width: | Height: | Size: 170 KiB |
BIN
frontend/public/help-assets/screenshots/15-gps-tracking.png
Normal file
|
After Width: | Height: | Size: 1.3 MiB |
BIN
frontend/public/help-assets/screenshots/16-gps-devices.png
Normal file
|
After Width: | Height: | Size: 55 KiB |
BIN
frontend/public/help-assets/screenshots/17-gps-settings.png
Normal file
|
After Width: | Height: | Size: 65 KiB |
BIN
frontend/public/help-assets/screenshots/18-ai-assistant.png
Normal file
|
After Width: | Height: | Size: 84 KiB |
@@ -4,6 +4,7 @@ import { Auth0Provider } from '@auth0/auth0-react';
|
||||
import { Toaster } from 'react-hot-toast';
|
||||
import { AuthProvider } from '@/contexts/AuthContext';
|
||||
import { AbilityProvider } from '@/contexts/AbilityContext';
|
||||
import { TimezoneProvider } from '@/contexts/TimezoneContext';
|
||||
import { ThemeProvider } from '@/contexts/ThemeContext';
|
||||
import { ProtectedRoute } from '@/components/ProtectedRoute';
|
||||
import { Layout } from '@/components/Layout';
|
||||
@@ -13,10 +14,9 @@ import { Callback } from '@/pages/Callback';
|
||||
import { PendingApproval } from '@/pages/PendingApproval';
|
||||
import { Dashboard } from '@/pages/Dashboard';
|
||||
import { CommandCenter } from '@/pages/CommandCenter';
|
||||
import { VIPList } from '@/pages/VipList';
|
||||
import { VIPList } from '@/pages/VIPList';
|
||||
import { VIPSchedule } from '@/pages/VIPSchedule';
|
||||
import { DriverList } from '@/pages/DriverList';
|
||||
import { VehicleList } from '@/pages/VehicleList';
|
||||
import { FleetPage } from '@/pages/FleetPage';
|
||||
import { EventList } from '@/pages/EventList';
|
||||
import { FlightList } from '@/pages/FlightList';
|
||||
import { UserList } from '@/pages/UserList';
|
||||
@@ -24,6 +24,8 @@ import { AdminTools } from '@/pages/AdminTools';
|
||||
import { DriverProfile } from '@/pages/DriverProfile';
|
||||
import { MySchedule } from '@/pages/MySchedule';
|
||||
import { GpsTracking } from '@/pages/GpsTracking';
|
||||
import { Reports } from '@/pages/Reports';
|
||||
import { Help } from '@/pages/Help';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
// Smart redirect based on user role
|
||||
@@ -67,6 +69,7 @@ function App() {
|
||||
>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AuthProvider>
|
||||
<TimezoneProvider>
|
||||
<AbilityProvider>
|
||||
<BrowserRouter
|
||||
future={{
|
||||
@@ -115,13 +118,16 @@ function App() {
|
||||
<Route path="/command-center" element={<CommandCenter />} />
|
||||
<Route path="/vips" element={<VIPList />} />
|
||||
<Route path="/vips/:id/schedule" element={<VIPSchedule />} />
|
||||
<Route path="/drivers" element={<DriverList />} />
|
||||
<Route path="/vehicles" element={<VehicleList />} />
|
||||
<Route path="/fleet" element={<FleetPage />} />
|
||||
<Route path="/drivers" element={<Navigate to="/fleet?tab=drivers" replace />} />
|
||||
<Route path="/vehicles" element={<Navigate to="/fleet?tab=vehicles" replace />} />
|
||||
<Route path="/events" element={<EventList />} />
|
||||
<Route path="/flights" element={<FlightList />} />
|
||||
<Route path="/users" element={<UserList />} />
|
||||
<Route path="/admin-tools" element={<AdminTools />} />
|
||||
<Route path="/gps-tracking" element={<GpsTracking />} />
|
||||
<Route path="/reports" element={<Reports />} />
|
||||
<Route path="/help" element={<Help />} />
|
||||
<Route path="/profile" element={<DriverProfile />} />
|
||||
<Route path="/my-schedule" element={<MySchedule />} />
|
||||
<Route path="/" element={<HomeRedirect />} />
|
||||
@@ -134,6 +140,7 @@ function App() {
|
||||
</Routes>
|
||||
</BrowserRouter>
|
||||
</AbilityProvider>
|
||||
</TimezoneProvider>
|
||||
</AuthProvider>
|
||||
</QueryClientProvider>
|
||||
</Auth0Provider>
|
||||
|
||||
524
frontend/src/components/AccountabilityRosterPDF.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
90
frontend/src/components/ConfirmModal.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { X, Send, Loader2 } from 'lucide-react';
|
||||
import { useDriverMessages, useSendMessage, useMarkMessagesAsRead } from '../hooks/useSignalMessages';
|
||||
import { useFormattedDate } from '@/hooks/useFormattedDate';
|
||||
|
||||
interface Driver {
|
||||
id: string;
|
||||
@@ -18,6 +19,7 @@ export function DriverChatModal({ driver, isOpen, onClose }: DriverChatModalProp
|
||||
const [message, setMessage] = useState('');
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const { formatDateTime } = useFormattedDate();
|
||||
|
||||
const { data: messages, isLoading } = useDriverMessages(driver?.id || null, isOpen);
|
||||
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 (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50">
|
||||
<div
|
||||
@@ -126,7 +112,7 @@ export function DriverChatModal({ driver, isOpen, onClose }: DriverChatModalProp
|
||||
<p className={`text-[10px] mt-1 ${
|
||||
msg.direction === 'OUTBOUND' ? 'text-primary-foreground/70' : 'text-muted-foreground/70'
|
||||
}`}>
|
||||
{formatTime(msg.timestamp)}
|
||||
{formatDateTime(msg.timestamp)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { X } from 'lucide-react';
|
||||
import { DEPARTMENT_LABELS } from '@/lib/enum-labels';
|
||||
|
||||
interface DriverFormProps {
|
||||
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"
|
||||
>
|
||||
<option value="">Select Department</option>
|
||||
<option value="OFFICE_OF_DEVELOPMENT">Office of Development</option>
|
||||
<option value="ADMIN">Admin</option>
|
||||
{Object.entries(DEPARTMENT_LABELS).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
|
||||
147
frontend/src/components/DriverLocationModal.tsx
Normal 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 © 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>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { api } from '@/lib/api';
|
||||
import { X, Calendar, Clock, MapPin, Car, User, ChevronLeft, ChevronRight } from 'lucide-react';
|
||||
import { Driver } from '@/types';
|
||||
import { useState } from 'react';
|
||||
import { useFormattedDate } from '@/hooks/useFormattedDate';
|
||||
|
||||
interface ScheduleEvent {
|
||||
id: string;
|
||||
@@ -36,6 +37,7 @@ interface DriverScheduleModalProps {
|
||||
|
||||
export function DriverScheduleModal({ driver, isOpen, onClose }: DriverScheduleModalProps) {
|
||||
const [selectedDate, setSelectedDate] = useState(new Date());
|
||||
const { formatDate, formatTime } = useFormattedDate();
|
||||
|
||||
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 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) => {
|
||||
switch (status) {
|
||||
case 'COMPLETED':
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState, useMemo } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
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 { 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 {
|
||||
event?: ScheduleEvent | null;
|
||||
@@ -27,6 +30,7 @@ export interface EventFormData {
|
||||
status: string;
|
||||
driverId?: string;
|
||||
vehicleId?: string;
|
||||
masterEventId?: string;
|
||||
forceAssign?: boolean;
|
||||
}
|
||||
|
||||
@@ -38,17 +42,7 @@ interface ScheduleConflict {
|
||||
}
|
||||
|
||||
export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraActions }: EventFormProps) {
|
||||
// Helper to convert ISO datetime to datetime-local format
|
||||
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 { formatDateTime } = useFormattedDate();
|
||||
|
||||
const [formData, setFormData] = useState<EventFormData>({
|
||||
vipIds: event?.vipIds || [],
|
||||
@@ -63,6 +57,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
status: event?.status || 'SCHEDULED',
|
||||
driverId: event?.driverId || '',
|
||||
vehicleId: event?.vehicleId || '',
|
||||
masterEventId: event?.masterEventId || '',
|
||||
});
|
||||
|
||||
const [showConflictDialog, setShowConflictDialog] = useState(false);
|
||||
@@ -73,7 +68,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
|
||||
// Fetch VIPs for selection
|
||||
const { data: vips } = useQuery<VIP[]>({
|
||||
queryKey: ['vips'],
|
||||
queryKey: queryKeys.vips.all,
|
||||
queryFn: async () => {
|
||||
const { data } = await api.get('/vips');
|
||||
return data;
|
||||
@@ -82,7 +77,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
|
||||
// Fetch Drivers for dropdown
|
||||
const { data: drivers } = useQuery<Driver[]>({
|
||||
queryKey: ['drivers'],
|
||||
queryKey: queryKeys.drivers.all,
|
||||
queryFn: async () => {
|
||||
const { data } = await api.get('/drivers');
|
||||
return data;
|
||||
@@ -91,16 +86,37 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
|
||||
// Fetch Vehicles for dropdown
|
||||
const { data: vehicles } = useQuery<Vehicle[]>({
|
||||
queryKey: ['vehicles'],
|
||||
queryKey: queryKeys.vehicles.all,
|
||||
queryFn: async () => {
|
||||
const { data } = await api.get('/vehicles');
|
||||
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 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 handleSubmit = (e: React.FormEvent) => {
|
||||
@@ -117,6 +133,7 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
description: formData.description || undefined,
|
||||
driverId: formData.driverId || undefined,
|
||||
vehicleId: formData.vehicleId || undefined,
|
||||
masterEventId: formData.masterEventId || undefined,
|
||||
};
|
||||
|
||||
// Store for potential retry
|
||||
@@ -193,10 +210,12 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
});
|
||||
};
|
||||
|
||||
const selectedVipNames = vips
|
||||
?.filter(vip => formData.vipIds.includes(vip.id))
|
||||
.map(vip => vip.name)
|
||||
.join(', ') || 'None selected';
|
||||
const selectedVipNames = useMemo(() => {
|
||||
return vips
|
||||
?.filter(vip => formData.vipIds.includes(vip.id))
|
||||
.map(vip => vip.partySize > 1 ? `${vip.name} (+${vip.partySize - 1})` : vip.name)
|
||||
.join(', ') || 'None selected';
|
||||
}, [vips, formData.vipIds]);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -216,6 +235,42 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
</div>
|
||||
|
||||
<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 */}
|
||||
<div>
|
||||
<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">
|
||||
{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 && (
|
||||
<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>
|
||||
{selectedVehicle && (
|
||||
<div className={`mt-2 text-sm ${seatsUsed > seatsAvailable ? 'text-red-600 font-medium' : 'text-muted-foreground'}`}>
|
||||
Capacity: {seatsUsed}/{seatsAvailable} seats used
|
||||
{seatsUsed > seatsAvailable && ' ⚠️ OVER CAPACITY'}
|
||||
Capacity: {seatsUsed}/{seatsAvailable} seats (incl. entourage)
|
||||
{seatsUsed > seatsAvailable && ' — OVER CAPACITY'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -387,11 +445,11 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
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"
|
||||
>
|
||||
<option value="TRANSPORT">Transport</option>
|
||||
<option value="MEETING">Meeting</option>
|
||||
<option value="EVENT">Event</option>
|
||||
<option value="MEAL">Meal</option>
|
||||
<option value="ACCOMMODATION">Accommodation</option>
|
||||
{Object.entries(EVENT_TYPE_LABELS).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
@@ -405,10 +463,11 @@ export function EventForm({ event, onSubmit, onCancel, isSubmitting, extraAction
|
||||
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"
|
||||
>
|
||||
<option value="SCHEDULED">Scheduled</option>
|
||||
<option value="IN_PROGRESS">In Progress</option>
|
||||
<option value="COMPLETED">Completed</option>
|
||||
<option value="CANCELLED">Cancelled</option>
|
||||
{Object.entries(EVENT_STATUS_LABELS).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
467
frontend/src/components/FlightCard.tsx
Normal 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;
|
||||
}
|
||||
237
frontend/src/components/FlightProgressBar.tsx
Normal 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">
|
||||
✕
|
||||
</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>
|
||||
);
|
||||
}
|
||||
37
frontend/src/components/GpsIndicatorDot.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import toast from 'react-hot-toast';
|
||||
import { api } from '@/lib/api';
|
||||
import { ChevronDown, AlertTriangle, X } from 'lucide-react';
|
||||
import { formatDateTime } from '@/lib/utils';
|
||||
import { useFormattedDate } from '@/hooks/useFormattedDate';
|
||||
|
||||
interface Driver {
|
||||
id: string;
|
||||
@@ -32,6 +32,7 @@ export function InlineDriverSelector({
|
||||
currentDriverName,
|
||||
onDriverChange,
|
||||
}: InlineDriverSelectorProps) {
|
||||
const { formatDateTime } = useFormattedDate();
|
||||
const queryClient = useQueryClient();
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [showConflictDialog, setShowConflictDialog] = useState(false);
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
Plane,
|
||||
Users,
|
||||
Car,
|
||||
Truck,
|
||||
Calendar,
|
||||
UserCog,
|
||||
LayoutDashboard,
|
||||
@@ -22,6 +21,8 @@ import {
|
||||
LogOut,
|
||||
Phone,
|
||||
AlertCircle,
|
||||
FileText,
|
||||
HelpCircle,
|
||||
} from 'lucide-react';
|
||||
import { UserMenu } from '@/components/UserMenu';
|
||||
import { AppearanceMenu } from '@/components/AppearanceMenu';
|
||||
@@ -60,6 +61,22 @@ export function Layout({ children }: LayoutProps) {
|
||||
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)
|
||||
const isDriverRole = backendUser?.role === 'DRIVER';
|
||||
|
||||
@@ -71,8 +88,7 @@ export function Layout({ children }: LayoutProps) {
|
||||
{ name: 'My Profile', href: '/profile', icon: UserCog, driverOnly: true },
|
||||
{ name: 'War Room', href: '/command-center', icon: Radio, requireRead: 'ScheduleEvent' as const, coordinatorOnly: true },
|
||||
{ name: 'VIPs', href: '/vips', icon: Users, requireRead: 'VIP' as const, coordinatorOnly: true },
|
||||
{ name: 'Drivers', href: '/drivers', icon: Car, requireRead: 'Driver' as const, coordinatorOnly: true },
|
||||
{ name: 'Vehicles', href: '/vehicles', icon: Truck, requireRead: 'Vehicle' as const, coordinatorOnly: true },
|
||||
{ name: 'Fleet', href: '/fleet', icon: Car, requireRead: 'Driver' as const, coordinatorOnly: true },
|
||||
{ name: 'Activities', href: '/events', icon: Calendar, requireRead: 'ScheduleEvent' as const, coordinatorOnly: true },
|
||||
{ name: 'Flights', href: '/flights', icon: Plane, requireRead: 'Flight' as const, coordinatorOnly: true },
|
||||
];
|
||||
@@ -80,8 +96,10 @@ export function Layout({ children }: LayoutProps) {
|
||||
// Admin dropdown items (nested under Admin)
|
||||
const adminItems = [
|
||||
{ name: 'Users', href: '/users', icon: UserCog },
|
||||
{ name: 'Reports', href: '/reports', icon: FileText },
|
||||
{ name: 'GPS Tracking', href: '/gps-tracking', icon: Radio },
|
||||
{ name: 'Admin Tools', href: '/admin-tools', icon: Settings },
|
||||
{ name: 'Help Guide', href: '/help', icon: HelpCircle },
|
||||
];
|
||||
|
||||
// Filter navigation based on role and CASL permissions
|
||||
@@ -407,8 +425,8 @@ export function Layout({ children }: LayoutProps) {
|
||||
{children}
|
||||
</main>
|
||||
|
||||
{/* AI Copilot - floating chat (only for Admins and Coordinators) */}
|
||||
{backendUser && (backendUser.role === 'ADMINISTRATOR' || backendUser.role === 'COORDINATOR') && (
|
||||
{/* AI Copilot - floating chat (only if backend has API key and user is Admin/Coordinator) */}
|
||||
{features?.copilot && backendUser && (backendUser.role === 'ADMINISTRATOR' || backendUser.role === 'COORDINATOR') && (
|
||||
<AICopilot />
|
||||
)}
|
||||
</div>
|
||||
|
||||
36
frontend/src/components/SortableHeader.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
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 {
|
||||
vip?: VIP | null;
|
||||
@@ -17,7 +19,13 @@ interface VIP {
|
||||
expectedArrival: string | null;
|
||||
airportPickup: boolean;
|
||||
venueTransport: boolean;
|
||||
partySize: number;
|
||||
notes: string | null;
|
||||
isRosterOnly: boolean;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
emergencyContactName: string | null;
|
||||
emergencyContactPhone: string | null;
|
||||
}
|
||||
|
||||
export interface VIPFormData {
|
||||
@@ -28,22 +36,16 @@ export interface VIPFormData {
|
||||
expectedArrival?: string;
|
||||
airportPickup?: boolean;
|
||||
venueTransport?: boolean;
|
||||
partySize?: number;
|
||||
notes?: string;
|
||||
isRosterOnly?: boolean;
|
||||
phone?: string;
|
||||
email?: string;
|
||||
emergencyContactName?: string;
|
||||
emergencyContactPhone?: string;
|
||||
}
|
||||
|
||||
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>({
|
||||
name: vip?.name || '',
|
||||
organization: vip?.organization || '',
|
||||
@@ -52,9 +54,19 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
|
||||
expectedArrival: toDatetimeLocal(vip?.expectedArrival || null),
|
||||
airportPickup: vip?.airportPickup ?? false,
|
||||
venueTransport: vip?.venueTransport ?? false,
|
||||
partySize: vip?.partySize ?? 1,
|
||||
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) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -66,6 +78,10 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
|
||||
? new Date(formData.expectedArrival).toISOString()
|
||||
: undefined,
|
||||
notes: formData.notes || undefined,
|
||||
phone: formData.phone || undefined,
|
||||
email: formData.email || undefined,
|
||||
emergencyContactName: formData.emergencyContactName || undefined,
|
||||
emergencyContactPhone: formData.emergencyContactPhone || undefined,
|
||||
};
|
||||
|
||||
onSubmit(cleanedData);
|
||||
@@ -80,6 +96,8 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
|
||||
[name]:
|
||||
type === 'checkbox'
|
||||
? (e.target as HTMLInputElement).checked
|
||||
: type === 'number'
|
||||
? parseInt(value) || 1
|
||||
: value,
|
||||
}));
|
||||
};
|
||||
@@ -133,6 +151,26 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
|
||||
/>
|
||||
</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 */}
|
||||
<div>
|
||||
<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"
|
||||
style={{ minHeight: '44px' }}
|
||||
>
|
||||
<option value="OFFICE_OF_DEVELOPMENT">Office of Development</option>
|
||||
<option value="ADMIN">Admin</option>
|
||||
{Object.entries(DEPARTMENT_LABELS).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</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"
|
||||
style={{ minHeight: '44px' }}
|
||||
>
|
||||
<option value="FLIGHT">Flight</option>
|
||||
<option value="SELF_DRIVING">Self Driving</option>
|
||||
{Object.entries(ARRIVAL_MODE_LABELS).map(([value, label]) => (
|
||||
<option key={value} value={value}>
|
||||
{label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -213,6 +257,118 @@ export function VIPForm({ vip, onSubmit, onCancel, isSubmitting }: VIPFormProps)
|
||||
</label>
|
||||
</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 */}
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-foreground mb-2">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createContext, useContext, useEffect, useState, ReactNode } from 'react';
|
||||
import { useAuth0 } from '@auth0/auth0-react';
|
||||
import { api } from '@/lib/api';
|
||||
import { api, setTokenGetter } from '@/lib/api';
|
||||
|
||||
interface BackendUser {
|
||||
id: string;
|
||||
@@ -40,9 +40,16 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [fetchingUser, setFetchingUser] = useState(false);
|
||||
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(() => {
|
||||
// Wait for Auth0 to finish loading before fetching token
|
||||
if (isAuthenticated && !isLoading && !fetchingUser && !backendUser) {
|
||||
setFetchingUser(true);
|
||||
setAuthError(null);
|
||||
@@ -53,42 +60,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
setFetchingUser(false);
|
||||
}, 10000); // 10 second timeout
|
||||
|
||||
getAccessTokenSilently()
|
||||
.then(async (token) => {
|
||||
// Fetch backend user profile (api interceptor handles token automatically)
|
||||
api.get('/auth/profile')
|
||||
.then((response) => {
|
||||
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);
|
||||
setBackendUser(response.data);
|
||||
setAuthError(null);
|
||||
} catch (error: any) {
|
||||
console.error('[AUTH] Failed to fetch user profile:', error);
|
||||
setBackendUser(null);
|
||||
|
||||
// Set specific error message
|
||||
if (error.response?.status === 401) {
|
||||
setAuthError('Your account is pending approval or your session has expired');
|
||||
} else {
|
||||
setAuthError('Failed to load user profile - please try logging in again');
|
||||
}
|
||||
}
|
||||
console.log('[AUTH] User profile fetched successfully:', response.data.email);
|
||||
setBackendUser(response.data);
|
||||
setAuthError(null);
|
||||
})
|
||||
.catch((error) => {
|
||||
.catch((error: any) => {
|
||||
clearTimeout(timeoutId);
|
||||
console.error('[AUTH] Failed to get token:', error);
|
||||
console.error('[AUTH] Failed to fetch user profile:', error);
|
||||
setBackendUser(null);
|
||||
|
||||
// Handle specific Auth0 errors
|
||||
if (error.error === 'missing_refresh_token' || error.message?.includes('Missing Refresh Token')) {
|
||||
// Handle specific errors
|
||||
if (error.response?.status === 401) {
|
||||
setAuthError('Your account is pending approval or your session has expired');
|
||||
} else if (error.error === 'missing_refresh_token' || error.message?.includes('Missing Refresh Token')) {
|
||||
setAuthError('Session expired - please log in again');
|
||||
} else if (error.error === 'login_required') {
|
||||
setAuthError('Login required');
|
||||
} else {
|
||||
setAuthError('Authentication failed - please try logging in again');
|
||||
setAuthError('Failed to load user profile - please try logging in again');
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
@@ -99,7 +92,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
}, [isAuthenticated, isLoading]);
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem('auth0_token');
|
||||
setTokenGetter(null);
|
||||
auth0Logout({ logoutParams: { returnTo: window.location.origin } });
|
||||
};
|
||||
|
||||
|
||||