-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmanager.js
More file actions
2340 lines (1983 loc) · 91.6 KB
/
Copy pathmanager.js
File metadata and controls
2340 lines (1983 loc) · 91.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
import { auth, db } from './firebase-config.js';
import { onAuthStateChanged, signOut } from "https://www.gstatic.com/firebasejs/12.6.0/firebase-auth.js";
import { collection, getDocs, doc, getDoc, updateDoc, arrayUnion, arrayRemove, addDoc, deleteDoc, Timestamp } from "https://www.gstatic.com/firebasejs/12.6.0/firebase-firestore.js";
import { getPageUrl, getApiUrl } from './utils.js';
import { initialize as initializeWhenIWork, getScheduledHours, createWIWShift, deleteWIWShift } from './wheniwork.js';
import { fadeIn, fadeInStagger } from './animations.js';
import { checkAndShowVersionPopup } from './version-check.js';
import { showReportDialog } from './report-utils.js';
let currentUser = null;
let allUsers = [];
let allTasks = [];
let selectedUser = null;
let selectedTask = null;
let budgetData = null;
let quarterDates = null; // Store DePaul quarter dates
// Task filter state
let taskFilters = {
dueFrom: null,
dueTo: null,
hoursMin: null,
hoursMax: null,
locations: ['IRL 1', 'IRL 2', 'Remote', 'custom'],
categories: ['Workshop', 'Maintenance', 'Project', 'Media', 'Event', 'Other'],
priorityOnly: false,
skills: []
};
// Available skills from skills.txt
const AVAILABLE_SKILLS = [
"Textiles",
"Screen Printing",
"3D Printer (FDM)",
"3D Printer (Resin)",
"Laser Cutter",
"Wood Shop",
"Programming",
"Mechanical",
"Electronics",
"3D Modeling",
"Graphic Design",
"Photo/Video",
"CNC"
];
// Check auth state and redirect if not logged in or not a manager
onAuthStateChanged(auth, async (user) => {
if (user) {
const userDoc = await getDoc(doc(db, "users", user.uid));
if (userDoc.exists()) {
currentUser = {
id: user.uid,
...userDoc.data()
};
// Check if user is a manager
if (currentUser.role !== "manager") {
alert("Access denied. Manager privileges required.");
window.location.href = getPageUrl("staff");
return;
}
console.log("Logged in as manager:", currentUser.fullName);
// Load data
await loadAllUsers();
await loadAllTasks();
await loadBudgetData();
await loadQuarterDates();
// Render team list
renderTeamList();
// Render tasks tab
renderTasksTab();
// Setup logout button
setupLogoutButton();
// Setup report button
setupReportButton();
// Setup settings button
setupSettingsButton();
// Setup tab switching
setupTabs();
// Setup task dialog
setupTaskDialog();
// Setup task filters
setupTaskFilters();
// Setup hours calculation mode switch
setupHoursCalculationSwitch();
// Setup edit budget button (hour budget dialog)
setupEditBudgetButton();
// Render hours
await renderHours();
// Check and show version popup if needed
await checkAndShowVersionPopup(currentUser);
}
} else {
window.location.href = getPageUrl("signin");
}
});
// Setup logout button
function setupLogoutButton() {
const logoutButton = document.querySelector('button[style*="rgb(255, 93, 93)"]');
if (logoutButton) {
logoutButton.addEventListener('click', async () => {
try {
await signOut(auth);
} catch (error) {
console.error("Error signing out:", error);
alert("Error signing out: " + error.message);
}
});
}
}
// Setup report button functionality
function setupReportButton() {
const reportButton = document.getElementById('reportButton');
if (reportButton) {
reportButton.addEventListener('click', () => {
showReportDialog(currentUser);
});
}
}
// Setup settings button functionality
function setupSettingsButton() {
const settingsButtons = document.querySelectorAll('.circle-button');
settingsButtons.forEach(button => {
// Find the cog button specifically
if (button.innerHTML.includes('fa-cog')) {
button.addEventListener('click', () => {
const settingsDialog = document.getElementById('settingsDialog');
if (settingsDialog) {
settingsDialog.showModal();
}
});
}
});
// Setup close button for settings dialog
const settingsDialog = document.getElementById('settingsDialog');
if (settingsDialog) {
const closeButton = settingsDialog.querySelector('button[aria-label="Close"]');
if (closeButton) {
closeButton.addEventListener('click', () => {
settingsDialog.close();
});
}
}
}
// Setup tab switching functionality
function setupTabs() {
const tabButtons = document.querySelectorAll('.tab-button');
const tabContents = document.querySelectorAll('.tab-content');
tabButtons.forEach(button => {
button.addEventListener('click', () => {
const targetTab = button.getAttribute('data-tab');
// Remove active class from all buttons and contents
tabButtons.forEach(btn => btn.classList.remove('active'));
tabContents.forEach(content => content.classList.remove('active'));
// Add active class to clicked button and corresponding content
button.classList.add('active');
document.getElementById(targetTab).classList.add('active');
});
});
}
// Load all users from Firestore
async function loadAllUsers() {
try {
console.log("Loading users from Firestore...");
const usersCollection = collection(db, "users");
const usersSnapshot = await getDocs(usersCollection);
allUsers = usersSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
console.log("Users loaded:", allUsers.length, "users found");
} catch (error) {
console.error("Error loading users:", error);
}
}
// Load all tasks from Firestore
async function loadAllTasks() {
try {
console.log("Loading tasks from Firestore...");
const tasksCollection = collection(db, "tasks");
const tasksSnapshot = await getDocs(tasksCollection);
allTasks = tasksSnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
console.log("Tasks loaded:", allTasks.length, "tasks found");
} catch (error) {
console.error("Error loading tasks:", error);
}
}
// Load budget data from Firestore
async function loadBudgetData() {
try {
console.log("Loading budget data from Firestore...");
const dataCollection = collection(db, "data");
const dataSnapshot = await getDocs(dataCollection);
if (!dataSnapshot.empty) {
// Get the first (and only) document
const dataDoc = dataSnapshot.docs[0];
budgetData = {
id: dataDoc.id,
...dataDoc.data()
};
console.log("Budget data loaded:", budgetData);
} else {
console.warn("No budget data found in 'data' collection");
budgetData = {
quarterlyBudget: 0,
weeklyBudget: 0,
yearlyBudget: 0,
avgPay: 0
};
}
} catch (error) {
console.error("Error loading budget data:", error);
}
}
// Update budget data in Firestore
async function updateBudgetData(updates) {
try {
if (!budgetData || !budgetData.id) {
console.error("Budget data not loaded yet");
return;
}
await updateDoc(doc(db, "data", budgetData.id), updates);
// Update local copy
budgetData = {
...budgetData,
...updates
};
console.log("Budget data updated:", updates);
} catch (error) {
console.error("Error updating budget data:", error);
throw error;
}
}
// Load academic quarter dates from DePaul calendar via server
async function loadQuarterDates() {
try {
console.log("Loading DePaul academic quarter dates...");
const response = await fetch(getApiUrl('quarter-dates'));
if (!response.ok) {
throw new Error(`Failed to fetch quarter dates: ${response.statusText}`);
}
const data = await response.json();
quarterDates = data;
console.log("Quarter dates loaded:", quarterDates);
} catch (error) {
console.error("Error loading quarter dates:", error);
quarterDates = null;
}
}
// Render team list
function renderTeamList() {
const teamContainer = document.querySelector('#team article');
if (!teamContainer) return;
// Filter out managers, only show regular users
const regularUsersUNF = allUsers.filter(user => user.role !== "manager");
let regularUsers = regularUsersUNF.sort((a, b) => a.fullName.localeCompare(b.fullName));
if (regularUsers.length === 0) {
teamContainer.innerHTML = '<p>No team members found.</p>';
fadeIn(teamContainer.querySelector('p'));
return;
}
teamContainer.innerHTML = regularUsers.map(user => {
// Determine badge color based on active tasks
const userTasks = allTasks.filter(task =>
task.assignedTo && task.assignedTo.includes(user.id) && !task.completed
);
const taskCount = userTasks.length;
var colors = ['green', 'yellow', 'red', 'purple', 'blue', 'pink', 'indigo'];
let badgeColor = 'green';
if (taskCount >= 8) badgeColor = 'red';
else if (taskCount >= 4) badgeColor = 'yellow';
return `<a class="hoveranim user-link" href="#" data-user-id="${user.id}"><span class="badge badge-${badgeColor}"><i class="fa-solid fa-user"></i> ${user.fullName}</span></a>`;
}).join('\n');
// Animate team member badges with stagger effect
fadeInStagger(teamContainer, '.user-link');
// Attach click listeners
document.querySelectorAll('.user-link').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const userId = link.getAttribute('data-user-id');
openUserDialog(userId);
});
});
}
// Open user edit dialog
function openUserDialog(userId) {
selectedUser = allUsers.find(u => u.id === userId);
if (!selectedUser) return;
const dialog = document.getElementById('editUser');
// Update dialog content
const userName = dialog.querySelector('h2');
userName.innerHTML = `<i class="fa-solid fa-user"></i> ${selectedUser.fullName}`;
const now = new Date();
// Get user's active tasks (not completed and not expired)
const userTasks = allTasks.filter(task => {
if (!task.assignedTo || !task.assignedTo.includes(selectedUser.id)) return false;
if (task.completed) return false;
// Exclude expired nonflexible tasks
if (task.nonflexible && task.due) {
const dueDate = task.due.toDate ? task.due.toDate() : new Date(task.due);
if (dueDate < now) return false;
}
return true;
});
// Get user's historical tasks (completed or expired nonflexible)
const historicalTasks = allTasks.filter(task => {
if (!task.assignedTo || !task.assignedTo.includes(selectedUser.id)) return false;
// Include completed tasks
if (task.completed) return true;
// Include expired nonflexible tasks
if (task.nonflexible && task.due) {
const dueDate = task.due.toDate ? task.due.toDate() : new Date(task.due);
if (dueDate < now) return true;
}
return false;
});
// Render active tasks
const flexContainer = dialog.querySelector('div[style*="display: flex"]');
const allDivs = flexContainer.querySelectorAll(':scope > div');
const tasksDiv = allDivs[0]; // First div is tasks
const tasksSection = tasksDiv.querySelector('h5');
tasksSection.textContent = `${userTasks.length} Active Task${userTasks.length !== 1 ? 's' : ''}`;
const tasksArticle = tasksDiv.querySelector('article');
if (userTasks.length === 0) {
tasksArticle.innerHTML = '<p style="color: #888;">No active tasks</p>';
} else {
tasksArticle.innerHTML = userTasks.map(task =>
`<span class="badge badge-gray"><i class="fa-solid fa-${task.icon || 'list'}"></i> ${task.title} | ${task.hours} Hrs <a href="#" class="hoveranim delete-assignment" data-task-id="${task.id}"><i class="fa-solid fa-x"></i></a></span><br>`
).join('');
// Attach delete assignment listeners
setTimeout(() => {
dialog.querySelectorAll('.delete-assignment').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const taskId = link.getAttribute('data-task-id');
removeUserFromTask(taskId);
});
});
}, 0);
}
// Populate allowed hours
const allowedHoursInput = document.getElementById('userAllowedHours');
if (allowedHoursInput) {
allowedHoursInput.value = selectedUser.allowedHours || 25;
// Add change listener to save allowed hours
allowedHoursInput.addEventListener('change', async () => {
const newAllowedHours = parseInt(allowedHoursInput.value) || 25;
try {
await updateDoc(doc(db, "users", selectedUser.id), {
allowedHours: newAllowedHours
});
// Update local data
selectedUser.allowedHours = newAllowedHours;
const userIndex = allUsers.findIndex(u => u.id === selectedUser.id);
if (userIndex !== -1) {
allUsers[userIndex].allowedHours = newAllowedHours;
}
console.log(`Allowed hours updated to ${newAllowedHours} for ${selectedUser.fullName}`);
} catch (error) {
console.error("Error updating allowed hours:", error);
alert("Error updating allowed hours: " + error.message);
}
});
}
//Render task history
renderTaskHistory(historicalTasks);
// Render skills
renderSkillsInDialog();
// Show dialog
dialog.showModal();
}
function renderTaskHistory(historicalTasks) {
const historySection = document.getElementById('taskHistoryTitle');
const historyArticle = document.getElementById('taskHistoryContent');
if (!historySection || !historyArticle) {
console.warn('Task history elements not found');
return;
}
// Update section title
historySection.textContent = `${historicalTasks.length} Historical Task${historicalTasks.length !== 1 ? 's' : ''}`;
if (historicalTasks.length === 0) {
historyArticle.innerHTML = '<p style="color: #888;">No task history</p>';
} else {
historyArticle.innerHTML = historicalTasks.map(task => {
const statusBadge = task.completed
? '<span class="badge badge-green">Completed</span>'
: '<span class="badge badge-red">Expired</span>';
return `<span class="badge badge-gray"><i class="fa-solid fa-${task.icon || 'list'}"></i> ${task.title} | ${task.hours} Hrs ${statusBadge}</span><br>`;
}).join('');
}
}
// Render skills in dialog
function renderSkillsInDialog() {
const dialog = document.getElementById('editUser');
const flexContainer = dialog.querySelector('div[style*="display: flex"]');
const allDivs = flexContainer.querySelectorAll(':scope > div');
const skillsDiv = allDivs[1]; // Second div is skills
const skillsArticle = skillsDiv.querySelector('article');
const userSkills = selectedUser.skills || [];
if (userSkills.length === 0) {
skillsArticle.innerHTML = '<p style="color: #888;">No skills added yet</p>';
} else {
skillsArticle.innerHTML = userSkills.map(skill =>
`<span class="badge badge-gray">${skill} <a href="#" class="hoveranim delete-skill" data-skill="${skill}"><i class="fa-solid fa-x"></i></a></span>`
).join(' ');
}
// Attach delete listeners
dialog.querySelectorAll('.delete-skill').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const skill = link.getAttribute('data-skill');
removeSkill(skill);
});
});
}
// Setup dialog functionality
const dialog = document.getElementById('editUser');
// Close button
const closeButton = dialog.querySelector('button[aria-label="Close"]');
closeButton.addEventListener('click', () => {
dialog.close();
});
// Add skill button
const addSkillButtons = Array.from(dialog.querySelectorAll('button')).filter(btn =>
btn.textContent.includes('Add Skill')
);
if (addSkillButtons.length > 0) {
addSkillButtons[0].addEventListener('click', () => {
showAddSkillPrompt();
});
}
// Delete user button
const deleteUserButtons = Array.from(dialog.querySelectorAll('button')).filter(btn =>
btn.textContent.includes('Delete User')
);
if (deleteUserButtons.length > 0) {
deleteUserButtons[0].addEventListener('click', () => {
confirmDeleteUser();
});
}
// Show add skill prompt
function showAddSkillPrompt() {
if (!selectedUser) return;
const userSkills = selectedUser.skills || [];
const availableSkills = AVAILABLE_SKILLS.filter(skill => !userSkills.includes(skill));
if (availableSkills.length === 0) {
alert("This user already has all available skills!");
return;
}
const skillList = availableSkills.map((skill, idx) => `${idx + 1}. ${skill}`).join('\n');
const skillInput = prompt(`Available skills:\n${skillList}\n\nEnter the number or name of the skill to add:`);
if (!skillInput) return;
let skillToAdd;
// Check if input is a number
if (!isNaN(skillInput)) {
const index = parseInt(skillInput) - 1;
if (index >= 0 && index < availableSkills.length) {
skillToAdd = availableSkills[index];
}
} else {
// Check if input matches a skill name
skillToAdd = availableSkills.find(skill =>
skill.toLowerCase() === skillInput.toLowerCase()
);
}
if (skillToAdd) {
addSkill(skillToAdd);
} else {
alert("Invalid skill selection. Please try again.");
}
}
// Add skill to user
async function addSkill(skill) {
if (!selectedUser) return;
try {
await updateDoc(doc(db, "users", selectedUser.id), {
skills: arrayUnion(skill)
});
// Update local data
if (!selectedUser.skills) selectedUser.skills = [];
selectedUser.skills.push(skill);
// Update the user in allUsers array
const userIndex = allUsers.findIndex(u => u.id === selectedUser.id);
if (userIndex !== -1) {
allUsers[userIndex] = selectedUser;
}
// Re-render skills
renderSkillsInDialog();
console.log(`Skill "${skill}" added to ${selectedUser.fullName}`);
} catch (error) {
console.error("Error adding skill:", error);
alert("Error adding skill: " + error.message);
}
}
// Remove skill from user
async function removeSkill(skill) {
if (!selectedUser) return;
if (!confirm(`Remove "${skill}" from ${selectedUser.fullName}?`)) {
return;
}
try {
await updateDoc(doc(db, "users", selectedUser.id), {
skills: arrayRemove(skill)
});
// Update local data
if (selectedUser.skills) {
const index = selectedUser.skills.indexOf(skill);
if (index > -1) {
selectedUser.skills.splice(index, 1);
}
}
// Update the user in allUsers array
const userIndex = allUsers.findIndex(u => u.id === selectedUser.id);
if (userIndex !== -1) {
allUsers[userIndex] = selectedUser;
}
// Re-render skills
renderSkillsInDialog();
console.log(`Skill "${skill}" removed from ${selectedUser.fullName}`);
} catch (error) {
console.error("Error removing skill:", error);
alert("Error removing skill: " + error.message);
}
}
// Remove user from a task assignment
async function removeUserFromTask(taskId) {
if (!selectedUser) return;
const task = allTasks.find(t => t.id === taskId);
if (!task) return;
if (!confirm(`Remove ${selectedUser.fullName} from "${task.title}"?`)) {
return;
}
try {
// Delete WhenIWork shift for this user if it exists
const wiwShiftIDs = task.wiwShiftIDs || {};
const shiftId = wiwShiftIDs[selectedUser.id];
if (shiftId) {
try {
console.log(`Deleting WhenIWork shift ${shiftId} for user ${selectedUser.id}`);
await deleteWIWShift(shiftId);
delete wiwShiftIDs[selectedUser.id];
console.log(`✓ WhenIWork shift ${shiftId} deleted`);
} catch (wiwError) {
console.error(`Error deleting WhenIWork shift:`, wiwError);
}
}
// Update Firestore - remove user from assignedTo and assignedToNames arrays, update wiwShiftIDs
await updateDoc(doc(db, "tasks", taskId), {
assignedTo: arrayRemove(selectedUser.id),
assignedToNames: arrayRemove(selectedUser.fullName),
wiwShiftIDs: wiwShiftIDs
});
// Update local data
const taskIndex = allTasks.findIndex(t => t.id === taskId);
if (taskIndex !== -1) {
if (allTasks[taskIndex].assignedTo) {
allTasks[taskIndex].assignedTo = allTasks[taskIndex].assignedTo.filter(id => id !== selectedUser.id);
}
if (allTasks[taskIndex].assignedToNames) {
allTasks[taskIndex].assignedToNames = allTasks[taskIndex].assignedToNames.filter(name => name !== selectedUser.fullName);
}
allTasks[taskIndex].wiwShiftIDs = wiwShiftIDs;
}
// Send Slack notification
try {
const idToken = await auth.currentUser.getIdToken();
await fetch(getApiUrl('notify/task-unclaimed'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${idToken}`
},
body: JSON.stringify({
taskData: {
title: task.title,
hours: task.hours,
due: task.due
},
userData: {
email: selectedUser.email,
fullName: selectedUser.fullName
}
})
});
} catch (slackError) {
console.warn('Slack notification failed (non-critical):', slackError);
}
// Re-open the dialog to refresh the task list
openUserDialog(selectedUser.id);
console.log(`${selectedUser.fullName} removed from task "${task.title}"`);
} catch (error) {
console.error("Error removing user from task:", error);
alert("Error removing assignment: " + error.message);
}
}
// Helper function to check if a date is in the current week
function isDateInCurrentWeek(date) {
const now = new Date();
const startOfWeek = new Date(now);
startOfWeek.setDate(now.getDate() - now.getDay()); // Sunday
startOfWeek.setHours(0, 0, 0, 0);
const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(startOfWeek.getDate() + 7);
return date >= startOfWeek && date < endOfWeek;
}
// Helper function to check if a date is in the current academic quarter
function isDateInCurrentQuarter(date) {
if (!quarterDates || !quarterDates.quarters) {
console.error('[Quarter Check] Quarter data not loaded!');
return false;
}
const now = new Date();
console.log(`[Quarter Check] Checking if ${date.toISOString()} is in current academic quarter`);
// Get all quarters in chronological order
const quarterOrder = ['autumn', 'winter', 'spring', 'summer'];
const sortedQuarters = quarterOrder
.filter(q => quarterDates.quarters[q])
.map(q => ({
name: q,
start: new Date(quarterDates.quarters[q].start),
displayName: quarterDates.quarters[q].name
}));
// Find which quarter we're currently in
for (let i = 0; i < sortedQuarters.length; i++) {
const quarter = sortedQuarters[i];
const nextQuarter = sortedQuarters[i + 1];
const quarterStart = quarter.start;
// Quarter ends when next quarter starts, or end of year if last quarter
const quarterEnd = nextQuarter ? nextQuarter.start : new Date(quarter.start.getFullYear() + 1, 8, 1); // Aug 1 next year
// Check if 'now' is in this quarter
if (now >= quarterStart && now < quarterEnd) {
console.log(`[Quarter Check] Current quarter: ${quarter.displayName} (${quarterStart.toLocaleDateString()} - ${quarterEnd.toLocaleDateString()})`);
const result = date >= quarterStart && date < quarterEnd;
console.log(`[Quarter Check] Date ${date.toLocaleDateString()} is ${result ? 'IN' : 'NOT IN'} current quarter`);
return result;
}
}
console.log('[Quarter Check] Not currently in any academic quarter');
return false;
}
// Helper function to check if a date is in the current academic year
function isDateInCurrentYear(date) {
if (!quarterDates || !quarterDates.quarters) {
console.error('[Year Check] Quarter data not loaded!');
return false;
}
console.log('[Year Check] quarterDates.quarters:', quarterDates.quarters);
// Academic year runs from Autumn start to next Autumn start
const autumn = quarterDates.quarters.autumn;
if (!autumn) {
console.error('[Year Check] Quarter data incomplete (missing autumn)!');
return false;
}
console.log('[Year Check] autumn object:', autumn);
console.log('[Year Check] autumn.start:', autumn.start);
const academicYearStart = new Date(autumn.start);
// Academic year ends when the next autumn starts (approximately 1 year later)
const academicYearEnd = new Date(academicYearStart);
academicYearEnd.setFullYear(academicYearEnd.getFullYear() + 1);
console.log(`[Year Check] Academic year: ${academicYearStart.toLocaleDateString()} - ${academicYearEnd.toLocaleDateString()}`);
console.log('[Year Check] academicYearStart ISO:', academicYearStart.toISOString());
console.log('[Year Check] academicYearEnd ISO:', academicYearEnd.toISOString());
const result = date >= academicYearStart && date < academicYearEnd;
console.log(`[Year Check] Date ${date.toLocaleDateString()} is ${result ? 'IN' : 'NOT IN'} current academic year`);
// Check if date is within the academic year range
return result;
}
// Setup hours calculation mode switch
function setupHoursCalculationSwitch() {
const includeActiveSwitch = document.getElementById('includeActiveHours');
const noteElement = document.getElementById('hoursCalculationNote');
if (includeActiveSwitch) {
includeActiveSwitch.addEventListener('change', async () => {
// Update note text
if (includeActiveSwitch.checked) {
noteElement.textContent = 'Hour usage includes both completed and active tasks, as well as shifts scheduled in WhenIWork.';
} else {
noteElement.textContent = "Hour usage is based on tasks marked as 'complete' and shifts scheduled in WhenIWork.";
}
// Show loader while recalculating
const loader = document.getElementById('overviewLoader');
const content = document.getElementById('overviewContent');
if (loader) loader.style.display = 'flex';
if (content) content.style.display = 'none';
// Re-render hours with new calculation mode
await renderHours();
});
}
}
async function renderHours() {
// Check if budget data is loaded
if (!budgetData) {
console.error("[Render Hours] Budget data not loaded yet");
return;
}
// Check if we should include active tasks
const includeActiveSwitch = document.getElementById('includeActiveHours');
const includeActive = includeActiveSwitch ? includeActiveSwitch.checked : false;
console.log(`[Render Hours] Include active tasks: ${includeActive}`);
var totalHoursYear = 0;
var totalHoursQuarter = 0;
var totalHoursWeek = 0;
// Initialize WhenIWork once (login + get users)
console.log('[Render Hours] Initializing WhenIWork...');
await initializeWhenIWork().catch(err => { console.error('[WhenIWork Init]', err); });
// Fetch WhenIWork hours efficiently in a single pass
console.log('[Render Hours] Fetching WhenIWork scheduled hours...');
const wiwHours = await getScheduledHours(quarterDates).catch(err => {
console.error('[WhenIWork Hours]', err);
return { week: 0, quarter: 0, year: 0 };
});
const whenIWorkWeek = wiwHours.week;
const whenIWorkQuarter = wiwHours.quarter;
const whenIWorkYear = wiwHours.year;
console.log(`[Render Hours] WhenIWork hours - Week: ${whenIWorkWeek}, Quarter: ${whenIWorkQuarter}, Year: ${whenIWorkYear}`);
var tasksCountedYear = 0;
var tasksCountedQuarter = 0;
var tasksCountedWeek = 0;
allTasks.forEach(function(element, index) {
// Determine if we should count this task
const shouldCount = includeActive
? element.assignedTo && element.assignedTo.length > 0
: element.completed && element.assignedTo && element.assignedTo.length > 0;
if (shouldCount) {
let dateToCheck = null;
// For completed tasks, use completedDate (or fall back to due date for old tasks)
if (element.completed) {
if (element.completedDate) {
dateToCheck = new Date(element.completedDate.toDate());
console.log(`[Task ${index}] "${element.title}" - Completed: ${dateToCheck.toLocaleDateString()}, Hours: ${element.hours || 0}`);
} else if (element.due) {
// Fallback for old completed tasks without completedDate
dateToCheck = new Date(element.due.toDate());
console.log(`[Task ${index}] "${element.title}" - Completed (old, using due date): ${dateToCheck.toLocaleDateString()}, Hours: ${element.hours || 0}`);
} else {
console.log(`[Task ${index}] "${element.title}" - Skipped (Completed but no completedDate or due date)`);
return;
}
}
// For active tasks (when includeActive is true), use due date
else if (!element.completed && element.due) {
dateToCheck = new Date(element.due.toDate());
console.log(`[Task ${index}] "${element.title}" - Active, Due: ${dateToCheck.toLocaleDateString()}, Hours: ${element.hours || 0}`);
}
// Skip if no date available
else {
console.log(`[Task ${index}] "${element.title}" - Skipped (No due date)`);
return;
}
if (isDateInCurrentYear(dateToCheck)) {
totalHoursYear += Number(element.hours) || 0;
tasksCountedYear++;
console.log(` ✓ Added to year total. Year total now: ${totalHoursYear} (${tasksCountedYear} tasks)`);
if (isDateInCurrentQuarter(dateToCheck)) {
totalHoursQuarter += Number(element.hours) || 0;
tasksCountedQuarter++;
console.log(` ✓ Added to quarter total. Quarter total now: ${totalHoursQuarter} (${tasksCountedQuarter} tasks)`);
if (isDateInCurrentWeek(dateToCheck)) {
totalHoursWeek += Number(element.hours) || 0;
tasksCountedWeek++;
console.log(` ✓ Added to week total. Week total now: ${totalHoursWeek} (${tasksCountedWeek} tasks)`);
}
}
}
} else {
console.log(`[Task ${index}] "${element.title}" - Skipped (Completed: ${element.completed}, Include active: ${includeActive})`);
}
});
// Add WhenIWork hours to totals
totalHoursWeek += whenIWorkWeek;
totalHoursQuarter += whenIWorkQuarter;
totalHoursYear += whenIWorkYear;
console.log('======================================');
console.log('[Render Hours] Final totals (including WhenIWork):');
console.log(` Week: ${totalHoursWeek} hours (${tasksCountedWeek} tasks + ${whenIWorkWeek} WhenIWork hrs) (budget: ${budgetData.weeklyBudget})`);
console.log(` Quarter: ${totalHoursQuarter} hours (${tasksCountedQuarter} tasks + ${whenIWorkQuarter} WhenIWork hrs) (budget: ${budgetData.quarterlyBudget})`);
console.log(` Year: ${totalHoursYear} hours (${tasksCountedYear} tasks + ${whenIWorkYear} WhenIWork hrs) (budget: ${budgetData.yearlyBudget})`);
console.log('======================================');
// Update circular progress bars
updateCircularProgress('weekly', totalHoursWeek, budgetData.weeklyBudget, 'this week');
updateCircularProgress('quarterly', totalHoursQuarter, budgetData.quarterlyBudget, 'this quarter');
updateCircularProgress('yearly', totalHoursYear, budgetData.yearlyBudget, 'this year');
// Hide loader and show content with animation
const loader = document.getElementById('overviewLoader');
const content = document.getElementById('overviewContent');
if (loader) loader.style.display = 'none';
if (content) {
content.style.display = 'block';
fadeIn(content);
}
console.log('[Render Hours] UI updated successfully');
}
// Helper function to update circular progress bars
function updateCircularProgress(period, used, budget, label) {
const remaining = budget - used;
const percentage = budget > 0 ? Math.min((used / budget) * 100, 100) : 0;
const isOverBudget = remaining < 0;
// Update text
document.getElementById(`${period}Usage`).textContent = `${used} out of ${budget} hours ${label}`;
const remainingElement = document.getElementById(`${period}Remaining`);
remainingElement.textContent = `${Math.abs(remaining)} hours ${remaining >= 0 ? 'remaining' : 'over budget'}`;
// Add/remove negative class
if (isOverBudget) {
remainingElement.classList.add('negative');
} else {
remainingElement.classList.remove('negative');
}
// Update percentage display
document.getElementById(`${period}Percent`).textContent = `${Math.round(percentage)}%`;
// Update circular progress
const circle = document.getElementById(`${period}Circle`);
const radius = 54;
const circumference = 2 * Math.PI * radius; // 339.292
const offset = circumference - (percentage / 100 * circumference);
circle.style.strokeDashoffset = offset;
// Add/remove over-budget class
if (isOverBudget) {
circle.classList.add('over-budget');
} else {
circle.classList.remove('over-budget');
}
}
// Confirm and delete user
async function confirmDeleteUser() {
if (!selectedUser) return;
const confirmation = prompt(`WARNING: This will permanently delete ${selectedUser.fullName} from both Firebase Auth and Firestore, and remove them from all assigned tasks.\n\nType "${selectedUser.fullName}" to confirm deletion:`);
if (confirmation !== selectedUser.fullName) {
alert("Deletion cancelled - name did not match.");
return;
}
const dialog = document.getElementById('editUser');
const dialogContent = dialog.querySelector('article');
// Show loading state
const originalContent = dialogContent.innerHTML;