-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1046 lines (964 loc) · 42 KB
/
script.js
File metadata and controls
1046 lines (964 loc) · 42 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
// Initialize data from localStorage with error handling
let vehicles = [];
try {
const storedVehicles = localStorage.getItem('vehicles');
if (storedVehicles) {
vehicles = JSON.parse(storedVehicles);
if (!Array.isArray(vehicles)) {
console.error('Stored vehicles is not an array:', vehicles);
vehicles = [];
}
}
} catch (e) {
console.error('Error parsing localStorage vehicles:', e);
vehicles = [];
}
let selectedVehicleId = localStorage.getItem('selectedVehicleId') || null;
// Function to repair vehicles data
function repairVehiclesData() {
try {
vehicles = vehicles.map((vehicle, index) => {
if (!vehicle || typeof vehicle !== 'object') {
console.warn(`Invalid vehicle at index ${index}, skipping`);
return null;
}
if (!vehicle.id) {
console.warn(`Vehicle at index ${index} missing ID, generating new one`);
vehicle.id = generateUUID();
}
return {
id: vehicle.id,
name: vehicle.name || `Vehicle ${index + 1}`,
notes: vehicle.notes || '',
currentInfo: vehicle.currentInfo || { date: new Date().toISOString().split('T')[0], mileage: 0 },
completedServices: Array.isArray(vehicle.completedServices) ? vehicle.completedServices : [],
pendingServices: Array.isArray(vehicle.pendingServices) ? vehicle.pendingServices : []
};
}).filter(v => v !== null);
saveData();
console.log('Repaired vehicles:', vehicles);
renderVehicleList(); // Refresh list after repair
} catch (e) {
console.error('Error in repairVehiclesData:', e);
}
}
// Generate a simple UUID for vehicle IDs
function generateUUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Function to save data to localStorage
function saveData() {
try {
localStorage.setItem('vehicles', JSON.stringify(vehicles));
localStorage.setItem('selectedVehicleId', selectedVehicleId);
} catch (e) {
console.error('Error saving to localStorage:', e);
}
}
// Function to get the selected vehicle
function getSelectedVehicle() {
return vehicles.find(v => v.id === selectedVehicleId) || null;
}
// Function to show snackbar
function showSnackbar(message) {
try {
const snackbar = document.getElementById('snackbar');
if (snackbar) {
snackbar.textContent = message;
snackbar.classList.add('show');
setTimeout(() => snackbar.classList.remove('show'), 3000);
} else {
console.warn('Snackbar element not found');
}
} catch (e) {
console.error('Error in showSnackbar:', e);
}
}
// Function to toggle dark mode
function toggleDarkMode() {
try {
document.body.classList.toggle('dark');
localStorage.setItem('theme', document.body.classList.contains('dark') ? 'dark' : 'light');
toggleHamburgerMenu(); // Close menu after action
} catch (e) {
console.error('Error in toggleDarkMode:', e);
}
}
// Function to toggle hamburger menu
function toggleHamburgerMenu() {
try {
const menu = document.getElementById('hamburgerMenu');
if (menu) {
menu.style.display = menu.style.display === 'flex' ? 'none' : 'flex';
menu.classList.toggle('show');
}
} catch (e) {
console.error('Error in toggleHamburgerMenu:', e);
}
}
// Function to backup localStorage data
async function backupData() {
try {
const data = JSON.stringify(localStorage);
const blob = new Blob([data], { type: 'application/json' });
// Generate filename with date and time (e.g., CSART-backup-2025-04-26-12-57-00.json)
const now = new Date();
const timestamp = now.getFullYear() + '-' +
String(now.getMonth() + 1).padStart(2, '0') + '-' +
String(now.getDate()).padStart(2, '0') + '-' +
String(now.getHours()).padStart(2, '0') + '-' +
String(now.getMinutes()).padStart(2, '0') + '-' +
String(now.getSeconds()).padStart(2, '0');
const filename = `CSART-backup-${timestamp}.json`;
// Check if running on desktop (basic heuristic: screen width > 600px)
const isDesktop = window.innerWidth > 600;
if (isDesktop && window.showSaveFilePicker) {
// Use File System Access API for desktop save dialog
const fileHandle = await window.showSaveFilePicker({
suggestedName: filename,
types: [{
description: 'JSON Files',
accept: { 'application/json': ['.json'] }
}]
});
const writable = await fileHandle.createWritable();
await writable.write(blob);
await writable.close();
} else {
// Fallback for mobile or unsupported browsers
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
showSnackbar('Data backed up');
toggleHamburgerMenu(); // Close menu after action
} catch (e) {
console.error('Error in backupData:', e);
showSnackbar('Backup failed');
}
}
// Function to restore localStorage data
function restoreData(event) {
try {
const file = event.target.files[0];
if (!file) {
showSnackbar('No file selected');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const data = JSON.parse(e.target.result);
// Validate data
if (!data.vehicles || !data.selectedVehicleId || !data.theme) {
throw new Error('Invalid backup file: missing required keys');
}
// Clear existing localStorage
localStorage.clear();
// Restore new data
Object.entries(data).forEach(([key, value]) => localStorage.setItem(key, value));
// Repair and refresh
vehicles = JSON.parse(localStorage.getItem('vehicles') || '[]');
selectedVehicleId = localStorage.getItem('selectedVehicleId') || null;
repairVehiclesData();
renderPage();
showSnackbar('Data restored');
toggleHamburgerMenu(); // Close menu after action
} catch (err) {
console.error('Error restoring data:', err);
showSnackbar('Invalid backup file');
}
};
reader.readAsText(file);
} catch (e) {
console.error('Error in restoreData:', e);
showSnackbar('Restore failed');
}
}
// Function to sync date with time server
async function syncDateWithTimeServer(vehicle) {
try {
// Set a timeout for the fetch request (5 seconds)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch('http://worldtimeapi.org/api/timezone/Etc/UTC', {
signal: controller.signal
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
const serverDate = new Date(data.datetime).toISOString().split('T')[0];
// Update vehicle's currentInfo.date if unset or significantly outdated
if (!vehicle.currentInfo.date || Math.abs(new Date(vehicle.currentInfo.date) - new Date(serverDate)) > 24 * 60 * 60 * 1000) {
vehicle.currentInfo.date = serverDate;
saveData();
console.log('Synced date with time server:', serverDate);
}
} catch (e) {
console.warn('Failed to sync date with time server:', e);
// Fallback to device time if unset
if (!vehicle.currentInfo.date) {
vehicle.currentInfo.date = new Date().toISOString().split('T')[0];
saveData();
console.log('Set date to device time:', vehicle.currentInfo.date);
}
}
}
// Client-side routing
function navigateTo(path) {
try {
console.log('Navigating to:', path);
if (path.startsWith('/vehicle/') && !path.split('/vehicle/')[1]) {
console.error('Invalid vehicle ID in path:', path);
showSnackbar('Cannot navigate: Invalid vehicle ID');
return;
}
// Check if running on file:// protocol
if (window.location.protocol === 'file:') {
console.warn('Using file:// fallback navigation (history.pushState not supported)');
// Update selectedVehicleId and render directly
if (path.startsWith('/vehicle/')) {
selectedVehicleId = path.split('/vehicle/')[1];
} else {
selectedVehicleId = null;
}
renderPage();
} else {
// Normal navigation for http:// or https://
history.pushState({}, '', path);
renderPage();
}
} catch (e) {
console.error('Error in navigateTo:', e);
if (e.name === 'SecurityError' && window.location.protocol === 'file:') {
showSnackbar('Navigation failed: Run the app on a local server (e.g., http://localhost) to enable full navigation');
} else {
showSnackbar('Navigation failed');
}
}
}
window.addEventListener('popstate', () => {
console.log('Popstate event triggered');
renderPage();
});
function renderPage() {
try {
let path = window.location.pathname;
console.log('Rendering page for path:', path);
const mainPage = document.getElementById('mainPage');
const detailPage = document.getElementById('detailPage');
if (!mainPage || !detailPage) {
console.error('Main or detail page elements not found');
return;
}
// Normalize path for /carsart
if (path.startsWith('/carsart')) {
path = path.replace('/carsart', '');
}
if (path === '/' || path === '') {
mainPage.style.display = 'block';
detailPage.style.display = 'none';
renderVehicleList();
} else if (path.startsWith('/vehicle/')) {
selectedVehicleId = path.split('/vehicle/')[1];
mainPage.style.display = 'none';
detailPage.style.display = 'block';
renderSelectedVehicle();
}
} catch (e) {
console.error('Error in renderPage:', e);
}
}
// Function to open vehicle modal
function openVehicleModal(index = -1) {
try {
const modal = document.getElementById('vehicleModal');
const submitButton = document.getElementById('vehicleSubmit');
const cancelButton = document.getElementById('vehicleCancel');
const title = document.getElementById('vehicleModalTitle');
if (!modal || !submitButton || !cancelButton || !title) {
console.error('Modal elements not found');
return;
}
if (index >= 0) {
const vehicle = vehicles[index];
document.getElementById('vehicleName').value = vehicle.name;
document.getElementById('vehicleNotes').value = vehicle.notes;
submitButton.textContent = 'Update Vehicle';
submitButton.setAttribute('data-editing', 'true');
submitButton.setAttribute('data-index', index);
cancelButton.style.display = 'block';
title.textContent = 'Edit Vehicle';
} else {
document.getElementById('vehicleName').value = '';
document.getElementById('vehicleNotes').value = '';
submitButton.textContent = 'Add Vehicle';
submitButton.setAttribute('data-editing', 'false');
submitButton.setAttribute('data-index', '-1');
cancelButton.style.display = 'none';
title.textContent = 'Add Vehicle';
}
modal.style.display = 'flex';
} catch (e) {
console.error('Error in openVehicleModal:', e);
}
}
// Function to close vehicle modal
function closeVehicleModal() {
try {
const modal = document.getElementById('vehicleModal');
if (modal) {
modal.style.display = 'none';
document.getElementById('vehicleName').value = '';
document.getElementById('vehicleNotes').value = '';
}
} catch (e) {
console.error('Error in closeVehicleModal:', e);
}
}
// Function to submit a vehicle (add or update)
function submitVehicle() {
try {
const submitButton = document.getElementById('vehicleSubmit');
const isEditing = submitButton.getAttribute('data-editing') === 'true';
const index = parseInt(submitButton.getAttribute('data-index'));
const vehicle = {
name: document.getElementById('vehicleName').value,
notes: document.getElementById('vehicleNotes').value
};
if (vehicle.name) {
if (isEditing) {
vehicles[index].name = vehicle.name;
vehicles[index].notes = vehicle.notes;
saveData();
renderVehicleList();
if (selectedVehicleId === vehicles[index].id) {
renderSelectedVehicle();
}
showSnackbar('Vehicle updated');
} else {
vehicle.id = generateUUID();
vehicle.currentInfo = { date: new Date().toISOString().split('T')[0], mileage: 0 };
vehicle.completedServices = [];
vehicle.pendingServices = [];
vehicles.push(vehicle);
saveData();
renderVehicleList();
showSnackbar('Vehicle added');
}
closeVehicleModal();
} else {
alert('Please enter a vehicle name.');
}
} catch (e) {
console.error('Error in submitVehicle:', e);
}
}
// Function to edit a vehicle
function editVehicle(index) {
try {
openVehicleModal(index);
} catch (e) {
console.error('Error in editVehicle:', e);
}
}
// Function to delete a vehicle
function deleteVehicle(index) {
try {
if (confirm('Are you sure you want to delete this vehicle and all its service records?')) {
const vehicleId = vehicles[index].id;
vehicles.splice(index, 1);
if (selectedVehicleId === vehicleId) {
selectedVehicleId = vehicles.length > 0 ? vehicles[0].id : null;
navigateTo('/');
}
saveData();
renderVehicleList();
showSnackbar('Vehicle deleted');
}
} catch (e) {
console.error('Error in deleteVehicle:', e);
}
}
// Function to render vehicle list
function renderVehicleList() {
try {
console.log('Rendering vehicle list, vehicles:', vehicles);
let vehicleList = document.getElementById('vehicleList');
if (!vehicleList) {
console.warn('vehicleList element not found, retrying...');
setTimeout(renderVehicleList, 100); // Retry after 100ms
return;
}
vehicleList.innerHTML = '';
if (vehicles.length === 0) {
console.log('No vehicles, showing "No vehicles added yet"');
vehicleList.innerHTML = '<p class="no-vehicle">No vehicles added yet.</p>';
return;
}
vehicles.forEach((vehicle, index) => {
if (!vehicle.id || !vehicle.name) {
console.error('Vehicle missing ID or name:', vehicle);
return;
}
console.log('Rendering vehicle:', vehicle.id, vehicle.name);
const card = document.createElement('div');
card.className = 'vehicle-card';
card.setAttribute('onclick', `navigateTo('/vehicle/${vehicle.id}')`);
card.addEventListener('click', (e) => {
console.log('Vehicle card clicked:', vehicle.id);
navigateTo(`/vehicle/${vehicle.id}`);
});
const infoDiv = document.createElement('div');
const nameP = document.createElement('p');
nameP.textContent = vehicle.name;
infoDiv.appendChild(nameP);
if (vehicle.notes) {
const notesP = document.createElement('p');
notesP.className = 'notes';
notesP.textContent = vehicle.notes;
infoDiv.appendChild(notesP);
}
const buttonsDiv = document.createElement('div');
const editBtn = document.createElement('button');
editBtn.className = 'vehicle-btn edit';
editBtn.innerHTML = '<span class="material-icons">edit</span>';
editBtn.addEventListener('click', (e) => {
e.stopPropagation();
editVehicle(index);
});
buttonsDiv.appendChild(editBtn);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'vehicle-btn delete';
deleteBtn.innerHTML = '<span class="material-icons">delete</span>';
deleteBtn.addEventListener('click', (e) => {
e.stopPropagation();
deleteVehicle(index);
});
buttonsDiv.appendChild(deleteBtn);
card.appendChild(infoDiv);
card.appendChild(buttonsDiv);
vehicleList.appendChild(card);
});
} catch (e) {
console.error('Error in renderVehicleList:', e);
}
}
// Function to render selected vehicle’s data
async function renderSelectedVehicle() {
try {
const vehicle = getSelectedVehicle();
if (vehicle) {
// Sync date with time server
await syncDateWithTimeServer(vehicle);
document.getElementById('detailVehicleName').textContent = vehicle.name;
document.getElementById('detailVehicleNotes').textContent = vehicle.notes || '';
document.getElementById('currentDateDisplay').textContent = vehicle.currentInfo.date;
document.getElementById('currentMileageDisplay').textContent = vehicle.currentInfo.mileage;
renderServicesTable();
} else {
console.error('No vehicle found for ID:', selectedVehicleId);
showSnackbar('Vehicle not found');
navigateTo('/');
}
} catch (e) {
console.error('Error in renderSelectedVehicle:', e);
}
}
// Current Info Modal functions
function openCurrentInfoModal() {
try {
const modal = document.getElementById('currentInfoModal');
const vehicle = getSelectedVehicle();
if (!modal || !vehicle) {
console.error('Current info modal or vehicle not found');
return;
}
document.getElementById('modalCurrentDate').value = vehicle.currentInfo.date;
document.getElementById('modalCurrentMileage').value = vehicle.currentInfo.mileage;
modal.style.display = 'flex';
} catch (e) {
console.error('Error in openCurrentInfoModal:', e);
}
}
function closeCurrentInfoModal() {
try {
const modal = document.getElementById('currentInfoModal');
if (modal) {
modal.style.display = 'none';
document.getElementById('modalCurrentDate').value = '';
document.getElementById('modalCurrentMileage').value = '';
}
} catch (e) {
console.error('Error in closeCurrentInfoModal:', e);
}
}
function submitCurrentInfo() {
try {
const vehicle = getSelectedVehicle();
if (vehicle) {
vehicle.currentInfo.date = document.getElementById('modalCurrentDate').value;
vehicle.currentInfo.mileage = parseInt(document.getElementById('modalCurrentMileage').value) || 0;
if (!vehicle.currentInfo.date) {
alert('Please enter a valid date.');
return;
}
saveData();
renderSelectedVehicle();
showSnackbar('Current information updated');
closeCurrentInfoModal();
}
} catch (e) {
console.error('Error in submitCurrentInfo:', e);
}
}
// Service modal functions
function openServiceModal(type = null, index = -1) {
try {
const modal = document.getElementById('serviceModal');
const formContainer = document.getElementById('serviceFormContainer');
if (!modal || !formContainer) {
console.error('Service modal elements not found');
return;
}
// Set radio button
const selectedType = type || 'pending';
document.querySelector(`input[name="serviceType"][value="${selectedType}"]`).checked = true;
// Load form
renderServiceForm(selectedType, index);
// Set modal state for editing
const submitButton = formContainer.querySelector('#serviceSubmit');
if (index >= 0) {
submitButton.textContent = 'Update Service';
submitButton.setAttribute('data-editing', 'true');
submitButton.setAttribute('data-index', index);
formContainer.querySelector('#serviceCancel').style.display = 'block';
} else {
submitButton.textContent = 'Add Service';
submitButton.setAttribute('data-editing', 'false');
submitButton.setAttribute('data-index', '-1');
formContainer.querySelector('#serviceCancel').style.display = 'none';
}
modal.style.display = 'flex';
} catch (e) {
console.error('Error in openServiceModal:', e);
}
}
function closeServiceModal() {
try {
const modal = document.getElementById('serviceModal');
if (modal) {
modal.style.display = 'none';
document.getElementById('serviceFormContainer').innerHTML = '';
document.querySelector('input[name="serviceType"][value="pending"]').checked = true;
}
} catch (e) {
console.error('Error in closeServiceModal:', e);
}
}
function handleServiceTypeChange(type) {
try {
const formContainer = document.getElementById('serviceFormContainer');
const isEditing = formContainer.querySelector('#serviceSubmit')?.getAttribute('data-editing') === 'true';
const index = parseInt(formContainer.querySelector('#serviceSubmit')?.getAttribute('data-index') || '-1');
renderServiceForm(type, isEditing ? index : -1);
} catch (e) {
console.error('Error in handleServiceTypeChange:', e);
}
}
function renderServiceForm(type, index) {
try {
const formContainer = document.getElementById('serviceFormContainer');
if (!formContainer) return;
const vehicle = getSelectedVehicle();
if (!vehicle) return;
let formHTML = '';
if (type === 'completed') {
const service = index >= 0 ? vehicle.completedServices[index] : {};
formHTML = `
<div class="form-group">
<input type="date" id="serviceDate" class="material-input" value="${service.date || ''}" required>
<label for="serviceDate">Date</label>
</div>
<div class="form-group">
<input type="text" id="serviceDescription" class="material-input" placeholder=" " value="${service.description || ''}" required>
<label for="serviceDescription">Description</label>
</div>
<div class="form-group">
<input type="text" id="serviceShop" class="material-input" placeholder=" " value="${service.shop || ''}">
<label for="serviceShop">Shop</label>
</div>
<div class="form-group">
<input type="number" id="serviceCost" class="material-input" min="0" step="0.01" placeholder=" " value="${service.cost || ''}">
<label for="serviceCost">Cost (₦)</label>
</div>
<div class="form-group">
<input type="number" id="serviceMileage" class="material-input" min="0" placeholder=" " value="${service.mileage || ''}">
<label for="serviceMileage">Mileage</label>
</div>
<div class="form-group">
<input type="text" id="serviceReceipt" class="material-input" placeholder=" " value="${service.receipt || ''}">
<label for="serviceReceipt">Receipt #</label>
</div>
<div class="form-buttons">
<button class="material-button" id="serviceSubmit" data-editing="false" data-index="-1" onclick="submitService('completed')">Add Service</button>
<button class="material-button cancel-btn" id="serviceCancel" onclick="cancelEdit('completed')" style="display: none;">Cancel</button>
</div>
`;
} else {
const service = index >= 0 ? vehicle.pendingServices[index] : {};
formHTML = `
<div class="form-group">
<input type="text" id="serviceDescription" class="material-input" placeholder=" " value="${service.description || ''}" required>
<label for="serviceDescription">Description</label>
</div>
<div class="form-group">
<input type="date" id="serviceDueDate" class="material-input" placeholder=" " value="${service.dueDate || ''}">
<label for="serviceDueDate">Due Date</label>
</div>
<div class="form-group">
<input type="number" id="serviceDueMileage" class="material-input" min="0" placeholder=" " value="${service.dueMileage || ''}">
<label for="serviceDueMileage">Due Mileage</label>
</div>
<div class="form-group">
<select id="servicePriority" class="material-input">
<option value="High" ${service.priority === 'High' ? 'selected' : ''}>High</option>
<option value="Medium" ${service.priority === 'Medium' ? 'selected' : ''}>Medium</option>
<option value="Low" ${service.priority === 'Low' ? 'selected' : ''}>Low</option>
</select>
<label for="servicePriority">Priority</label>
</div>
<div class="form-group">
<input type="text" id="serviceNotes" class="material-input" placeholder=" " value="${service.notes || ''}">
<label for="serviceNotes">Notes</label>
</div>
<div class="form-buttons">
<button class="material-button" id="serviceSubmit" data-editing="false" data-index="-1" onclick="submitService('pending')">Add Service</button>
<button class="material-button cancel-btn" id="serviceCancel" onclick="cancelEdit('pending')" style="display: none;">Cancel</button>
</div>
`;
}
formContainer.innerHTML = formHTML;
// Restore editing state
if (index >= 0) {
const submitButton = formContainer.querySelector('#serviceSubmit');
submitButton.textContent = 'Update Service';
submitButton.setAttribute('data-editing', 'true');
submitButton.setAttribute('data-index', index);
formContainer.querySelector('#serviceCancel').style.display = 'block';
}
} catch (e) {
console.error('Error in renderServiceForm:', e);
}
}
// Function to clear form fields
function clearServiceForm(type) {
try {
if (type === 'completed') {
document.getElementById('serviceDate').value = '';
document.getElementById('serviceDescription').value = '';
document.getElementById('serviceShop').value = '';
document.getElementById('serviceCost').value = '';
document.getElementById('serviceMileage').value = '';
document.getElementById('serviceReceipt').value = '';
} else {
document.getElementById('serviceDescription').value = '';
document.getElementById('serviceDueDate').value = '';
document.getElementById('serviceDueMileage').value = '';
document.getElementById('servicePriority').value = 'High';
document.getElementById('serviceNotes').value = '';
}
} catch (e) {
console.error('Error in clearServiceForm:', e);
}
}
// Function to handle service submission
function submitService(type) {
try {
const vehicle = getSelectedVehicle();
if (!vehicle) return;
const submitButton = document.getElementById('serviceSubmit');
const isEditing = submitButton.getAttribute('data-editing') === 'true';
const index = parseInt(submitButton.getAttribute('data-index'));
if (type === 'completed') {
const service = {
date: document.getElementById('serviceDate').value,
description: document.getElementById('serviceDescription').value,
shop: document.getElementById('serviceShop').value,
cost: parseFloat(document.getElementById('serviceCost').value) || 0,
mileage: parseInt(document.getElementById('serviceMileage').value) || 0,
receipt: document.getElementById('serviceReceipt').value
};
if (service.description && service.date) {
if (isEditing) {
vehicle.completedServices[index] = service;
showSnackbar('Completed service updated');
} else {
vehicle.completedServices.push(service);
showSnackbar('Completed service added');
}
saveData();
renderServicesTable();
clearServiceForm('completed');
closeServiceModal();
} else {
alert('Please enter at least a date and description.');
}
} else {
const service = {
description: document.getElementById('serviceDescription').value,
dueDate: document.getElementById('serviceDueDate').value,
dueMileage: parseInt(document.getElementById('serviceDueMileage').value) || 0,
priority: document.getElementById('servicePriority').value,
notes: document.getElementById('serviceNotes').value
};
if (service.description) {
if (isEditing) {
vehicle.pendingServices[index] = service;
showSnackbar('Pending service updated');
} else {
vehicle.pendingServices.push(service);
showSnackbar('Pending service added');
}
saveData();
renderServicesTable();
clearServiceForm('pending');
closeServiceModal();
} else {
alert('Please enter a description.');
}
}
} catch (e) {
console.error('Error in submitService:', e);
}
}
// Function to edit a service
function editService(type, index) {
try {
openServiceModal(type, index);
} catch (e) {
console.error('Error in editService:', e);
}
}
// Function to delete a service
function deleteService(type, index) {
try {
const vehicle = getSelectedVehicle();
if (!vehicle) return;
if (confirm('Are you sure you want to delete this service?')) {
if (type === 'completed') {
vehicle.completedServices.splice(index, 1);
showSnackbar('Completed service deleted');
} else {
vehicle.pendingServices.splice(index, 1);
showSnackbar('Pending service deleted');
}
saveData();
renderServicesTable();
}
} catch (e) {
console.error('Error in deleteService:', e);
}
}
// Function to cancel editing
function cancelEdit(type) {
try {
clearServiceForm(type);
closeServiceModal();
} catch (e) {
console.error('Error in cancelEdit:', e);
}
}
// Function to open service detail modal
function openServiceDetailModal(type, index) {
try {
const vehicle = getSelectedVehicle();
if (!vehicle) return;
const modal = document.getElementById('serviceDetailModal');
const list = document.getElementById('serviceDetailList');
if (!modal || !list) {
console.error('Service detail modal elements not found');
return;
}
list.innerHTML = '';
let service;
if (type === 'completed') {
service = vehicle.completedServices[index];
list.innerHTML = `
<li><strong>Type:</strong> Completed</li>
<li><strong>Description:</strong> ${service.description || '-'}</li>
<li><strong>Date:</strong> ${service.date || '-'}</li>
<li><strong>Mileage:</strong> ${service.mileage || '-'}</li>
<li><strong>Cost:</strong> ₦${(service.cost || 0).toFixed(2)}</li>
<li><strong>Shop:</strong> ${service.shop || '-'}</li>
<li><strong>Receipt #:</strong> ${service.receipt || '-'}</li>
`;
} else {
service = vehicle.pendingServices[index];
list.innerHTML = `
<li><strong>Type:</strong> Pending</li>
<li><strong>Description:</strong> ${service.description || '-'}</li>
<li><strong>Due Date:</strong> ${service.dueDate || '-'}</li>
<li><strong>Due Mileage:</strong> ${service.dueMileage || '-'}</li>
<li><strong>Priority:</strong> ${service.priority || '-'}</li>
<li><strong>Notes:</strong> ${service.notes || '-'}</li>
<li><strong>Is Due:</strong> ${isServiceDue(service) ? 'Yes' : 'No'}</li>
`;
}
modal.style.display = 'flex';
} catch (e) {
console.error('Error in openServiceDetailModal:', e);
}
}
// Function to close service detail modal
function closeServiceDetailModal() {
try {
const modal = document.getElementById('serviceDetailModal');
if (modal) {
modal.style.display = 'none';
document.getElementById('serviceDetailList').innerHTML = '';
}
} catch (e) {
console.error('Error in closeServiceDetailModal:', e);
}
}
// Function to check if a pending service is due
function isServiceDue(service) {
try {
const vehicle = getSelectedVehicle();
if (!vehicle) return false;
const today = new Date(vehicle.currentInfo.date);
const dueDate = service.dueDate ? new Date(service.dueDate) : null;
const currentMileage = vehicle.currentInfo.mileage;
const dueMileage = service.dueMileage;
return (dueDate && dueDate <= today) || (dueMileage && dueMileage <= currentMileage);
} catch (e) {
console.error('Error in isServiceDue:', e);
return false;
}
}
// Function to export table to CSV
function exportToCSV(tableId, filename) {
try {
const table = document.getElementById(tableId);
const rows = Array.from(table.querySelectorAll('tr'));
const csv = rows.map(row =>
Array.from(row.querySelectorAll('th, td'))
.filter(cell => !cell.querySelector('button'))
.map(cell => {
if (cell.textContent.startsWith('₦')) {
return `"${cell.textContent.replace('₦', '')}"`;
}
return `"${cell.textContent.replace(/Pending|Completed/, '').trim()}"`;
})
.join(',')
).join('\n');
const blob = new Blob([csv], { type: 'text/csv' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
showSnackbar(`Exported ${filename}`);
} catch (e) {
console.error('Error in exportToCSV:', e);
}
}
// Function to render services table
function renderServicesTable() {
try {
const vehicle = getSelectedVehicle();
if (!vehicle) return;
const services = [
...vehicle.pendingServices.map((s, index) => ({ ...s, type: 'pending', index })),
...vehicle.completedServices.map((s, index) => ({ ...s, type: 'completed', index }))
];
// Sort: Pending first, then by priority (High=1, Medium=2, Low=3), then by date descending for Completed
services.sort((a, b) => {
if (a.type !== b.type) {
return a.type === 'pending' ? -1 : 1;
}
if (a.type === 'pending') {
const priorityOrder = { High: 1, Medium: 2, Low: 3 };
return priorityOrder[a.priority] - priorityOrder[b.priority];
}
return new Date(b.date) - new Date(a.date);
});
const servicesBody = document.getElementById('detailServicesBody');
servicesBody.innerHTML = '';
services.forEach(service => {
const isDue = service.type === 'pending' && isServiceDue(service);
const priorityClass = service.type === 'pending' ?
(service.priority === 'High' ? 'priority-high' :
service.priority === 'Medium' ? 'priority-medium' : 'priority-low') : '';
const priorityTagClass = service.type === 'pending' ?
(service.priority === 'High' ? 'high' :
service.priority === 'Medium' ? 'medium' : 'low') : '';
const row = document.createElement('tr');
if (isDue && !priorityClass) row.classList.add('due');
if (priorityClass) row.classList.add(priorityClass);
row.setAttribute('aria-label', `View details for ${service.description}`);
row.innerHTML = `
<td>
${service.type === 'pending' ?
`<span class="pending-tag ${priorityTagClass}">Pending</span>` :
`<span class="completed-tag">Completed</span>`}
</td>
<td>${service.description}</td>
<td>${service.type === 'pending' ? (service.dueDate || '') : (service.date || '')}</td>
<td>${service.type === 'pending' ? (service.dueMileage || '') : (service.mileage || '')}</td>
<td>${service.type === 'pending' ? (service.priority || '') : ''}</td>