-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
4856 lines (4200 loc) · 208 KB
/
Copy pathapp.js
File metadata and controls
4856 lines (4200 loc) · 208 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
// ==========================
// Configuration & Constants
// ==========================
// Version: 2.0.1 - Fixed effectiveRange references
// EASY TO UPDATE ASSUMPTIONS - MODIFY THESE VALUES AS NEEDED
const RANGE_DERATING_FACTORS = {
coldClimate: 0.30, // 30% range reduction in cold climates (below freezing)
batteryDegradation5Year: 0.10, // 10% capacity loss after 5 years
hillsTerrain: 0.15, // 15% range reduction for rolling hills
mountainousTerrain: 0.25, // 25% range reduction for mountainous terrain
stopsPenalty: 0.001 // 0.1% range reduction per stop (regenerative braking helps)
};
const CHARGING_TIME_SCENARIOS = {
overnight: 12, // 12 hours available for overnight charging
midday: 4, // 4 hours available for mid-day charging
afternoon: 5 // 5 hours between trips
};
const CHARGER_REDUNDANCY_FACTOR = 0.20; // 20% extra chargers for redundancy
// ==========================
// State Management
// ==========================
// Wizard state
let currentStep = 1;
let completedSteps = new Set([1]); // Step 1 is always accessible
let selectedChargerScenario = null;
// Bus schedule data
let busSchedules = []; // Array of { id, name, trips: [], selectedBus: null }
let nextBusScheduleId = 1;
// Configuration data
let depotClimate = null;
let busesData = [];
let chargersData = [];
let currentResults = null;
// ==========================
// Data Loading
// ==========================
async function loadData() {
try {
console.log('Loading data files...');
// Load local data files from the `data/` folder
const [typeA, typeC, typeD, chargers] = await Promise.all([
fetch('data/buses-type-a.json').then(r => {
if (!r.ok) throw new Error(`Failed to load Type A buses: ${r.status}`);
return r.json();
}),
fetch('data/buses-type-c.json').then(r => {
if (!r.ok) throw new Error(`Failed to load Type C buses: ${r.status}`);
return r.json();
}),
fetch('data/buses-type-d.json').then(r => {
if (!r.ok) throw new Error(`Failed to load Type D buses: ${r.status}`);
return r.json();
}),
fetch('data/chargers.json').then(r => {
if (!r.ok) throw new Error(`Failed to load chargers: ${r.status}`);
return r.json();
})
]);
// Process bus data to normalize range and battery capacity properties
busesData = [...typeA, ...typeC, ...typeD].map(bus => {
// Extract range from various possible formats
let rangeRated = 0;
if (bus.battery && bus.battery.options && bus.battery.options.length > 0) {
// Use highest range option
rangeRated = Math.max(...bus.battery.options.map(opt => opt.range || 0));
} else if (bus.range) {
// Use range.usable first, then range.nameplate
rangeRated = bus.range.usable || bus.range.nameplate || bus.range.nameplate2 || 0;
}
// Extract battery capacity from various possible formats
let batteryCapacity = 0;
if (bus.battery) {
if (bus.battery.usableKwh) {
batteryCapacity = bus.battery.usableKwh;
} else if (bus.battery.nameplateKwh) {
batteryCapacity = bus.battery.nameplateKwh;
} else if (bus.battery.options && bus.battery.options.length > 0) {
// Use highest capacity option
batteryCapacity = Math.max(...bus.battery.options.map(opt => opt.usableKwh || opt.nameplateKwh || 0));
}
}
return {
...bus,
rangeRated: rangeRated,
batteryCapacity: batteryCapacity
};
});
chargersData = chargers;
console.log('✅ Data loaded successfully:', {
typeA: typeA.length,
typeC: typeC.length,
typeD: typeD.length,
totalBuses: busesData.length,
chargers: chargersData.length
});
// Log first bus to verify data structure and rangeRated
if (busesData.length > 0) {
console.log('Sample bus data:', busesData[0]);
console.log('Sample rangeRated:', busesData[0].rangeRated);
}
} catch (error) {
console.error('❌ Error loading data:', error);
alert(`Error loading bus and charger data: ${error.message}\n\nMake sure you're running this through a web server (e.g., python -m http.server 8000) and not opening the HTML file directly.\n\nCheck the browser console (F12) for more details.`);
}
}
// ==========================
// Climate Detection
// ==========================
async function detectClimate(location) {
if (!location || location.trim() === '') {
return null;
}
try {
// Using OpenStreetMap Nominatim API for geocoding (free, no API key required)
// Restricting to US addresses only
const geocodeUrl = `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(location)}&countrycodes=us`;
const response = await fetch(geocodeUrl, {
headers: {
'User-Agent': 'ElectricSchoolBusPlanner/1.0'
}
});
if (!response.ok) {
throw new Error('Geocoding failed');
}
const data = await response.json();
if (data && data.length > 0) {
const lat = parseFloat(data[0].lat);
const lon = parseFloat(data[0].lon);
// Simple climate classification based on latitude
// Cold climate zones (experiencing freezing temperatures):
// Generally above 40° latitude in Northern Hemisphere
// or below -40° in Southern Hemisphere
const isColdClimate = Math.abs(lat) > 40;
return {
lat,
lon,
isColdClimate,
location: data[0].display_name,
deratingFactor: isColdClimate ? RANGE_DERATING_FACTORS.coldClimate : 0
};
}
return null;
} catch (error) {
console.error('Error detecting climate:', error);
// Fallback: assume moderate climate
return {
lat: null,
lon: null,
isColdClimate: false,
location: location,
deratingFactor: 0
};
}
}
// ==========================
// Range Calculations
// ==========================
function calculateEffectiveRange(bus, trip, climate, considerDegradation) {
// Get base range
let baseRange;
if (bus.battery.options && bus.battery.options.length > 0) {
// Use the highest range option
baseRange = Math.max(...bus.battery.options.map(opt => opt.range || 0));
} else {
baseRange = bus.range.usable || bus.range.nameplate || 0;
}
if (!baseRange) return 0;
let effectiveRange = baseRange;
// Check global settings
const weatherCheckbox = document.getElementById('considerWeather');
const terrainCheckbox = document.getElementById('considerTerrain');
const terrainDropdown = document.getElementById('terrainType');
const useWeather = weatherCheckbox ? weatherCheckbox.checked : true;
const useTerrain = terrainCheckbox ? terrainCheckbox.checked : false;
// Apply climate derating
if (useWeather && climate && climate.isColdClimate) {
effectiveRange *= (1 - RANGE_DERATING_FACTORS.coldClimate);
}
// Apply battery degradation if enabled
if (considerDegradation) {
effectiveRange *= (1 - RANGE_DERATING_FACTORS.batteryDegradation5Year);
}
// Apply terrain derating
let terrainToUse = 'flat';
if (useTerrain && terrainDropdown) {
terrainToUse = terrainDropdown.value;
} else if (!terrainCheckbox && trip.terrain) {
// Fallback for backward compatibility or if checkbox missing
terrainToUse = trip.terrain;
}
if (terrainToUse === 'rolling' || terrainToUse === 'hills') {
effectiveRange *= (1 - RANGE_DERATING_FACTORS.hillsTerrain);
} else if (terrainToUse === 'mountainous') {
effectiveRange *= (1 - RANGE_DERATING_FACTORS.mountainousTerrain);
}
// Apply stops penalty
if (trip.stops) {
const stopsPenalty = trip.stops * RANGE_DERATING_FACTORS.stopsPenalty;
effectiveRange *= (1 - Math.min(stopsPenalty, 0.1)); // Cap at 10% max
}
return Math.round(effectiveRange);
}
// ==========================
// Bus Compatibility Checking
// ==========================
function checkBusCompatibility(bus, trips, climate, considerDegradation) {
const compatibility = {
compatible: true,
issues: [],
warnings: [],
routeAssignments: [],
totalDailyMiles: 0
};
// Check passenger capacity for each trip
for (const trip of trips) {
if (bus.passengerCapacity && trip.passengers > bus.passengerCapacity) {
compatibility.compatible = false;
compatibility.issues.push(
`Insufficient capacity for ${trip.name}: needs ${trip.passengers} seats, bus has ${bus.passengerCapacity}`
);
}
}
// Calculate total daily mileage and check range
const totalMiles = trips.reduce((sum, trip) => sum + trip.miles, 0);
compatibility.totalDailyMiles = totalMiles;
const effectiveRange = calculateEffectiveRange(bus, trips[0], climate, considerDegradation);
// Check if bus can handle all trips
if (totalMiles > effectiveRange) {
// Check if mid-day charging could work
const sortedRoutes = [...trips].sort((a, b) => {
return (a.startTime || '').localeCompare(b.startTime || '');
});
let currentCharge = effectiveRange;
let needsMidDayCharging = false;
for (let i = 0; i < sortedRoutes.length; i++) {
const trip = sortedRoutes[i];
currentCharge -= trip.miles;
if (currentCharge < effectiveRange * 0.2) { // Below 20% charge
needsMidDayCharging = true;
// Check if there's time to charge before next trip
if (i < sortedRoutes.length - 1) {
const timeBetween = calculateTimeBetweenRoutes(trip, sortedRoutes[i + 1]);
if (timeBetween >= 2) { // At least 2 hours
compatibility.warnings.push(
`Requires mid-day fast charging (${timeBetween} hours available between trips)`
);
// Simulate charging
currentCharge = effectiveRange * 0.8; // Charge to 80%
} else {
compatibility.compatible = false;
compatibility.issues.push(
`Insufficient range and charging time between ${trip.name} and ${sortedRoutes[i + 1].name}`
);
}
}
}
}
}
// Assign trips
compatibility.routeAssignments = trips.map(r => r.name);
return compatibility;
}
function calculateTimeBetweenRoutes(route1, route2) {
if (!route1.endTime || !route2.startTime) return 0;
const end = timeToMinutes(route1.endTime);
const start = timeToMinutes(route2.startTime);
return Math.max(0, (start - end) / 60);
}
function timeToMinutes(timeStr) {
const [hours, minutes] = timeStr.split(':').map(Number);
return hours * 60 + minutes;
}
// ==========================
// Charger Optimization
// ==========================
function optimizeChargers(compatibleBuses, trips, climate) {
// Handle case with no compatible buses
if (!compatibleBuses || compatibleBuses.length === 0) {
const emptyScenario = {
name: 'N/A',
description: 'No compatible buses found',
chargers: [],
totalCost: 0,
estimatedInstallCost: 0
};
return {
'cost-optimized': emptyScenario,
'infrastructure-minimized': emptyScenario,
'balanced': emptyScenario,
'redundancy': emptyScenario
};
}
const scenarios = {
'cost-optimized': optimizeCostOptimized(compatibleBuses, trips),
'infrastructure-minimized': optimizeInfrastructureMinimized(compatibleBuses, trips),
'balanced': optimizeBalanced(compatibleBuses, trips),
'redundancy': optimizeWithRedundancy(compatibleBuses, trips)
};
return scenarios;
}
function optimizeCostOptimized(buses, trips) {
// Prefer Level 2 chargers (cheapest) when possible
const numBuses = buses.length;
const chargers = [];
// Safety check
if (numBuses === 0 || trips.length === 0) {
return {
name: 'Cost Optimized',
description: 'Minimizes upfront charger costs',
chargers: [],
totalCost: 0,
estimatedInstallCost: 0
};
}
// Check if overnight Level 2 charging is sufficient
const maxDailyMiles = Math.max(...trips.map(r => r.miles));
const avgBusRange = buses.reduce((sum, b) => sum + (b.range.usable || b.range.nameplate || 0), 0) / buses.length;
if (maxDailyMiles < avgBusRange * 0.7) {
// Level 2 overnight charging sufficient
const level2 = chargersData.find(c => c.id === 'level2-medium-ac-networkable');
if (level2) {
chargers.push({
...level2,
quantity: numBuses,
reason: 'Overnight charging sufficient for daily trips'
});
}
} else {
// Need mix of Level 2 and DC fast charging
const level2 = chargersData.find(c => c.id === 'level2-medium-ac-networkable');
const dcFast = chargersData.find(c => c.id === 'level3-slow-dc');
const dcFastCount = Math.ceil(numBuses * 0.3); // 30% DC fast
const level2Count = numBuses - dcFastCount;
if (level2Count > 0 && level2) {
chargers.push({
...level2,
quantity: level2Count,
reason: 'Primary overnight charging'
});
}
if (dcFast) {
chargers.push({
...dcFast,
quantity: dcFastCount,
reason: 'Mid-day quick charging capability'
});
}
}
return {
name: 'Cost Optimized',
description: 'Minimizes upfront charger costs by prioritizing Level 2 chargers',
chargers,
totalCost: calculateTotalChargerCost(chargers),
estimatedInstallCost: estimateInstallationCost(chargers)
};
}
function optimizeInfrastructureMinimized(buses, trips) {
// Use fewer, more powerful chargers
const numBuses = buses.length;
const chargers = [];
// Safety check
if (numBuses === 0) {
return {
name: 'Infrastructure Minimized',
description: 'Fewer, more powerful chargers',
chargers: [],
totalCost: 0,
estimatedInstallCost: 0
};
}
// Use DC fast chargers that can be shared
const dcFast50 = chargersData.find(c => c.id === 'level3-fast-dc-50kw');
// Assume 2:1 bus to charger ratio for DC fast
const chargerCount = Math.ceil(numBuses / 2);
if (dcFast50) {
chargers.push({
...dcFast50,
quantity: chargerCount,
reason: 'Fast charging allows sharing chargers between buses'
});
}
return {
name: 'Infrastructure Minimized',
description: 'Fewer, more powerful chargers to reduce infrastructure footprint',
chargers,
totalCost: calculateTotalChargerCost(chargers),
estimatedInstallCost: estimateInstallationCost(chargers)
};
}
function optimizeBalanced(buses, trips) {
// Balanced approach
const numBuses = buses.length;
const chargers = [];
// Safety check
if (numBuses === 0) {
return {
name: 'Balanced',
description: 'Mix of Level 2 and DC fast chargers',
chargers: [],
totalCost: 0,
estimatedInstallCost: 0
};
}
const level2 = chargersData.find(c => c.id === 'level2-medium-ac-networkable');
const dcFast = chargersData.find(c => c.id === 'level3-slow-dc');
// 60% Level 2, 40% DC
const level2Count = Math.ceil(numBuses * 0.6);
const dcCount = Math.ceil(numBuses * 0.4);
if (level2) {
chargers.push({
...level2,
quantity: level2Count,
reason: 'Primary overnight charging'
});
}
if (dcFast) {
chargers.push({
...dcFast,
quantity: dcCount,
reason: 'Flexibility for quick turnaround'
});
}
return {
name: 'Balanced',
description: 'Mix of Level 2 and DC fast chargers for operational flexibility',
chargers,
totalCost: calculateTotalChargerCost(chargers),
estimatedInstallCost: estimateInstallationCost(chargers)
};
}
function optimizeWithRedundancy(buses, trips) {
// Add redundancy for backup
const baseScenario = optimizeBalanced(buses, trips);
// Add 20% more chargers for redundancy
const chargersWithRedundancy = baseScenario.chargers.map(c => ({
...c,
quantity: Math.ceil(c.quantity * (1 + CHARGER_REDUNDANCY_FACTOR)),
reason: c.reason + ' (with redundancy)'
}));
return {
name: 'With Redundancy',
description: 'Additional chargers for backup and maintenance downtime',
chargers: chargersWithRedundancy,
totalCost: calculateTotalChargerCost(chargersWithRedundancy),
estimatedInstallCost: estimateInstallationCost(chargersWithRedundancy)
};
}
function calculateTotalChargerCost(chargers) {
return chargers.reduce((sum, c) => {
const avgCost = (c.priceRange.min + c.priceRange.max) / 2;
return sum + (avgCost * c.quantity);
}, 0);
}
function estimateInstallationCost(chargers) {
// Rough installation cost estimates
const costs = {
'$': 5000,
'$$': 15000,
'$$$': 35000,
'$$$$': 75000
};
return chargers.reduce((sum, c) => {
const installCost = costs[c.infrastructureCost] || 10000;
return sum + (installCost * c.quantity);
}, 0);
}
// ==========================
// Bus Schedule Management
// ==========================
function addBusSchedule(schedule) {
busSchedules.push({
id: nextBusScheduleId++,
...schedule
});
renderBusSchedules();
}
function editBusSchedule(index, schedule) {
busSchedules[index] = {
...busSchedules[index],
...schedule
};
renderBusSchedules();
}
function deleteBusSchedule(index) {
if (confirm('Are you sure you want to delete this bus schedule?')) {
busSchedules.splice(index, 1);
renderBusSchedules();
}
}
function renderBusSchedules() {
const container = document.getElementById('busSchedulesList');
if (busSchedules.length === 0) {
container.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🚌</div>
<p>No bus schedules added yet. Click "Add Bus Schedule" to get started.</p>
<small class="text-muted">Each bus schedule represents one physical bus with all its daily trips.</small>
</div>
`;
return;
}
container.innerHTML = busSchedules.map((schedule, index) => {
const totalMiles = schedule.trips.reduce((sum, t) => sum + t.miles, 0);
const maxPassengers = Math.max(...schedule.trips.map(t => t.passengers));
const firstTrip = schedule.trips[0];
const lastTrip = schedule.trips[schedule.trips.length - 1];
const timeRange = `${firstTrip.startTime} - ${lastTrip.endTime}`;
return `
<div class="bus-schedule-card">
<div class="bus-schedule-header">
<div>
<div class="bus-schedule-title">🚌 ${schedule.name}</div>
<div class="bus-schedule-subtitle">${schedule.trips.length} trip${schedule.trips.length > 1 ? 's' : ''} • ${totalMiles} miles • ${timeRange}</div>
</div>
<div class="bus-schedule-actions">
<button class="btn btn-sm btn-secondary" onclick="openEditBusScheduleModal(${index})">Edit</button>
<button class="btn btn-sm btn-danger" onclick="deleteBusSchedule(${index})">Delete</button>
</div>
</div>
<div class="trips-summary">
${schedule.trips.map((trip, tripIdx) => `
<div class="trip-summary-item">
<span class="trip-number">${tripIdx + 1}</span>
<div class="trip-summary-details">
<strong>${trip.startLocation || 'Start'} → ${trip.endLocation || 'End'}</strong>
<span class="trip-summary-meta">${trip.miles} mi • ${trip.passengers} passengers • ${trip.startTime}-${trip.endTime}</span>
${trip.returnToDepot !== false ? '<span class="depot-indicator">⚡ Returned to Chargers</span>' : '<span class="depot-indicator no-return">No Charging</span>'}
</div>
</div>
`).join('')}
</div>
<div class="bus-schedule-stats">
<div class="stat-badge">
<span class="stat-label">Total Distance</span>
<span class="stat-value">${totalMiles} mi</span>
</div>
<div class="stat-badge">
<span class="stat-label">Max Capacity Needed</span>
<span class="stat-value">${maxPassengers} seats</span>
</div>
<div class="stat-badge">
<span class="stat-label">Charging Stops</span>
<span class="stat-value">${schedule.trips.filter(t => t.returnToDepot !== false).length}</span>
</div>
</div>
</div>
`;
}).join('');
}
function saveBusSchedulesToFile() {
if (busSchedules.length === 0) {
alert('No bus schedules to save.');
return;
}
const data = JSON.stringify(busSchedules, null, 2);
const blob = new Blob([data], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'bus-schedules.json';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
function loadBusSchedulesFromFile(input) {
const file = input.files[0];
if (!file) return;
const reader = new FileReader();
reader.onload = function(e) {
try {
const loadedSchedules = JSON.parse(e.target.result);
// Basic validation
if (!Array.isArray(loadedSchedules)) {
throw new Error('Invalid file format: Expected an array of schedules.');
}
// Update state
busSchedules = loadedSchedules;
// Update ID counter to avoid conflicts
if (busSchedules.length > 0) {
const maxId = Math.max(...busSchedules.map(s => s.id || 0));
nextBusScheduleId = maxId + 1;
}
renderBusSchedules();
alert(`Successfully loaded ${busSchedules.length} bus schedules.`);
} catch (error) {
console.error('Error loading file:', error);
alert('Error loading file: ' + error.message);
}
// Reset input so same file can be selected again if needed
input.value = '';
};
reader.readAsText(file);
}
// ==========================
// Modal Management
// ==========================
let currentEditingScheduleIndex = null;
let modalTrips = []; // Temporary trips being edited in modal
function openAddBusScheduleModal() {
currentEditingScheduleIndex = null;
modalTrips = [];
document.getElementById('modalTitle').textContent = 'Add Bus Schedule';
document.getElementById('busScheduleName').value = `Bus #${busSchedules.length + 1}`;
// Add first trip by default
addTripToModal(false);
document.getElementById('busScheduleModal').style.display = 'flex';
// Ensure we start at the top
const modalBody = document.querySelector('#busScheduleModal .modal-body');
if (modalBody) modalBody.scrollTop = 0;
}
function openEditBusScheduleModal(index) {
currentEditingScheduleIndex = index;
const schedule = busSchedules[index];
modalTrips = [...schedule.trips]; // Clone trips
document.getElementById('modalTitle').textContent = 'Edit Bus Schedule';
document.getElementById('busScheduleName').value = schedule.name;
renderModalTrips();
document.getElementById('busScheduleModal').style.display = 'flex';
// Ensure we start at the top
const modalBody = document.querySelector('#busScheduleModal .modal-body');
if (modalBody) modalBody.scrollTop = 0;
}
function addTripToModal(scrollToNew = true) {
// Get the last trip to use for smart defaults
const lastTrip = modalTrips.length > 0 ? modalTrips[modalTrips.length - 1] : null;
let defaultStartLocation = '';
let defaultStartTime = '07:00';
if (lastTrip) {
// Start location = previous trip's end location
defaultStartLocation = lastTrip.endLocation || '';
// Start time = previous trip's end time
defaultStartTime = lastTrip.endTime || '07:00';
}
// Add a new trip with smart defaults
modalTrips.push({
startLocation: defaultStartLocation,
endLocation: '',
miles: 0,
passengers: lastTrip ? lastTrip.passengers : 0, // Use same passenger count as last trip
startTime: defaultStartTime,
endTime: addMinutesToTime(defaultStartTime, 60), // Default to 1 hour after start
returnToDepot: true,
notes: ''
});
renderModalTrips();
if (scrollToNew) {
setTimeout(() => {
const container = document.getElementById('modalTripsContainer');
const trips = container.querySelectorAll('.modal-trip-form');
const lastTrip = trips[trips.length - 1];
if (lastTrip) {
lastTrip.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}, 100);
}
}
// Helper function to add minutes to a time string (HH:MM format)
function addMinutesToTime(timeString, minutesToAdd) {
const [hours, minutes] = timeString.split(':').map(Number);
const totalMinutes = hours * 60 + minutes + minutesToAdd;
const newHours = Math.floor(totalMinutes / 60) % 24;
const newMinutes = totalMinutes % 60;
return `${String(newHours).padStart(2, '0')}:${String(newMinutes).padStart(2, '0')}`;
}
function removeTripFromModal(tripIndex) {
if (modalTrips.length === 1) {
alert('A bus schedule must have at least one trip.');
return;
}
modalTrips.splice(tripIndex, 1);
renderModalTrips();
}
function renderModalTrips() {
const container = document.getElementById('modalTripsContainer');
const tripsHTML = modalTrips.map((trip, index) => `
<div class="modal-trip-form" data-trip-index="${index}">
<div class="modal-trip-header">
<h4>Trip ${index + 1}</h4>
${modalTrips.length > 1 ? `<button type="button" class="btn-icon-only" onclick="removeTripFromModal(${index})">✕</button>` : ''}
</div>
<div class="form-row">
<div class="form-group">
<label>Start Location</label>
<input type="text" value="${trip.startLocation || ''}"
onchange="updateModalTrip(${index}, 'startLocation', this.value)"
placeholder="e.g., Depot or School">
</div>
<div class="form-group">
<label>End Location</label>
<input type="text" value="${trip.endLocation || ''}"
onchange="updateModalTrip(${index}, 'endLocation', this.value)"
placeholder="e.g., School or Last Stop">
<div style="margin-top: 8px;">
<label style="font-weight: normal; display: flex; align-items: center; gap: 8px; cursor: pointer;">
<input type="checkbox" ${trip.returnToDepot !== false ? 'checked' : ''}
onchange="updateModalTrip(${index}, 'returnToDepot', this.checked)"
style="width: auto; margin: 0;">
<span>Can charge at this location</span>
</label>
</div>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label>Distance (miles)*</label>
<input type="number" value="${trip.miles || ''}" min="0" step="0.1" required
onchange="updateModalTrip(${index}, 'miles', parseFloat(this.value) || 0)"
placeholder="e.g., 15">
</div>
<div class="form-group">
<label>Passengers*</label>
<input type="number" value="${trip.passengers !== undefined ? trip.passengers : ''}" min="0" required
onchange="updateModalTrip(${index}, 'passengers', this.value === '' ? 0 : parseInt(this.value))"
placeholder="e.g., 50">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label>Start Time*</label>
<input type="time" value="${trip.startTime}" required
onchange="updateModalTrip(${index}, 'startTime', this.value)">
</div>
<div class="form-group">
<label>End Time*</label>
<input type="time" value="${trip.endTime}" required
onchange="updateModalTrip(${index}, 'endTime', this.value)">
</div>
</div>
<div class="form-group">
<label>Notes</label>
<textarea rows="2" onchange="updateModalTrip(${index}, 'notes', this.value)"
placeholder="Optional notes about this trip...">${trip.notes || ''}</textarea>
</div>
</div>
`).join('');
// Add the "Add Another Trip" button at the bottom
const addButtonHTML = `
<div style="text-align: center; margin-top: 20px;">
<button type="button" class="btn btn-secondary" onclick="addTripToModal()">
+ Add Another Trip
</button>
</div>
`;
container.innerHTML = tripsHTML + addButtonHTML;
}
function updateModalTrip(index, field, value) {
modalTrips[index][field] = value;
}
function closeModal() {
document.getElementById('busScheduleModal').style.display = 'none';
modalTrips = [];
currentEditingScheduleIndex = null;
}
function saveBusSchedule() {
const name = document.getElementById('busScheduleName').value.trim();
if (!name) {
alert('Please enter a bus name.');
return;
}
// Validate all trips have required fields
for (let i = 0; i < modalTrips.length; i++) {
const trip = modalTrips[i];
if (!trip.miles || trip.miles <= 0) {
alert(`Trip ${i + 1}: Please enter a valid distance.`);
return;
}
if (trip.passengers === undefined || trip.passengers === null || trip.passengers < 0) {
alert(`Trip ${i + 1}: Please enter a valid passenger count (0 or more).`);
return;
}
if (!trip.startTime || !trip.endTime) {
alert(`Trip ${i + 1}: Please enter start and end times.`);
return;
}
}
// Validate at least one trip has passengers
const hasPassengers = modalTrips.some(t => t.passengers > 0);
if (!hasPassengers) {
alert('At least one trip must have passengers (greater than 0) to justify the route.');
return;
}
// Validate at least one trip returns to chargers
const hasChargerReturn = modalTrips.some(t => t.returnToDepot !== false);
if (!hasChargerReturn) {
alert('At least one trip must have "Can charge at this location" checked to ensure the bus can recharge.');
return;
}
const schedule = {
name,
trips: modalTrips.map(t => ({...t})), // Clone trips
selectedBus: null,
selectedCharger: null
};
if (currentEditingScheduleIndex !== null) {
editBusSchedule(currentEditingScheduleIndex, schedule);
} else {
addBusSchedule(schedule);
}
closeModal();
}
// ==========================
// Climate Display Helper
// ==========================
function updateClimateDisplay() {
const infoDiv = document.getElementById('depotInfo');
if (depotClimate) {
infoDiv.style.display = 'flex';
document.getElementById('climateZone').textContent =
depotClimate.isColdClimate ? 'Cold (Below Freezing)' : 'Moderate';
document.getElementById('winterDerating').textContent =
depotClimate.isColdClimate ? '30%' : '0%';
} else {
infoDiv.style.display = 'none';
}
}
// ==========================
// Trip Scheduling & Optimization
// ==========================
function addBusGroup() {
const group = {
id: nextBusGroupId++,
name: `Bus ${busGroups.length + 1}`,
trips: [],
selectedBus: null,
selectedCharger: null
};
busGroups.push(group);
displayBusGroups();
}
function autoOptimizeBusGroups() {
if (trips.length === 0) return;
// Sort trips by start time
const sortedTrips = trips.map((t, idx) => ({ ...t, originalIndex: idx }))
.sort((a, b) => timeToMinutes(a.startTime) - timeToMinutes(b.startTime));
busGroups = [];
nextBusGroupId = 1;
// Greedy algorithm: assign each trip to the first available bus
for (const trip of sortedTrips) {
let assigned = false;
// Try to assign to existing bus group
for (const group of busGroups) {
if (canAddTripToGroup(group, trip)) {
group.assignedTripIndices.push(trip.originalIndex);
assigned = true;
break;
}
}
// If can't fit in any existing group, create new bus