-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
2143 lines (1805 loc) · 63.6 KB
/
Copy pathserver.js
File metadata and controls
2143 lines (1805 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Load local .env values in development without affecting production (no-op if file missing)
if (process.env.NODE_ENV !== 'production') {
try {
require('dotenv').config();
} catch (err) {
// dotenv is optional; ignore if not installed in production build
console.warn('dotenv not loaded (optional):', err.message);
}
}
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const https = require('https');
const { connectToDatabase, getCollection } = require('./db');
const multer = require('multer');
const OpenAI = require('openai');
const app = express();
// Determine which front-end origins are allowed to talk to the API / socket server.
// Supports wildcards such as https://*.vercel.app and literal "*" to allow all.
const defaultOrigins = [
'http://localhost:5173',
'https://agentflowcorp.vercel.app'
];
const rawOrigins = process.env.ALLOWED_ORIGINS || defaultOrigins.join(',');
const originEntries = rawOrigins.split(',').map(origin => origin.trim()).filter(Boolean);
const allowAllOrigins = originEntries.includes('*');
const exactOrigins = originEntries.filter(origin => origin && !origin.includes('*') && origin !== '*');
const wildcardOrigins = originEntries
.filter(origin => origin.includes('*'))
.map(origin => {
const escaped = origin.replace(/[.+?^${}()|[\]\\]/g, '\\$&');
const regexSource = `^${escaped.replace(/\\\*/g, '.*')}$`;
return {
pattern: origin,
regex: new RegExp(regexSource)
};
});
function isOriginAllowed(origin) {
if (allowAllOrigins || !origin) {
return true;
}
if (exactOrigins.includes(origin)) {
return true;
}
return wildcardOrigins.some(({ regex }) => regex.test(origin));
}
const corsOriginSetting = allowAllOrigins
? true
: (origin, callback) => {
if (isOriginAllowed(origin)) {
return callback(null, true);
}
console.warn('CORS blocked origin:', origin);
return callback(new Error('Not allowed by CORS'));
};
const corsOptions = {
origin: corsOriginSetting,
methods: ['GET', 'POST', 'PATCH', 'DELETE']
};
const corsSummary = allowAllOrigins
? '*'
: [
...exactOrigins,
...wildcardOrigins.map(({ pattern }) => `${pattern} (wildcard)`)
].join(', ');
const server = http.createServer(app);
const io = new Server(server, { cors: corsOptions });
// Middleware
app.use(cors(corsOptions));
app.use(express.json());
// ============================================
// AUTHENTICATION CONFIG
// ============================================
const JWT_SECRET = process.env.JWT_SECRET || 'agentflow-mvp-secret-change-in-production';
const GOOGLE_MAPS_API_KEY = process.env.GOOGLE_MAPS_API_KEY || process.env.VITE_GOOGLE_MAPS_API_KEY || '';
const OPENAI_API_KEY = process.env.OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY || '';
// Initialize OpenAI client
const openai = OPENAI_API_KEY ? new OpenAI({ apiKey: OPENAI_API_KEY }) : null;
// Configure multer for file uploads (memory storage for images)
const upload = multer({
storage: multer.memoryStorage(),
limits: {
fileSize: 10 * 1024 * 1024, // 10MB max file size
},
fileFilter: (req, file, cb) => {
// Accept images only
if (file.mimetype.startsWith('image/')) {
cb(null, true);
} else {
cb(new Error('Only image files are allowed'));
}
}
});
// ============================================
// IN-MEMORY DATA STORE (Replace with DB later)
// ============================================
const users = new Map(); // NEW: User accounts (email/password)
const agents = new Map();
const clients = new Map(); // NEW: Persistent client profiles
const showingSessions = new Map(); // NEW: One session per client per day
const dailyRoutes = new Map();
const locationShares = new Map();
const agentLocations = new Map();
async function hydrateFromDatabase() {
const usersCol = getCollection('users');
const agentsCol = getCollection('agents');
const clientsCol = getCollection('clients');
const sessionsCol = getCollection('sessions');
if (!usersCol || !agentsCol || !clientsCol || !sessionsCol) {
return;
}
const [userDocs, agentDocs, clientDocs, sessionDocs] = await Promise.all([
usersCol.find({}).toArray(),
agentsCol.find({}).toArray(),
clientsCol.find({}).toArray(),
sessionsCol.find({}).toArray()
]);
userDocs.forEach(doc => users.set(doc.id, doc));
agentDocs.forEach(doc => agents.set(doc.id, doc));
clientDocs.forEach(doc => clients.set(doc.id, doc));
sessionDocs.forEach(doc => showingSessions.set(doc.id, doc));
console.log('✅ Hydrated data from MongoDB', {
users: userDocs.length,
agents: agentDocs.length,
clients: clientDocs.length,
sessions: sessionDocs.length
});
}
async function saveUser(user) {
const col = getCollection('users');
if (!col) {
console.warn('⚠️ Database not connected - user save skipped:', user.id);
return;
}
try {
const result = await col.updateOne({ id: user.id }, { $set: user }, { upsert: true });
console.log(`✅ Saved user ${user.email} to database`);
return result;
} catch (error) {
console.error('❌ Failed to save user to database:', error.message);
throw new Error(`Database save failed for user ${user.id}: ${error.message}`);
}
}
async function saveAgent(agent) {
const col = getCollection('agents');
if (!col) {
console.warn('⚠️ Database not connected - agent save skipped:', agent.id);
return;
}
try {
const result = await col.updateOne({ id: agent.id }, { $set: agent }, { upsert: true });
console.log(`✅ Saved agent ${agent.email} to database`);
return result;
} catch (error) {
console.error('❌ Failed to save agent to database:', error.message);
throw new Error(`Database save failed for agent ${agent.id}: ${error.message}`);
}
}
async function saveClient(client) {
const col = getCollection('clients');
if (!col) {
console.warn('⚠️ Database not connected - client save skipped:', client.id);
return;
}
try {
const result = await col.updateOne({ id: client.id }, { $set: client }, { upsert: true });
console.log(`✅ Saved client ${client.name} to database`);
return result;
} catch (error) {
console.error('❌ Failed to save client to database:', error.message);
throw new Error(`Database save failed for client ${client.id}: ${error.message}`);
}
}
async function removeClient(clientId) {
const col = getCollection('clients');
if (!col) {
console.warn('⚠️ Database not connected - client removal skipped:', clientId);
return;
}
try {
const result = await col.deleteOne({ id: clientId });
console.log(`✅ Removed client ${clientId} from database`);
return result;
} catch (error) {
console.error('❌ Failed to remove client from database:', error.message);
throw new Error(`Database delete failed for client ${clientId}: ${error.message}`);
}
}
async function saveSession(session) {
const col = getCollection('sessions');
if (!col) {
console.warn('⚠️ Database not connected - session save skipped:', session.id);
return;
}
try {
const result = await col.updateOne({ id: session.id }, { $set: session }, { upsert: true });
console.log(`✅ Saved session ${session.id} to database`);
return result;
} catch (error) {
console.error('❌ Failed to save session to database:', error.message);
throw new Error(`Database save failed for session ${session.id}: ${error.message}`);
}
}
async function removeSession(sessionId) {
const col = getCollection('sessions');
if (!col) {
console.warn('⚠️ Database not connected - session removal skipped:', sessionId);
return;
}
try {
const result = await col.deleteOne({ id: sessionId });
console.log(`✅ Removed session ${sessionId} from database`);
return result;
} catch (error) {
console.error('❌ Failed to remove session from database:', error.message);
throw new Error(`Database delete failed for session ${sessionId}: ${error.message}`);
}
}
// Seed a demo agent for testing
const demoAgentId = uuidv4();
agents.set(demoAgentId, {
id: demoAgentId,
email: 'demo@agentflow.app',
name: 'Agent John',
phone: '+1-416-555-1234',
home_address: '100 Queen St, Toronto',
home_lat: 43.6532,
home_lng: -79.3832,
created_at: new Date().toISOString()
});
console.log('Demo Agent ID:', demoAgentId);
// Seed some demo clients
const demoClients = [
{
id: uuidv4(),
agent_id: demoAgentId,
name: 'Sarah Chen',
phone: '+1-416-555-0101',
email: 'sarah@example.com',
home_address: '456 Bloor St West, Toronto',
home_lat: 43.6677,
home_lng: -79.4055,
created_at: new Date().toISOString()
},
{
id: uuidv4(),
agent_id: demoAgentId,
name: 'James Rodriguez',
phone: '+1-416-555-0202',
email: 'james@example.com',
home_address: '789 College St, Toronto',
home_lat: 43.6571,
home_lng: -79.4113,
created_at: new Date().toISOString()
},
{
id: uuidv4(),
agent_id: demoAgentId,
name: 'Emily Wong',
phone: '+1-416-555-0303',
email: 'emily@example.com',
home_address: '321 Spadina Ave, Toronto',
home_lat: 43.6550,
home_lng: -79.3998,
created_at: new Date().toISOString()
}
];
demoClients.forEach(client => clients.set(client.id, client));
console.log(`Seeded ${demoClients.length} demo clients`);
const seededDemoAgents = new Set();
const seedingInProgress = new Set(); // Track in-progress seeding to prevent race conditions
async function seedDemoDataForAgent(agentId) {
if (!agentId || agentId === demoAgentId || seededDemoAgents.has(agentId)) {
return;
}
// Check if seeding is already in progress for this agent (race condition prevention)
if (seedingInProgress.has(agentId)) {
console.log(`⏳ Demo seeding already in progress for agent ${agentId}, skipping duplicate request`);
return;
}
const agent = agents.get(agentId);
if (!agent || agent.is_demo !== true) {
return;
}
const alreadyHasClients = Array.from(clients.values()).some(c => c.agent_id === agentId);
if (alreadyHasClients) {
seededDemoAgents.add(agentId);
return;
}
// Mark seeding as in progress
seedingInProgress.add(agentId);
try {
// Double-check after acquiring lock (in case another request just finished)
if (seededDemoAgents.has(agentId)) {
return;
}
demoClients.forEach(template => {
const clone = {
...template,
id: uuidv4(),
agent_id: agentId,
created_at: new Date().toISOString()
};
clients.set(clone.id, clone);
});
seededDemoAgents.add(agentId);
console.log(`✅ Seeded ${demoClients.length} demo clients for agent ${agentId}`);
// Optionally save to database (non-blocking)
const clonedClients = Array.from(clients.values()).filter(c => c.agent_id === agentId);
Promise.all(clonedClients.map(c => saveClient(c))).catch(err => {
console.warn('⚠️ Failed to persist demo clients to database:', err.message);
});
} finally {
// Always remove from in-progress set
seedingInProgress.delete(agentId);
}
}
// ============================================
// AUTHENTICATION MIDDLEWARE
// ============================================
// Verify JWT token and attach user to request
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1]; // Bearer TOKEN
if (!token) {
return res.status(401).json({ error: 'Access token required' });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res.status(403).json({ error: 'Invalid or expired token' });
}
req.user = user; // { userId, email }
next();
});
}
// ============================================
// HELPER FUNCTIONS
// ============================================
// Timeout wrapper for promises
function withTimeout(promise, timeoutMs, errorMessage = 'Operation timed out') {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(errorMessage)), timeoutMs)
)
]);
}
// Input validation helpers
function isValidEmail(email) {
if (!email || typeof email !== 'string') {
return false;
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email.trim());
}
function isValidPhone(phone) {
if (!phone || typeof phone !== 'string') {
return false;
}
// Basic phone validation - at least 10 digits
const digitsOnly = phone.replace(/\D/g, '');
return digitsOnly.length >= 10 && digitsOnly.length <= 15;
}
function sanitizeString(str, maxLength = 255) {
if (!str || typeof str !== 'string') {
return '';
}
return str.trim().slice(0, maxLength);
}
// Mock geocoding (replace with Google Maps API later)
function mockGeocode(address) {
// Simple mock - returns random Toronto coordinates
// WARNING: This is a fallback and should only be used in development/demo mode
const baseLatToronto = 43.65;
const baseLngToronto = -79.38;
console.warn(`⚠️ GEOCODING FALLBACK: Using mock coordinates for address "${address}". Configure GOOGLE_MAPS_API_KEY for accurate geocoding.`);
return {
lat: baseLatToronto + (Math.random() * 0.1 - 0.05),
lng: baseLngToronto + (Math.random() * 0.1 - 0.05),
isMock: true
};
}
// Validate coordinates are within reasonable bounds
function validateCoordinates(lat, lng) {
if (typeof lat !== 'number' || typeof lng !== 'number') {
return false;
}
// Basic validation: coordinates must be valid numbers
if (!Number.isFinite(lat) || !Number.isFinite(lng)) {
return false;
}
// Validate lat/lng ranges
if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {
console.error(`❌ Invalid coordinates: lat=${lat}, lng=${lng} (out of range)`);
return false;
}
// Optional: Validate for Toronto/North America area (can be removed for global use)
// Toronto area: roughly lat 40-50, lng -85 to -70
if (lat < 35 || lat > 55 || lng < -100 || lng > -60) {
console.warn(`⚠️ Coordinates outside expected region (North America): lat=${lat}, lng=${lng}`);
// Don't return false - just warn, as this might be intentional
}
return true;
}
function fetchJson(url) {
return new Promise((resolve, reject) => {
https
.get(url, res => {
let data = '';
res.on('data', chunk => { data += chunk; });
res.on('end', () => {
try {
resolve(JSON.parse(data));
} catch (err) {
reject(err);
}
});
})
.on('error', reject);
});
}
async function geocodeAddress(address) {
if (!GOOGLE_MAPS_API_KEY || !address) {
return null;
}
try {
const url = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodeURIComponent(address)}&key=${GOOGLE_MAPS_API_KEY}`;
const response = await fetchJson(url);
// Validate response structure
if (!response || typeof response !== 'object') {
console.error('❌ Invalid response from Google Geocoding API');
return null;
}
if (response.status === 'OK' && response.results && response.results.length > 0) {
const location = response.results[0]?.geometry?.location;
if (location && validateCoordinates(location.lat, location.lng)) {
return { lat: location.lat, lng: location.lng };
}
console.error('❌ Invalid coordinates returned from geocoding API');
return null;
}
if (response.status === 'ZERO_RESULTS') {
console.warn(`⚠️ Geocoding returned zero results for: "${address}"`);
} else if (response.status !== 'OK') {
console.warn(`⚠️ Geocoding failed with status: ${response.status}`, response.error_message);
}
} catch (error) {
console.error('❌ Error calling Google Geocoding API:', error.message);
}
return null;
}
async function resolveCoordinates(lat, lng, address) {
const parsedLat = typeof lat === 'number' ? lat : parseFloat(lat);
const parsedLng = typeof lng === 'number' ? lng : parseFloat(lng);
// Use provided coordinates if valid
if (Number.isFinite(parsedLat) && Number.isFinite(parsedLng) && validateCoordinates(parsedLat, parsedLng)) {
console.log(`✅ Using provided coordinates: (${parsedLat}, ${parsedLng})`);
return { lat: parsedLat, lng: parsedLng };
}
// Try geocoding the address
const geocoded = await geocodeAddress(address);
if (geocoded) {
console.log(`✅ Geocoded address "${address}" to coordinates: (${geocoded.lat}, ${geocoded.lng})`);
return geocoded;
}
// Fallback to mock coordinates (with warning)
const mock = mockGeocode(address);
return { lat: mock.lat, lng: mock.lng };
}
async function optimizePropertiesWithGoogle(session, client, agent, includePickup) {
if (!GOOGLE_MAPS_API_KEY || !session.properties || session.properties.length <= 1) {
return { properties: session.properties, legs: null };
}
try {
const origin = agent?.home_address;
let destination = includePickup
? (client?.home_address || agent?.home_address)
: (session.properties[session.properties.length - 1]?.address || agent?.home_address);
const waypointAddresses = session.properties.map(prop => prop.address).filter(Boolean);
if (!origin || !destination || waypointAddresses.length === 0) {
console.warn('⚠️ Missing required addresses for route optimization');
return { properties: session.properties, legs: null };
}
const params = new URLSearchParams({
origin,
destination,
mode: 'driving',
departure_time: 'now',
traffic_model: 'best_guess',
key: GOOGLE_MAPS_API_KEY
});
params.append('waypoints', `optimize:true|${waypointAddresses.join('|')}`);
const url = `https://maps.googleapis.com/maps/api/directions/json?${params.toString()}`;
const response = await fetchJson(url);
// Validate response structure
if (!response || typeof response !== 'object') {
console.error('❌ Invalid response from Google Directions API');
return { properties: session.properties, legs: null };
}
if (response.status === 'OK') {
if (!response.routes || response.routes.length === 0) {
console.warn('⚠️ Directions API returned OK but no routes');
return { properties: session.properties, legs: null };
}
const route = response.routes[0];
if (!route) {
console.error('❌ First route is undefined');
return { properties: session.properties, legs: null };
}
const order = route.waypoint_order || [];
// Validate waypoint order
if (order.length !== session.properties.length) {
console.warn(`⚠️ Waypoint order length mismatch: expected ${session.properties.length}, got ${order.length}`);
return { properties: session.properties, legs: null };
}
const optimized = order.map(index => {
if (index < 0 || index >= session.properties.length) {
console.error(`❌ Invalid waypoint index: ${index}`);
return null;
}
return session.properties[index];
}).filter(Boolean);
if (optimized.length !== session.properties.length) {
console.warn('⚠️ Some properties were lost during optimization, using original order');
return { properties: session.properties, legs: null };
}
return { properties: optimized, legs: route.legs || null };
}
// Handle specific error statuses
if (response.status === 'ZERO_RESULTS') {
console.warn('⚠️ Directions API found no route between the locations');
} else if (response.status === 'OVER_QUERY_LIMIT') {
console.error('❌ Google API quota exceeded');
} else if (response.status === 'REQUEST_DENIED') {
console.error('❌ Google API request denied:', response.error_message);
} else {
console.warn(`⚠️ Directions API returned status: ${response.status}`, response.error_message);
}
} catch (error) {
console.error('❌ Directions API error:', error.message);
}
return { properties: session.properties, legs: null };
}
function ensureAgent(agentId) {
const fallbackAgent = agents.get(demoAgentId);
if (!agentId) {
return fallbackAgent;
}
if (agents.has(agentId)) {
const existing = agents.get(agentId);
if (existing?.is_demo) {
seedDemoDataForAgent(agentId);
}
return existing;
}
const placeholder = {
id: agentId,
email: `demo-${agentId}@agentflow.app`,
name: 'Demo Agent',
phone: '',
home_address: fallbackAgent?.home_address || '100 Queen St, Toronto',
home_lat: fallbackAgent?.home_lat || 43.6532,
home_lng: fallbackAgent?.home_lng || -79.3832,
created_at: new Date().toISOString(),
is_demo: true
};
agents.set(agentId, placeholder);
seedDemoDataForAgent(agentId);
return placeholder;
}
// Calculate straight-line distance (km) between two points
function calculateDistance(lat1, lng1, lat2, lng2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLng = (lng2 - lng1) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
// Calculate estimated drive time (minutes) based on distance
function estimateDriveTime(distanceKm) {
// Average Toronto traffic: ~30 km/h in city
return Math.ceil((distanceKm / 30) * 60);
}
// Calculate time window for a client session
async function calculateSessionTimeWindow(session, client, agent) {
const SHOWING_DURATION_MIN = 30; // Fixed: 30 min per property
const pickupLat = client.home_lat;
const pickupLng = client.home_lng;
const includePickup = !!session.pickup_client;
// Optimize property sequence using Google Directions when available
const googleOptimization = await optimizePropertiesWithGoogle(session, client, agent, includePickup);
const optimizedProperties = googleOptimization.properties || session.properties;
const googleLegs = googleOptimization.legs;
let legIndex = 0;
function getDriveStats(fallbackMinutes, fallbackDistanceKm) {
if (googleLegs && googleLegs[legIndex]) {
const leg = googleLegs[legIndex++];
const minutes = Math.ceil((leg.duration_in_traffic?.value || leg.duration?.value || (fallbackMinutes * 60)) / 60);
const distanceKm = leg.distance?.value ? parseFloat((leg.distance.value / 1000).toFixed(2)) : fallbackDistanceKm;
return { minutes, distanceKm };
}
return { minutes: fallbackMinutes, distanceKm: fallbackDistanceKm };
}
// Calculate timeline
const timeline = [];
let currentTime = new Date(session.start_time);
let currentLat = agent.home_lat;
let currentLng = agent.home_lng;
timeline.push({
type: 'departure',
location: 'Agent Home',
address: agent.home_address,
time: currentTime.toISOString(),
lat: currentLat,
lng: currentLng
});
if (includePickup && pickupLat && pickupLng) {
const distToPickup = calculateDistance(currentLat, currentLng, pickupLat, pickupLng);
const driveToPickup = estimateDriveTime(distToPickup);
currentTime = new Date(currentTime.getTime() + driveToPickup * 60000);
currentLat = pickupLat;
currentLng = pickupLng;
timeline.push({
type: 'pickup',
location: 'Client Pickup',
address: client.home_address,
client_name: client.name,
time: currentTime.toISOString(),
lat: currentLat,
lng: currentLng
});
}
// 2. Visit each property
optimizedProperties.forEach((prop, index) => {
const distToProp = calculateDistance(currentLat, currentLng, prop.lat, prop.lng);
const fallbackDrive = estimateDriveTime(distToProp);
const { minutes: driveToProp, distanceKm } = getDriveStats(fallbackDrive, parseFloat(distToProp.toFixed(2)));
// Drive to property
currentTime = new Date(currentTime.getTime() + driveToProp * 60000);
timeline.push({
type: 'property',
location: `Property ${index + 1}`,
address: prop.address,
arrival_time: currentTime.toISOString(),
duration_min: SHOWING_DURATION_MIN,
lat: prop.lat,
lng: prop.lng,
drive_time_min: driveToProp,
distance_km: distanceKm
});
// Showing duration
currentTime = new Date(currentTime.getTime() + SHOWING_DURATION_MIN * 60000);
currentLat = prop.lat;
currentLng = prop.lng;
});
// 3. Wrap up / dropoff logic
// IMPORTANT: Client pickup/dropoff uses client.home_address as the DEFAULT ADDRESS
// This is the client's home location used for both pickup and dropoff calculations
if (includePickup) {
const lastPropLat = currentLat;
const lastPropLng = currentLng;
const distHomeFromLast = calculateDistance(lastPropLat, lastPropLng, client.home_lat, client.home_lng);
const fallbackDriveHome = estimateDriveTime(distHomeFromLast);
const { minutes: driveHomeFromLast } = getDriveStats(fallbackDriveHome, parseFloat(distHomeFromLast.toFixed(2)));
let dropoffLat, dropoffLng, dropoffAddress, dropoffType;
// Dropoff decision logic:
// - If return drive to client home < 30 min: drop client at their home (client.home_address)
// - Otherwise: drop client at last property (saves time/cost)
if (driveHomeFromLast < 30) {
dropoffLat = client.home_lat;
dropoffLng = client.home_lng;
dropoffAddress = client.home_address; // DEFAULT ADDRESS for dropoff
dropoffType = 'dropoff_home';
currentTime = new Date(currentTime.getTime() + driveHomeFromLast * 60000);
} else {
dropoffLat = lastPropLat;
dropoffLng = lastPropLng;
dropoffAddress = optimizedProperties[optimizedProperties.length - 1]?.address;
dropoffType = 'dropoff_property';
}
timeline.push({
type: dropoffType,
location: 'Client Dropoff',
address: dropoffAddress,
client_name: client.name,
time: currentTime.toISOString(),
lat: dropoffLat,
lng: dropoffLng
});
} else if (optimizedProperties.length > 0) {
timeline.push({
type: 'wrap_up',
location: 'Last Stop',
address: optimizedProperties[optimizedProperties.length - 1].address,
time: currentTime.toISOString(),
lat: currentLat,
lng: currentLng
});
}
const sessionEndTime = currentTime.toISOString();
const totalDurationMin = Math.ceil((new Date(sessionEndTime) - new Date(session.start_time)) / 60000);
return {
session_id: session.id,
client_id: session.client_id,
client_name: client.name,
start_time: session.start_time,
end_time: sessionEndTime,
total_duration_min: totalDurationMin,
optimized_properties: optimizedProperties,
timeline
};
}
// Detect conflicts between sessions
function detectConflicts(sessionsForDay) {
const conflicts = [];
for (let i = 0; i < sessionsForDay.length - 1; i++) {
for (let j = i + 1; j < sessionsForDay.length; j++) {
const session1Start = new Date(sessionsForDay[i].start_time);
const session1End = new Date(sessionsForDay[i].end_time);
const session2Start = new Date(sessionsForDay[j].start_time);
const session2End = new Date(sessionsForDay[j].end_time);
// Check for overlap
if (session1Start < session2End && session2Start < session1End) {
const overlapMin = Math.min(
(session1End - session2Start) / 60000,
(session2End - session1Start) / 60000
);
conflicts.push({
type: 'overlap',
session1_id: sessionsForDay[i].session_id,
session1_client: sessionsForDay[i].client_name,
session2_id: sessionsForDay[j].session_id,
session2_client: sessionsForDay[j].client_name,
overlap_minutes: Math.ceil(overlapMin),
message: `Conflict: ${sessionsForDay[i].client_name} (ends ${session1End.toLocaleTimeString()}) overlaps with ${sessionsForDay[j].client_name} (starts ${session2Start.toLocaleTimeString()})`
});
}
}
}
return conflicts;
}
// ============================================
// API ENDPOINTS
// ============================================
// Health check
app.get('/api/health', (req, res) => {
res.json({
status: 'ok',
app: 'AgentFlow MVP',
timestamp: new Date().toISOString(),
demoAgentId
});
});
// ============================================
// AUTHENTICATION ENDPOINTS
// ============================================
// Register new user
app.post('/api/auth/register', async (req, res) => {
try {
const { email, password, name, phone } = req.body;
// Validation
if (!email || !password || !name) {
return res.status(400).json({ error: 'Email, password, and name are required' });
}
// Validate email format
if (!isValidEmail(email)) {
return res.status(400).json({ error: 'Invalid email format' });
}
// Validate password strength
if (password.length < 8) {
return res.status(400).json({ error: 'Password must be at least 8 characters long' });
}
// Validate name length
if (sanitizeString(name).length < 2) {
return res.status(400).json({ error: 'Name must be at least 2 characters long' });
}
// Validate phone if provided
if (phone && !isValidPhone(phone)) {
return res.status(400).json({ error: 'Invalid phone number format' });
}
// Check if email already exists
const existingUser = Array.from(users.values()).find(u => u.email === email);
if (existingUser) {
return res.status(409).json({ error: 'Email already registered' });
}
// Hash password
const passwordHash = await bcrypt.hash(password, 10);
// Create user (sanitize inputs)
const userId = uuidv4();
const user = {
id: userId,
email: email.trim().toLowerCase(),
passwordHash,
name: sanitizeString(name),
phone: phone ? sanitizeString(phone, 20) : '',
created_at: new Date().toISOString()
};
users.set(userId, user);
await saveUser(user);
// Create agent profile for this user
const agentId = uuidv4();
const agent = {
id: agentId,
user_id: userId,
email: email.trim().toLowerCase(),
name: sanitizeString(name),
phone: phone ? sanitizeString(phone, 20) : '',
home_address: '',
home_lat: null,
home_lng: null,
created_at: new Date().toISOString(),
is_demo: false
};
agents.set(agentId, agent);
await saveAgent(agent);
// Generate JWT token
const token = jwt.sign(
{ userId, email, agentId },
JWT_SECRET,
{ expiresIn: '30d' }
);
res.status(201).json({
message: 'User registered successfully',
token,
user: {
id: userId,
email,
name,
phone: phone || '',
agentId
}
});
} catch (error) {
console.error('Register error:', error);
res.status(500).json({ error: 'Failed to register user' });
}
});
// Login user
app.post('/api/auth/login', async (req, res) => {
try {
const { email, password } = req.body;
// Validation
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
// Find user by email
const user = Array.from(users.values()).find(u => u.email === email);
if (!user) {
return res.status(401).json({ error: 'Invalid email or password' });
}
// Verify password
const passwordMatch = await bcrypt.compare(password, user.passwordHash);
if (!passwordMatch) {
return res.status(401).json({ error: 'Invalid email or password' });
}
// Find agent profile