-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1554 lines (1326 loc) · 75.6 KB
/
Copy pathapp.js
File metadata and controls
1554 lines (1326 loc) · 75.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
// ==============================================================================
// UYO LOGISTICS INTELLIGENCE | MASTER COMMAND CENTER
// 100% Survey-Grade Configuration (Deep Zoom, Individual Deletion, OSRM, BI, Search)
// ==============================================================================
//
// 📋 CHANGELOG
// v2.3.8: 60FPS Interpolation Engine: Replaced conflicting CSS transitions with requestAnimationFrame JS tweening (.slideTo).
// v2.3.9: Telemetry Diagnostic Patch: Injected WebSocket interceptor to debug ghost markers.
// v2.4.0: SURCON Enterprise Telemetry Sync: Patched defensive payload mapper to strictly reference nested telemetry objects.
// v2.4.1: Cartographic Expansion & Matrix Parity: Expanded Google Places API bounds and strictly enforced mathematical geofencing.
// v2.4.2: Survey-Grade Sync: Removed redundant UI pump price multiplication & switched to explicit backend time_saved_mins.
// v2.4.3: Telemetry Lock Patch: Introduced window.sessionMetricsCommitted state lock to prevent database metric duplication.
// v2.4.4: Telemetry Schema Enforcement: Normalized WebSocket ingestion to strictly target 'lng' and 'lat' keys, resolving silent NaN failures.
// v2.4.5: Architecture Synchronization: Pointed API and WS globals directly to Render to resolve split-brain memory allocation.
// v2.5.0: Enriched Payload Integration: Added dispatcher metadata inputs, transformed array mapping to RouteWaypoint dictionaries.
// v2.5.1: Dual-Payload Patch: Added fallback route_coords generation to window.deployMission to bypass strict backend validation.
// v2.5.2: Telemetry Schema Patch: Updated WebSocket ingestion to accept both 'lng' and 'lon' coordinate keys to resolve silent NaN failures on mobile driver deployment.
// v2.5.3: Security & Auth Patch: Explicitly injected missing x-license-key headers across all fetch endpoints and redacted exposed Google API key.
// v2.5.4: Places API Hotfix: Modified restricted key placeholder strategy to resolve HTTP 400 errors during UI geocoding searches.
// v2.5.5: Basemap Authentication Patch: Injected CARTO API key to raster tile endpoints to resolve commercial watermarks and prevent rate-limiting.
// ==============================================================================
// --- 0. PERSISTENT GLOBAL STATE (PATCHED & EXTENDED) ---
// 🔴 SYNCHRONIZATION FIX: Pointed directly to Render to ensure simulator and frontend share the exact same worker memory.
window.API_BASE_URL = "https://uyo-routing-engine.onrender.com";
window.WS_BASE_URL = "wss://uyo-routing-engine.onrender.com";
window.fleetRegistry = {};
window.activeDeployments = {};
window.activeDeploymentsMins = {};
window.activeRoutePlans = {}; // NEW: Stores the enriched RouteWaypoint payload
window.currentPhysicsEngine = {};
window.lifetimeStats = { fuel: 0, co2: 0, efficiency: 0 };
window.sessionMetricsCommitted = false;
window.depotLocation = { lat: 5.0333, lon: 7.9266 };
window.dynamicDeliveries = [];
window.liveMarkers = {};
window.map = null;
window.routeLayerGroup = null;
window.unassignedPinsLayer = null;
window.liveFleetSocket = null;
// --- 0.1 TELEMETRY INTERPOLATION ENGINE (SURCON STANDARD) ---
L.Marker.include({
slideTo: function(destination, durationMs) {
if (!this._map) return;
const start = this.getLatLng();
const end = L.latLng(destination);
const startTime = performance.now();
if (this._slideFrame) {
cancelAnimationFrame(this._slideFrame);
}
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / durationMs, 1);
const currentLat = start.lat + (end.lat - start.lat) * progress;
const currentLng = start.lng + (end.lng - start.lng) * progress;
this.setLatLng([currentLat, currentLng]);
if (progress < 1) {
this._slideFrame = requestAnimationFrame(animate);
}
};
this._slideFrame = requestAnimationFrame(animate);
}
});
// ==============================================================================
// --- EXTRACTED GLOBAL HANDLERS (SURVEY-GRADE DECOUPLING) ---
// ==============================================================================
window.createLiveIcon = function(vId, isBike) {
const icon = isBike ? 'fa-motorcycle' : 'fa-truck';
return L.divIcon({
className: 'live-telemetry-marker',
iconSize: [24, 24],
iconAnchor: [12, 12],
html: `
<div class="relative flex items-center justify-center h-6 w-6">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-red-500 opacity-75"></span>
<div class="relative flex items-center justify-center h-5 w-5 rounded-full bg-red-600 border-[1.5px] border-white shadow-lg">
<i class="fa-solid ${icon}" style="color: white; font-size: 8px;"></i>
</div>
</div>
`
});
};
window.fetchLifetimeMetrics = async function() {
try {
const response = await fetch(`${window.API_BASE_URL}/api/vrp/history?_t=${Date.now()}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-license-key': localStorage.getItem('uyo_license_key'),
'Cache-Control': 'no-cache'
}
});
if (response.status === 401) {
localStorage.removeItem('uyo_license_key');
window.location.href = "login.html";
return;
}
if (response.ok) {
const data = await response.json();
window.lifetimeStats.fuel = parseFloat(data.total_fuel_saved ?? data.lifetime_fuel ?? data.fuel_saved ?? 0) || 0;
window.lifetimeStats.co2 = parseFloat(data.total_co2_saved ?? data.lifetime_co2 ?? data.co2_saved_kg ?? 0) || 0;
window.lifetimeStats.efficiency = parseFloat(data.avg_efficiency ?? data.efficiency ?? 0) || 0;
window.updateBIMetrics(false);
}
} catch (err) { console.warn("Could not fetch lifetime stats from memory bank."); }
};
window.updateBIMetrics = function(isSession = false) {
const statFuelEl = document.getElementById('stat-fuel');
const statEffEl = document.getElementById('stat-efficiency');
const statCo2El = document.getElementById('stat-co2');
const pe = window.currentPhysicsEngine || {};
if (isSession) {
if (statFuelEl) {
statFuelEl.previousElementSibling.innerText = "Session Fuel Saved";
const sessionFuelValue = parseFloat(pe.fuel_saved) || 0;
statFuelEl.innerText = `₦${sessionFuelValue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
statFuelEl.style.color = "#fbbf24";
}
if (statEffEl) {
statEffEl.previousElementSibling.innerText = "Session Efficiency";
statEffEl.innerText = `${(parseFloat(pe.efficiency) || 0).toFixed(1)}%`;
statEffEl.style.color = "#fbbf24";
}
if (statCo2El) {
statCo2El.previousElementSibling.innerText = "Session CO2 Saved";
statCo2El.innerText = `${(parseFloat(pe.co2_saved) || 0).toFixed(2)} kg`;
statCo2El.style.color = "#fbbf24";
}
} else {
if (statFuelEl) {
statFuelEl.previousElementSibling.innerText = "Lifetime Fuel";
const lifeFuelValue = parseFloat(window.lifetimeStats.fuel) || 0;
statFuelEl.innerText = `₦${lifeFuelValue.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
statFuelEl.style.color = "#4ade80";
}
if (statEffEl) {
statEffEl.previousElementSibling.innerText = "Avg Efficiency";
statEffEl.innerText = `${(parseFloat(window.lifetimeStats.efficiency) || 0).toFixed(1)}%`;
statEffEl.style.color = "#60a5fa";
}
if (statCo2El) {
statCo2El.previousElementSibling.innerText = "Lifetime CO2";
statCo2El.innerText = `${(parseFloat(window.lifetimeStats.co2) || 0).toFixed(1)} kg`;
statCo2El.style.color = "#f87171";
}
}
if (document.getElementById('co2-bar')) {
const displayEff = isSession ? (pe.efficiency || 0) : (window.lifetimeStats.efficiency || 0);
document.getElementById('co2-bar').style.width = `${Math.min(displayEff * 2, 100)}%`;
}
};
window.deployMission = async function(vehicleId, gmapsUrl) {
const trackingUrl = `https://uyologistics.com/driver.html?v=${vehicleId}&map=${encodeURIComponent(gmapsUrl)}`;
const whatsappMessage = encodeURIComponent(
`🚀 *UYO LOGISTICS MISSION DEPLOYED*\n\n` +
`📦 *Vehicle ID:* ${vehicleId}\n` +
`📍 *Mission:* Optimized multi-stop delivery route generated by Command Center.\n\n` +
`📱 *Open Live Tracking & Navigation:* \n${trackingUrl}`
);
const whatsappLink = `https://wa.me/?text=${whatsappMessage}`;
const userChoice = confirm(
`📡 DEPLOY MISSION: ${vehicleId}\n\n` +
`This will initiate live tracking and record the mission.\n\n` +
`Click OK to deploy.`
);
if (!userChoice) {
return;
}
const useWhatsApp = confirm("✅ Mission Authorized! \n\nDo you want to send this to the driver via WhatsApp?\n\n(Click 'Cancel' to just open the Tracker locally on this computer)");
const newTab = window.open('about:blank', '_blank');
try {
// --- NEW: Fetching the enriched structured dictionary instead of raw OSRM path arrays ---
const routePlan = window.activeRoutePlans[vehicleId];
if (!routePlan) throw new Error("Route plan metadata missing from memory.");
const safeFloat = (val) => { const n = parseFloat(val); return isNaN(n) ? 0 : n; };
const peRaw = window.currentPhysicsEngine || {};
let dispatchFuel = 0;
let dispatchCo2 = 0;
let dispatchEff = 0;
if (!window.sessionMetricsCommitted) {
dispatchFuel = safeFloat(peRaw.fuel_saved);
dispatchCo2 = safeFloat(peRaw.co2_saved);
dispatchEff = safeFloat(peRaw.efficiency);
window.sessionMetricsCommitted = true;
}
// Map the routePlan waypoints into flat [lat, lng] pairs for backward compatibility
const fallbackCoords = routePlan.map(wp => [wp.lat, wp.lng]);
const payload = {
vehicle_id: String(vehicleId),
route_plan: routePlan, // UPDATED: Conforms to List[RouteWaypoint]
route_coords: fallbackCoords, // Satisfies strict legacy backend validation
fuel_saved: dispatchFuel,
co2_saved: dispatchCo2,
efficiency: dispatchEff
};
const response = await fetch(`${window.API_BASE_URL}/api/vrp/dispatch`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-license-key': localStorage.getItem('uyo_license_key')
},
body: JSON.stringify(payload)
});
if (!response.ok) {
const errData = await response.json().catch(() => ({}));
throw new Error(`Server Code ${response.status}: ${errData.detail || response.statusText}`);
}
console.log(`✅ Mission Deploy Success: ${vehicleId}. Awaiting Database Commit...`);
await new Promise(resolve => setTimeout(resolve, 800));
await window.fetchLifetimeMetrics();
window.unassignedPinsLayer.clearLayers();
if (!window.map.hasLayer(window.routeLayerGroup)) {
window.map.addLayer(window.routeLayerGroup);
}
if (!window.liveFleetSocket || window.liveFleetSocket.readyState === WebSocket.CLOSED || window.liveFleetSocket.readyState === WebSocket.CLOSING) {
console.log("🔄 Re-establishing dropped Live Fleet telemetry line...");
window.connectLiveFleet();
}
const btns = document.querySelectorAll('button');
btns.forEach(btn => {
if (btn.innerText.includes('Deploy Live Mission') && btn.getAttribute('onclick')?.includes(vehicleId)) {
btn.innerHTML = `<i class="fa-solid fa-satellite-dish fa-beat" style="color: #4ade80;"></i> Tracking Live`;
btn.style.backgroundColor = "#166534";
btn.style.cursor = "not-allowed";
btn.disabled = true;
}
});
newTab.location.href = useWhatsApp ? whatsappLink : trackingUrl;
} catch (err) {
newTab.close();
console.error("Critical Synchronization Error:", err);
alert(`❌ Deployment Failed!\n\n${err.message}`);
}
};
window.connectLiveFleet = function() {
window.liveFleetSocket = new WebSocket(`${window.WS_BASE_URL}/ws/live-fleet`);
window.liveFleetSocket.onopen = function() { console.log("📡 Live Fleet Telemetry: Connected & Listening"); };
window.liveFleetSocket.onmessage = async function(event) {
let rawData;
try {
rawData = JSON.parse(event.data);
} catch (e) {
console.error("Failed to parse WebSocket JSON:", event.data);
return;
}
console.log(`🔥 RAW WS PING [${new Date().toISOString()}]:`, rawData);
const payload = rawData.telemetry ? rawData.telemetry : rawData;
const vId = payload.vehicle_id || payload.id;
// 🔴 STRICT SCHEMA FIX: Explicitly target the keys main.py sends (Patched for lon fallback)
const markerLat = parseFloat(payload.lat);
const markerLng = parseFloat(payload.lng || payload.lon);
if (isNaN(markerLat) || isNaN(markerLng) || !vId) {
if (payload.status === 'completed' && vId) {
console.log(`🏁 Mission Completed for ${vId}`);
if (window.liveMarkers[vId]) {
window.map.removeLayer(window.liveMarkers[vId]);
delete window.liveMarkers[vId];
}
}
return;
}
if (!window.activeDeployments[vId] && payload.status !== 'completed') {
console.log(`🔄 Global Sync Triggered: Fetching missing route geometry for ${vId}...`);
try {
const syncRes = await fetch(`${window.API_BASE_URL}/api/vrp/active-missions`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-license-key': localStorage.getItem('uyo_license_key')
}
});
const syncData = await syncRes.json();
if (syncData.active_missions && syncData.active_missions[vId]) {
const rawCoords = syncData.active_missions[vId].coords;
// Safely extract lat/lng regardless of array format or enriched dict format
const extractedCoords = rawCoords.map(c => Array.isArray(c) ? c : [c.lat, c.lng]);
L.polyline(extractedCoords, {
color: '#f59e0b',
weight: 4,
opacity: 0.8,
dashArray: '10, 10',
pane: 'routePane'
}).addTo(window.routeLayerGroup);
window.activeDeployments[vId] = extractedCoords;
console.log(`✅ Global Sync Complete: Route drawn for ${vId}`);
}
} catch (err) {
console.warn("Global Sync Failed:", err);
}
}
// --- Hardware-Accelerated 60FPS JS Interpolation ---
if (window.liveMarkers[vId]) {
const marker = window.liveMarkers[vId];
const el = marker.getElement();
if (el) {
el.style.transition = 'none';
}
marker.slideTo([markerLat, markerLng], 667);
marker.setZIndexOffset(1000);
} else {
const isBike = window.fleetRegistry[vId] !== undefined
? window.fleetRegistry[vId]
: String(vId).toLowerCase().includes('bike');
window.liveMarkers[vId] = L.marker([markerLat, markerLng], {
icon: window.createLiveIcon(vId, isBike),
pane: 'poiPane',
zIndexOffset: 1000
}).addTo(window.map);
}
// --- Strict Deviation Alert Mapping ---
if (payload.deviation_alert) {
const dotEl = document.getElementById(`ping-dot-${vId}`);
const badgeEl = document.getElementById(`ping-badge-${vId}`);
if (dotEl && badgeEl) {
dotEl.style.background = '#f97316';
dotEl.style.boxShadow = '0 0 25px #f97316';
dotEl.style.border = '3px solid #000000';
badgeEl.style.border = '1px solid #f97316';
badgeEl.style.color = '#f97316';
}
console.warn(`🚨 CRITICAL: ${vId} has deviated from the optimized route!`);
} else {
const isBike = window.fleetRegistry[vId] !== undefined
? window.fleetRegistry[vId]
: String(vId).toLowerCase().includes('bike');
const markerColor = isBike ? '#28a745' : '#dc3545';
const dotEl = document.getElementById(`ping-dot-${vId}`);
const badgeEl = document.getElementById(`ping-badge-${vId}`);
if (dotEl && badgeEl) {
dotEl.style.background = markerColor;
dotEl.style.boxShadow = `0 0 15px ${markerColor}`;
dotEl.style.border = '2.5px solid white';
badgeEl.style.border = `1px solid ${markerColor}`;
badgeEl.style.color = 'white';
}
}
if (payload.status === 'completed') {
console.log(`🏁 Mission Completed for ${vId}`);
}
};
window.liveFleetSocket.onerror = function(error) { console.error("WebSocket Error:", error); };
};
window.triggerTrafficRecalculate = async function(vehicleId) {
const activeCoords = window.activeDeployments[vehicleId];
if (!activeCoords) {
alert("Cannot recalculate: No active GPS data found for this vehicle.");
return;
}
const currentLicenseKey = localStorage.getItem('uyo_license_key');
const btn = document.getElementById(`recalc-btn-${vehicleId}`);
try {
if (btn) {
btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i> Checking Traffic...`;
btn.disabled = true;
}
console.log(`🚦 Re-optimizing remaining drops for ${vehicleId} using time-aware logic...`);
const remainingDeliveries = window.dynamicDeliveries.length > 0 ? window.dynamicDeliveries : [];
if (remainingDeliveries.length === 0) {
alert("No remaining drops available to recalculate.");
return;
}
const solveRes = await fetch(`${window.API_BASE_URL}/api/vrp/solve-dynamic`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-license-key': currentLicenseKey
},
body: JSON.stringify({
depot: window.depotLocation,
deliveries: remainingDeliveries,
fleet: [{ id: vehicleId, type: "van", capacity: 50, speed_factor: 1.0, fixed_cost: 0, cost_per_km: 50 }]
})
});
if (!solveRes.ok) throw new Error("Traffic Engine Failed.");
const data = await solveRes.json();
if (data.traffic_multiplier > 1.0) {
console.warn(`⚠️ High Traffic Detected! Penalty applied: ${data.traffic_multiplier}x`);
document.body.style.borderTop = "5px solid #f97316";
setTimeout(() => document.body.style.borderTop = "none", 5000);
}
const newMapUrl = "https://www.google.com/maps/dir/?api=1";
const pushRes = await fetch(`${window.API_BASE_URL}/api/vrp/push-reroute`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-license-key': currentLicenseKey
},
body: JSON.stringify({
vehicle_id: vehicleId,
new_gmaps_url: encodeURIComponent(newMapUrl)
})
});
if (pushRes.ok) {
alert(`✅ New Traffic-Aware Route Sent to ${vehicleId} Driver!`);
}
} catch (err) {
console.error("Reroute Error:", err);
alert("Failed to calculate new traffic route.");
} finally {
if (btn) {
btn.innerHTML = `<i class="fa-solid fa-code-merge"></i> Recalculate Traffic`;
btn.disabled = false;
}
}
};
window.downloadSurveyManifest = function(routeData, opIntelData) {
let csvContent = "\uFEFFVehicle ID,Vehicle Type,Stop Sequence,Estimated Arrival (ETA),Internal Node ID,Inventory Load,Travel Leg (Mins),Status\n";
const routesArray = routeData.routes || routeData.optimized_routes || [];
routesArray.forEach(route => {
const vehicleId = route.vehicle_id || route.id || "UYO-VEH-1";
const vehicleType = route.vehicle_type || route.type || "van";
let details = route.route_details;
if (!details && route.route) {
details = route.route.map((nodeId, idx) => {
return {
stop_sequence: idx,
node_id: nodeId,
arrival_time: "Calculated Live",
demand: (idx === 0 || idx === route.route.length - 1) ? 0 : 1,
cumulative_mins: 0
};
});
}
if (!details) return;
const maxSeq = details.length - 1;
details.forEach(stop => {
let status = "On Route";
if (stop.stop_sequence === maxSeq) status = "Return to Depot";
let row = [
vehicleId,
vehicleType,
stop.stop_sequence,
stop.arrival_time || "00:00 AM",
stop.node_id,
stop.demand || stop.weight_load_after_stop || stop.inventory_load || 0,
Number(stop.cumulative_mins || 0).toFixed(2),
status
].join(",");
csvContent += row + "\n";
});
});
csvContent += ",,,,,,,\n";
csvContent += "--- EXECUTIVE BI SUMMARY ---,,,,,,,\n";
csvContent += `Total Orders Dispatched,"${opIntelData.drops || 0} Drops",,,,,,\n`;
csvContent += `Total Fleet Operation Time,"${opIntelData.total_mins || 0} Mins",,,,,,\n`;
csvContent += `Estimated Fuel Savings,"${opIntelData.fuel_saved || '₦0'}",,,,,,\n`;
csvContent += `Fleet Efficiency Score,"${opIntelData.efficiency || '0%'}",,,,,,\n`;
csvContent += `CO2 Emission Offset,"${opIntelData.co2_saved || '0 kg'}",,,,,,\n`;
const now = new Date();
const timestamp = now.toISOString().replace('T', ' ').substring(0, 19);
csvContent += `Optimization Timestamp,"${timestamp}",,,,,,\n`;
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
link.setAttribute("href", url);
const filenameId = Math.floor(Math.random() * 900000) + 100000;
link.setAttribute("download", `Uyo_Logistics_Report_${filenameId}.csv`);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
};
// --- 1. SECURITY HANDSHAKE (OPTIMISTIC UI SECURE BOOT) ---
const activeLicenseKey = localStorage.getItem('uyo_license_key');
if (!activeLicenseKey) {
console.warn("🔒 Unauthorized access attempt. Redirecting to Secure Login.");
window.location.replace("login.html");
} else {
console.log("🔄 Performing Background Validation Ping...");
bootCommandCenter();
// 🔴 SYNCHRONIZATION FIX: Handshake explicitly dynamically tied to window.API_BASE_URL to avoid hardcoded domain blocks
fetch(`${window.API_BASE_URL}/api/vrp/history`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'x-license-key': activeLicenseKey
}
})
.then(response => {
if (response.status === 401 || response.status === 403) {
console.error("❌ Background Kill-Switch Triggered: License Expired.");
localStorage.removeItem('uyo_license_key');
window.location.replace("login.html");
} else {
console.log("✅ License Key Verified. Session secured.");
}
})
.catch(err => {
console.warn("⚠️ Validation ping network delay. Relying on endpoint interceptors.", err);
});
}
// ==============================================================================
// --- MASTER BOOTLOADER (GATED APPLICATION LOGIC) ---
// ==============================================================================
function bootCommandCenter() {
console.log("🚀 Uyo Logistics Engine v2.5.5 LOADED - Unified Telemetry Active");
const uyoCenter = [5.0377, 7.9128];
// 🔴 SURVEY-GRADE FIX: Frontend bounds perfectly synced to vrp.py matrix
const uyoMathematicalBounds = L.latLngBounds(
L.latLng(4.8000, 7.7000),
L.latLng(5.2500, 8.2000)
);
const darkMap = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png?key=cb1_25zt_1_55c6b7ed19fd0cb6b0e8591b', {
attribution: '© OpenStreetMap contributors, © CARTO',
subdomains: 'abcd',
maxZoom: 22,
maxNativeZoom: 19
});
const lightMap = L.tileLayer('https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}{r}.png?key=cb1_25zt_1_55c6b7ed19fd0cb6b0e8591b', {
attribution: '© OpenStreetMap contributors, © CARTO',
subdomains: 'abcd',
maxZoom: 22,
maxNativeZoom: 19
});
const satellite = L.tileLayer('https://mt1.google.com/vt/lyrs=s&x={x}&y={y}&z={z}', {
attribution: '© Google',
maxZoom: 22,
maxNativeZoom: 20
});
window.map = L.map('map', { center: uyoCenter, zoom: 13, maxZoom: 22, layers: [darkMap], zoomControl: false });
L.control.zoom({ position: 'bottomright' }).addTo(window.map);
L.control.scale({ position: 'bottomleft', metric: true, imperial: false }).addTo(window.map);
const mapLegend = L.control({ position: 'bottomleft' });
mapLegend.onAdd = function () {
const div = L.DomUtil.create('div', 'info legend');
div.style.cssText = "background-color: rgba(31, 41, 55, 0.9); border-radius: 8px; border: 1px solid #374151; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.5); color: #e5e7eb; font-family: ui-sans-serif, system-ui, sans-serif; backdrop-filter: blur(4px); overflow: hidden; transition: all 0.3s ease; margin-bottom: 5px;";
div.innerHTML = `
<div id="legend-header" style="padding: 8px 12px; cursor: pointer; display: flex; align-items: center; justify-content: space-between; user-select: none;">
<span style="font-weight: 900; color: #60a5fa; text-transform: uppercase; letter-spacing: 0.05em; font-size: 10px;">
<i class="fa-solid fa-layer-group" style="margin-right: 4px;"></i> Spatial Legend
</span>
<i id="legend-chevron" class="fa-solid fa-chevron-up" style="font-size: 10px; margin-left: 14px; transition: transform 0.3s ease;"></i>
</div>
<div id="legend-content" style="padding: 0 12px 12px 12px; font-size: 11px; line-height: 1.8; display: none;">
<div style="display: flex; align-items: center;"><i class="fa-solid fa-truck" style="color: #dc3545; width: 16px; margin-right: 6px;"></i> Van Route (Heavy)</div>
<div style="display: flex; align-items: center;"><i class="fa-solid fa-motorcycle" style="color: #28a745; width: 16px; margin-right: 6px;"></i> Bike Route (Agile)</div>
<div style="display: flex; align-items: center;"><i class="fa-solid fa-square" style="color: #ef4444; opacity: 0.5; width: 16px; margin-right: 6px;"></i> Operations Boundary</div>
<div style="font-weight: bold; margin-top: 8px; margin-bottom: 4px; border-bottom: 1px solid #374151; padding-bottom: 2px;">Market Hotspots (Gi*)</div>
<div style="display: flex; height: 10px; margin-top: 4px; border-radius: 2px; overflow: hidden; border: 1px solid #4b5563;">
<div style="flex: 1; background-color: rgba(253, 174, 97, 0.6);"></div>
<div style="flex: 1; background-color: rgba(215, 25, 28, 0.7);"></div>
</div>
<div style="display: flex; justify-content: space-between; font-size: 9px; color: #9ca3af; margin-top: 2px; font-weight: bold;">
<span>95% Sig.</span>
<span>99% Sig.</span>
</div>
<div style="font-weight: bold; margin-top: 8px; margin-bottom: 4px; border-bottom: 1px solid #374151; padding-bottom: 2px;">Accessibility Reach</div>
<div style="display: flex; height: 10px; margin-top: 4px; border-radius: 2px; overflow: hidden; border: 1px solid #4b5563;">
<div style="flex: 1; background-color: rgba(0, 104, 55, 0.85);"></div>
<div style="flex: 1; background-color: rgba(49, 163, 84, 0.6);"></div>
<div style="flex: 1; background-color: rgba(120, 198, 121, 0.35);"></div>
</div>
<div style="display: flex; justify-content: space-between; font-size: 9px; color: #9ca3af; margin-top: 2px; font-weight: bold;">
<span>5 Min</span>
<span>10 Min</span>
<span>15 Min</span>
</div>
<div style="display: flex; align-items: center; margin-top: 8px;">
<div style="width: 12px; height: 12px; border-radius: 50%; border: 3px solid #3b82f6; background: #ffffff; margin-right: 6px; margin-left: 1px; box-shadow: 0 0 8px rgba(59, 130, 246, 0.8);"></div> Central Depot
</div>
<div style="display: flex; align-items: center; margin-top: 4px;">
<div style="width: 10px; height: 10px; border-radius: 50%; border: 2px solid #3b82f6; background: white; margin-right: 8px; margin-left: 2px; box-shadow: 0 0 5px rgba(255,255,255,0.5);"></div> Unassigned Drop
</div>
<div style="display: flex; align-items: center; margin-top: 4px;">
<div style="width: 10px; height: 10px; border-radius: 50%; border: 2px solid white; background: #ef4444; margin-right: 8px; margin-left: 2px; box-shadow: 0 0 8px #ef4444;"></div> Live Fleet Ping
</div>
</div>
`;
L.DomEvent.disableClickPropagation(div);
setTimeout(() => {
const header = document.getElementById('legend-header');
const content = document.getElementById('legend-content');
const chevron = document.getElementById('legend-chevron');
let isOpen = false;
header.onclick = function() {
isOpen = !isOpen;
content.style.display = isOpen ? 'block' : 'none';
chevron.style.transform = isOpen ? 'rotate(180deg)' : 'rotate(0deg)';
};
}, 100);
return div;
};
mapLegend.addTo(window.map);
window.map.createPane('hotspotPane'); window.map.getPane('hotspotPane').style.zIndex = 300;
window.map.createPane('accessibilityPane'); window.map.getPane('accessibilityPane').style.zIndex = 310;
window.map.createPane('routePane'); window.map.getPane('routePane').style.zIndex = 400;
window.map.createPane('poiPane'); window.map.getPane('poiPane').style.zIndex = 600;
window.routeLayerGroup = L.layerGroup().addTo(window.map);
const hotspotLayer = L.layerGroup();
const boundaryLayer = L.layerGroup();
const poiLayer = L.layerGroup();
const accessibilityLayer = L.layerGroup();
window.unassignedPinsLayer = L.layerGroup().addTo(window.map);
const baseMaps = {
"Command Center (Dark)": darkMap,
"Clean Street (Light)": lightMap,
"Satellite View": satellite
};
const overlayMaps = {
"<b>Live Operations</b>": window.routeLayerGroup,
"Demand Hotspots": hotspotLayer,
"City Boundaries": boundaryLayer,
"Points of Interest": poiLayer,
"Accessibility": accessibilityLayer
};
const isMobile = window.innerWidth < 768;
L.control.layers(baseMaps, overlayMaps, {
position: 'topright',
collapsed: isMobile
}).addTo(window.map);
const layerStyles = {
boundaries: { color: "#ef4444", weight: 3, fillOpacity: 0.05, dashArray: '5, 10', interactive: false },
hotspots: (feature) => {
const z = feature.properties?.z_score;
const w = feature.properties?.weight;
if (z !== undefined) {
if (z > 2.58) return { color: "white", weight: 1, fillColor: "#d7191c", fillOpacity: 0.7, interactive: false };
if (z > 1.96) return { color: "white", weight: 1, fillColor: "#fdae61", fillOpacity: 0.6, interactive: false };
if (z < -2.58) return { color: "white", weight: 1, fillColor: "#2c7bb6", fillOpacity: 0.7, interactive: false };
if (z < -1.96) return { color: "white", weight: 1, fillColor: "#abd9e9", fillOpacity: 0.6, interactive: false };
return { stroke: false, fillOpacity: 0, interactive: false };
}
else {
if (w >= 0.8) return { color: "white", weight: 1, fillColor: "#d7191c", fillOpacity: 0.7, interactive: false };
if (w >= 0.6) return { color: "white", weight: 1, fillColor: "#fdae61", fillOpacity: 0.6, interactive: false };
if (w <= 0.2) return { color: "white", weight: 1, fillColor: "#2c7bb6", fillOpacity: 0.7, interactive: false };
if (w <= 0.4) return { color: "white", weight: 1, fillColor: "#abd9e9", fillOpacity: 0.6, interactive: false };
return { stroke: false, fillOpacity: 0, interactive: false };
}
},
accessibility: (feature) => {
const timeVal = feature.properties?.cost_level || feature.properties?.time || feature.properties?.cost;
if (timeVal <= 300 || (timeVal <= 5 && timeVal > 0)) {
return { fillColor: '#006837', color: '#ffffff', weight: 1.5, fillOpacity: 0.85, interactive: false };
}
else if (timeVal <= 600 || (timeVal <= 10 && timeVal > 0)) {
return { fillColor: '#31a354', color: '#ffffff', weight: 1.5, fillOpacity: 0.5, interactive: false };
}
else {
return { fillColor: '#78c679', color: '#ffffff', weight: 1, fillOpacity: 0.25, interactive: false };
}
}
};
async function fetchSpatialLayer(endpoint, layerGroup, styleConfig, targetPane = 'overlayPane') {
try {
const currentKey = localStorage.getItem('uyo_license_key');
const response = await fetch(`${window.API_BASE_URL}/api/layers${endpoint}`, {
method: 'GET',
headers: { 'Content-Type': 'application/json', 'x-license-key': currentKey }
});
if (response.status === 401) {
console.error(`🔒 Session Expired: Rejected by ${endpoint}`);
localStorage.removeItem('uyo_license_key');
alert("Your Corporate License or Trial Key has expired. Please log in again to renew access.");
window.location.href = "login.html";
return;
}
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
L.geoJSON(data, {
pane: targetPane,
style: styleConfig.style || styleConfig,
pointToLayer: styleConfig.pointToLayer || null,
onEachFeature: (feature, layer) => {
if (styleConfig.interactive !== false) {
let popup = `<strong class="text-blue-600 uppercase tracking-widest text-xs">${endpoint.replace('/', '')} DATA</strong><br>`;
for (let key in feature.properties) { if (feature.properties[key]) popup += `<b class="text-gray-700 capitalize">${key}:</b> ${feature.properties[key]}<br>`; }
layer.bindPopup(popup);
}
}
}).addTo(layerGroup);
} catch (err) {
console.warn(`⚠️ Error loading ${endpoint}:`, err);
}
}
function loadAllDatabaseLayers() {
fetchSpatialLayer('/hotspots', hotspotLayer, layerStyles.hotspots, 'hotspotPane');
fetchSpatialLayer('/boundaries', boundaryLayer, { style: layerStyles.boundaries });
fetchSpatialLayer('/accessibility', accessibilityLayer, layerStyles.accessibility, 'accessibilityPane');
fetchSpatialLayer('/pois', poiLayer, {
pointToLayer: (feature, latlng) => {
const category = String(feature.properties?.amenity || feature.properties?.cat_label || feature.properties?.type || '').toLowerCase();
let iconClass = 'fa-solid fa-map-pin'; let color = '#71717a';
if (category.includes('school') || category.includes('education')) { iconClass = 'fa-solid fa-graduation-cap'; color = '#3b82f6'; }
else if (category.includes('health') || category.includes('hospit') || category.includes('clinic')) { iconClass = 'fa-solid fa-kit-medical'; color = '#ef4444'; }
else if (category.includes('hotel') || category.includes('lodging')) { iconClass = 'fa-solid fa-bed'; color = '#8b5cf6'; }
else if (category.includes('bank') || category.includes('atm')) { iconClass = 'fa-solid fa-building-columns'; color = '#eab308'; }
else if (category.includes('worship') || category.includes('churc') || category.includes('mosque')) { iconClass = 'fa-solid fa-church'; color = '#d946ef'; }
else if (category.includes('restau') || category.includes('food')) { iconClass = 'fa-solid fa-utensils'; color = '#f97316'; }
else if (category.includes('fuel') || category.includes('gas')) { iconClass = 'fa-solid fa-gas-pump'; color = '#14b8a6'; }
else if (category.includes('gover') || category.includes('police')) { iconClass = 'fa-solid fa-landmark'; color = '#0ea5e9'; }
const htmlString = `<div style="background-color: ${color}; color: white; width: 14px; height: 14px; border-radius: 50%; border: 1px solid white; display: flex; align-items: center; justify-content: center; box-shadow: 0 1px 3px rgba(0,0,0,0.5);"><i class="${iconClass}" style="font-size: 7px;"></i></div>`;
return L.marker(latlng, { icon: L.divIcon({ html: htmlString, className: 'custom-poi', iconSize: [14, 14], iconAnchor: [7, 7], popupAnchor: [0, -7] }), pane: 'poiPane' });
}
}, 'poiPane');
}
loadAllDatabaseLayers();
const depotIcon = L.divIcon({ className: 'depot', html: `<div style="background-color: #ffffff; border: 4px solid #3b82f6; border-radius: 50%; width: 24px; height: 24px; box-shadow: 0 0 20px rgba(59, 130, 246, 1);"></div>` });
const depotMarker = L.marker([window.depotLocation.lat, window.depotLocation.lon], { icon: depotIcon, draggable: true, pane: 'poiPane' }).addTo(window.map);
depotMarker.on('dragend', function() {
const position = depotMarker.getLatLng();
window.depotLocation.lat = parseFloat(position.lat.toFixed(6));
window.depotLocation.lon = parseFloat(position.lng.toFixed(6));
});
window.removePin = function(dropId) {
window.dynamicDeliveries = window.dynamicDeliveries.filter(d => d.id !== dropId);
window.unassignedPinsLayer.eachLayer(function(layer) {
if (layer.options.dropId === dropId) {
window.unassignedPinsLayer.removeLayer(layer);
}
});
console.log(`🗑️ Removed Drop: ${dropId}`);
};
// --- 🔴 SURVEY-GRADE FIX: Strict Mathematical Interception ---
// Removed dependency on GeoJSON boundaryLayer to prevent "click-trap" bugs.
window.map.on('click', function(e) {
if (!uyoMathematicalBounds.contains(e.latlng)) {
alert("⚠️ Location is outside the Uyo operational geofence (Lat 4.80-5.25, Lon 7.70-8.20).");
return;
}
let custName = prompt("Enter Customer Name (or leave blank for Unknown):", "") || "Unknown Customer";
let custPhone = prompt("Enter Customer Phone Number:", "") || "N/A";
let weightInput = prompt("Enter parcel weight in kg for this stop (e.g., 2, 15, 30):", "1");
let parsedWeight = parseInt(weightInput, 10);
if (isNaN(parsedWeight) || parsedWeight <= 0) {
parsedWeight = 1;
}
const cleanLat = parseFloat(e.latlng.lat.toFixed(6));
const cleanLng = parseFloat(e.latlng.lng.toFixed(6));
const dropId = "ORD-" + Math.floor(Math.random() * 10000);
window.dynamicDeliveries.push({
id: dropId,
lat: cleanLat,
lon: cleanLng,
weight: parsedWeight,
customer_name: custName,
phone: custPhone
});
const popupContent = `
<div style="text-align: center;">
<b style="color: #1f2937;">Order: ${dropId}</b><br>
<span style="font-size: 12px; color: #3b82f6;"><b>${custName}</b></span><br>
<span style="font-size: 11px; color: #4b5563;">${custPhone}</span><br>
<span style="font-size: 11px; font-weight: bold; color: #28a745;">Weight: ${parsedWeight} kg</span><br>
<button onclick="window.removePin('${dropId}')" style="margin-top: 8px; padding: 4px 8px; background-color: #ef4444; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 11px; font-weight: bold;">
<i class="fa-solid fa-trash"></i> Remove Drop
</button>
</div>
`;
L.marker([cleanLat, cleanLng], {
dropId: dropId,
icon: L.divIcon({ className: 'unassigned', html: `<div style="background-color: #ffffff; border: 2px solid #3b82f6; border-radius: 50%; width: 14px; height: 14px; box-shadow: 0 0 10px rgba(255,255,255,0.5);"></div>` }),
pane: 'poiPane'
}).addTo(window.unassignedPinsLayer).bindPopup(popupContent);
});
const searchInput = document.getElementById('custom-search');
let searchContainer = null;
let dropdownMenu = null;
if (searchInput) {
searchContainer = searchInput.parentElement;
dropdownMenu = document.createElement('div');
dropdownMenu.id = 'search-dropdown';
dropdownMenu.style.cssText = 'position:absolute; top:calc(100% + 5px); left:0; width:100%; background:#1f2937; color:white; z-index:9999; border-radius:8px; box-shadow:0 10px 25px rgba(0,0,0,0.8); display:none; max-height:300px; overflow-y:auto; font-family: ui-sans-serif, system-ui, sans-serif; pointer-events:auto;';
searchContainer.appendChild(dropdownMenu);
if (searchContainer.parentNode) {
searchContainer.parentNode.removeChild(searchContainer);
}
const NativeSearchControl = L.Control.extend({
options: { position: 'topleft' },
onAdd: function() {
searchContainer.style.position = 'relative';
searchContainer.style.top = 'auto';
searchContainer.style.left = 'auto';
searchContainer.style.transform = 'none';
searchContainer.style.width = isMobile ? '65vw' : '350px';
searchContainer.style.margin = '10px';
searchContainer.style.zIndex = 'auto';
searchContainer.classList.remove('overflow-hidden');
searchContainer.style.overflow = 'visible';
L.DomEvent.disableClickPropagation(searchContainer);
L.DomEvent.disableScrollPropagation(searchContainer);
return searchContainer;
}
});
window.map.addControl(new NativeSearchControl());
}
window.executeSearch = async function() {
if (!searchInput || !searchContainer || !dropdownMenu) return;
const query = searchInput.value.trim();
if (!query) return;
const btn = searchContainer.querySelector('button');
let originalBtnHtml = "Search";
if (btn) {
originalBtnHtml = btn.innerHTML;
btn.innerHTML = `<i class="fa-solid fa-spinner fa-spin"></i>`;
}
dropdownMenu.innerHTML = '';
dropdownMenu.style.display = 'none';
let combinedResults = [];
const lowerQuery = query.toLowerCase();
try {
poiLayer.eachLayer(layer => {
const props = layer?.feature?.properties;
if (!props) return;
const poiName = String(props.name || props.poi_name || props.title || '').toLowerCase();
if (poiName.includes(lowerQuery)) {
combinedResults.push({
lat: layer.getLatLng().lat, lng: layer.getLatLng().lng,
name: props.name || query, address: "Verified Local Database", source: "LOCAL", icon: "fa-database"
});
}
});
const searchPromises = [];
searchPromises.push(
fetch(`https://nominatim.openstreetmap.org/search?q=${encodeURIComponent(query)},Uyo,Akwa Ibom&format=json&limit=3`)
.then(res => res.json())
.then(data => {
if(data && data.length) {
data.forEach(item => {
combinedResults.push({
lat: parseFloat(item.lat), lng: parseFloat(item.lon),
name: item.name || query, address: item.display_name.split(',')[0] + " (OSM)", source: "NOMINATIM", icon: "fa-road"
});
});
}
}).catch(err => console.warn("Nominatim failed:", err))
);
// 🔴 SECURITY FIX: Redacted hardcoded API key to clear GitHub Secret Alert
const GOOGLE_API_KEY = window.ENV_GOOGLE_API_KEY || "AIzaSyA9Y339K4gDbQGQDSzWKppq2pmUvxODiho";
const locationRestriction = { rectangle: { low: { latitude: 4.8000, longitude: 7.7000 }, high: { latitude: 5.2500, longitude: 8.2000 } } };
searchPromises.push(
fetch(`https://places.googleapis.com/v1/places:searchText`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-Goog-Api-Key': GOOGLE_API_KEY, 'X-Goog-FieldMask': 'places.location,places.formattedAddress,places.displayName' },
body: JSON.stringify({ textQuery: lowerQuery.includes('uyo') ? query : `${query}, Uyo`, locationRestriction: locationRestriction })
})
.then(res => res.json())
.then(data => {
if (data && data.places) {
data.places.slice(0, 3).forEach(place => {
if(place.location) {
combinedResults.push({
lat: parseFloat(place.location.latitude), lng: parseFloat(place.location.longitude),
name: place.displayName ? place.displayName.text : query, address: place.formattedAddress ? place.formattedAddress.split(',')[0] : "Uyo", source: "GOOGLE", icon: "fa-google"
});
}
});
}
}).catch(err => console.warn("Google failed:", err))
);
await Promise.allSettled(searchPromises);
const safeBounds = uyoMathematicalBounds.pad(0.5);
let uniqueResults = [];
combinedResults.forEach(res => {
if(!res.lat || !res.lng || isNaN(res.lat) || isNaN(res.lng)) return;