-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscheduler_rest.html
More file actions
779 lines (666 loc) · 30.8 KB
/
scheduler_rest.html
File metadata and controls
779 lines (666 loc) · 30.8 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
<!DOCTYPE html>
<html>
<head>
<title>Course Scheduler</title>
<style>
html, body {
font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
margin: 0;
padding: 10px;
background-color: #f5f5f5;
}
h1 {
font-size: 1.5em;
text-align: center;
}
#main-form {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 1em;
padding: 0;
justify-content: center;
}
#status-dot {
display: inline-block;
width: 14px;
height: 14px;
border-radius: 50%;
background: #bbb;
margin-left: 2px;
}
#nav-controls {
display: none;
width: 100%;
text-align: center;
}
#nav-controls.visible {
display: flex;
justify-content: center;
align-items: center;
gap: 10px;
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
@media not print {
.gap {
margin-top: 20px;
margin-bottom: 20px;
}
.grid {
display: flex;
flex-wrap: wrap;
row-gap: 20px;
column-gap: 20px;
justify-content: space-around;
flex: 0 0 600px;
}
.grid > div {
flex: 0 0 600px;
margin: 0;
box-shadow: 0 2px 10px rgba(0,0,0,0.3);
border: 1px solid #ddd;
border-radius: 8px;
}
}
@media print {
.container {
display: none !important;
}
.grid > div {
page-break-after: always;
break-after: page;
}
}
#content {
display: none;
}
</style>
</head>
<body>
<div class="container">
<h1>Course Scheduler</h1>
<form id="main-form">
<input type="text" id="server-url" value="http://localhost:8000" placeholder="Server URL">
<span id="status-dot"></span>
<input type="file" id="config-file" accept=".json">
<button type="button" onclick="submitConfiguration()">Submit</button>
<div id="nav-controls">
<button type="button" id="prev" onclick="previousSchedule()">Previous</button>
<span id="curr">0 of 0</span>
<button type="button" id="next" onclick="nextSchedule()">Next</button>
</div>
</form>
</div>
<div id="content">
<div class="gap"></div>
<div class="container">
<h1>Rooms</h1>
</div>
<div id="schedule" class="gap grid"></div>
<div class="container">
<h1>Faculty</h1>
</div>
<div id="faculty" class="gap grid"></div>
</div>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script type="text/javascript">
// Layout constants
const DAY_WIDTH = 110;
const DAY_PADDING = 2;
const LEFT_MARGIN = 45;
const TEXT_OFFSET = 50;
const SVG_PADDING = 2;
let currentSessionId = null;
let currentIndex = -1;
let totalGenerated = 0;
let scheduleLimit = 10;
let cleanupTriggered = false;
let cachedCountData = null; // Cache for count data
// Utility functions
function showError(message) {
alert(`Error: ${message}`);
}
function getBaseUrl() {
return document.getElementById('server-url').value.replace(/\/$/, '');
}
// API functions
async function cancelExistingSession() {
if (currentSessionId && !cleanupTriggered) {
try {
const url = getBaseUrl();
await fetch(`${url}/schedules/${currentSessionId}/cleanup`, {
method: 'POST'
});
cleanupTriggered = true;
hideContent();
} catch (error) {
console.error('Failed to cancel existing session:', error);
}
}
}
async function checkServerStatus() {
const dot = document.getElementById('status-dot');
dot.style.background = '#bbb'; // gray (checking)
try {
const url = getBaseUrl();
const response = await fetch(`${url}/health`, {method: 'GET'});
if (response.ok) {
dot.style.background = '#2ecc40'; // green
} else {
dot.style.background = '#e74c3c'; // red
}
} catch {
dot.style.background = '#e74c3c'; // red
}
}
async function submitConfiguration() {
const fileInput = document.getElementById('config-file');
if (!fileInput.files[0]) {
showError('Please select a configuration file');
return;
}
// Cancel existing session before submitting new configuration
await cancelExistingSession();
try {
const fileContent = await fileInput.files[0].text();
const configData = JSON.parse(fileContent);
const url = getBaseUrl();
const response = await fetch(`${url}/submit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(configData)
});
if (response.ok) {
const result = await response.json();
currentSessionId = result.schedule_id;
scheduleLimit = configData.limit;
currentIndex = -1;
totalGenerated = 0;
cleanupTriggered = false;
cachedCountData = null; // Reset cached data
document.getElementById('nav-controls').classList.add('visible');
updateNavigation();
startCountPolling();
// Automatically trigger generate all after session creation
await generateAllSchedules();
} else {
const errorText = await response.text();
showError(`[ERROR] Failed to submit configuration: ${response.status} - ${errorText}`);
hideContent();
}
} catch (error) {
showError(`[ERROR] Error: ${error.message}`);
hideContent();
}
}
async function navigateSchedule(direction) {
if (!currentSessionId) return;
// Use cached count data if available, otherwise fetch it
let countData = cachedCountData;
if (!countData) {
countData = await getScheduleCount();
if (!countData) {
showError('Failed to get schedule count from server');
return;
}
}
const newIndex = currentIndex + direction;
// Check bounds
if (newIndex < 0 || newIndex >= countData.current_count) {
return;
}
await loadScheduleByIndex(newIndex);
}
// Replace the separate navigation functions with calls to the generic one
const nextSchedule = () => navigateSchedule(1);
const previousSchedule = () => navigateSchedule(-1);
async function loadScheduleByIndex(index) {
if (!currentSessionId || index < 0) return;
try {
const url = getBaseUrl();
const response = await fetch(`${url}/schedules/${currentSessionId}/index/${index}`, {
method: 'GET'
});
if (response.ok) {
const result = await response.json();
displaySchedule(result.schedule);
currentIndex = index;
updateNavigation(cachedCountData); // Pass cached data
} else {
showError(`[ERROR] Failed to load schedule: ${response.status}`);
}
} catch (error) {
showError(`[ERROR] Error: ${error.message}`);
}
}
async function generateAllSchedules() {
if (!currentSessionId) return;
try {
const url = getBaseUrl();
const response = await fetch(`${url}/schedules/${currentSessionId}/generate_all`, {
method: 'POST'
});
if (response.ok) {
const result = await response.json();
// Start polling for count updates
startCountPolling();
} else {
const errorText = await response.text();
showError(`[ERROR] Failed to start generation: ${response.status} - ${errorText}`);
}
} catch (error) {
showError(`[ERROR] Error: ${error.message}`);
}
}
async function getScheduleCount() {
if (!currentSessionId) return null;
try {
const url = getBaseUrl();
const response = await fetch(`${url}/schedules/${currentSessionId}/count`, {
method: 'GET'
});
if (response.ok) {
const result = await response.json();
cachedCountData = result; // Cache the result
return result;
}
} catch (error) {
console.error('Failed to get schedule count:', error);
}
return null;
}
let countPollingInterval = null;
function startCountPolling() {
// Clear any existing polling
if (countPollingInterval) {
clearInterval(countPollingInterval);
}
// Poll every 2 seconds
countPollingInterval = setInterval(async () => {
const countData = await getScheduleCount();
if (countData) {
totalGenerated = countData.current_count;
updateNavigation(countData); // Pass the fresh data
// Stop polsling if generation is complete
if (countData.is_complete) {
clearInterval(countPollingInterval);
countPollingInterval = null;
}
}
}, 1000);
}
function updateNavigation(countData = null) {
// If countData is provided, use it; otherwise use cached data
const data = countData || cachedCountData;
if (!data) return;
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');
const currSpan = document.getElementById('curr');
totalGenerated = data.current_count;
currSpan.textContent = `${currentIndex + 1} of ${Math.max(currentIndex + 1, totalGenerated)}`;
prevBtn.disabled = currentIndex <= 0;
nextBtn.disabled = currentIndex + 1 >= totalGenerated;
}
// Schedule display functions (adapted from original)
const getHashCode = (str) => {
let h1 = 0x10293847;
let h2 = 0xfeedf00d;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
const intToHSL = (val) => {
const shortened = Math.imul(val, Math.imul(val, val)) % 360;
return "hsla(" + shortened + ",100%,30%,20%)";
};
function map_course(c) {
const result = [];
const {course, faculty, room, times, lab, lab_index} = c;
for (const t in times) {
const entry = {...times[t]};
entry['name'] = course;
entry['room'] = room;
entry['faculty'] = faculty;
result.push(entry);
}
if (lab) {
const entry = {...times[lab_index]};
entry['name'] = course;
entry['room'] = lab;
entry['faculty'] = faculty;
result.push(entry);
}
return result;
}
function displaySchedule(scheduleData) {
// Show the content div when displaying schedules
document.getElementById('content').style.display = 'block';
displayRoomSchedule(scheduleData);
displayFacultySchedule(scheduleData);
}
function hideContent() {
document.getElementById('content').style.display = 'none';
}
function displayRoomSchedule(scheduleData) {
const scheduleContainer = document.getElementById('schedule');
scheduleContainer.innerHTML = '';
// Hide content if no schedule data
if (!scheduleData || scheduleData.length === 0) {
hideContent();
return;
}
const the_data = scheduleData.flatMap(map_course);
// Extract unique locations
const rooms = new Set();
const labs = new Set();
for (const c of scheduleData) {
if (c.room) {
rooms.add(c.room);
}
if (c.lab) {
labs.add(c.lab);
}
}
const locations = Array.from(rooms).sort().concat(Array.from(labs).sort());
for (const room of locations) {
const div = d3.select("#schedule")
.append("div")
.style("padding", "5px")
.style("background", "white")
.style("width", (LEFT_MARGIN + (5 * DAY_WIDTH)) + "px");
div.append("h2")
.text(room)
.style("margin-top", "0")
.style("margin-bottom", "8px")
.style("margin-left", "5px")
.style("text-align", "center");
const days = div.append("div");
days.append('div')
.style('width', '40px')
.style("display", "inline-block");
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
for (const i in DAYS) {
days.append('span')
.text(DAYS[i])
.style("font-size", "10px")
.style("width", DAY_WIDTH + "px")
.style("display", "inline-block")
.style("text-align", "center");
}
// Compute time range for this room
const filtered = the_data.filter(x => x.room == room);
let minHour = 24;
let maxHour = 0;
for (const classData of filtered) {
const startHour = Math.floor(classData.start / 60);
const endHour = Math.ceil((classData.start + classData.duration) / 60);
minHour = Math.min(minHour, startHour);
maxHour = Math.max(maxHour, endHour);
}
if (minHour === 24 || maxHour === 0) {
minHour = 8;
maxHour = 17;
}
const TIMES = [];
for (let hour = minHour; hour <= maxHour; hour++) {
TIMES.push(hour);
}
const svgHeight = (maxHour - minHour) * 60 + (2 * SVG_PADDING);
const svg = div.append("svg")
.attr("width", LEFT_MARGIN + (5 * DAY_WIDTH))
.attr("height", svgHeight);
svg.selectAll('line')
.data(TIMES)
.enter()
.append('line')
.style("stroke", "lightgrey")
.style("stroke-width", 1)
.attr('x1', 0).attr('y1', d => (d - minHour) * 60 + SVG_PADDING)
.attr('x2', LEFT_MARGIN + (5 * DAY_WIDTH)).attr('y2', d => (d - minHour) * 60 + SVG_PADDING);
svg.selectAll('text')
.data(TIMES)
.enter()
.append('text')
.attr('x', 0).attr('y', d => (d - minHour) * 60 + SVG_PADDING)
.attr('dy', 12)
.text(d => {
const h = (d > 12) ? d - 12 : d;
const ap = (d >= 12) ? "PM" : "AM";
return h + ":00" + ap;
})
.style("font-size", "10px");
svg.selectAll('rect')
.data(filtered)
.enter()
.append('rect')
.attr('x', d => (d.day - 1) * DAY_WIDTH + LEFT_MARGIN + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING)
.attr('width', DAY_WIDTH - 2 * DAY_PADDING)
.attr('height', d => d.duration)
.style('fill', d => intToHSL(getHashCode(d.faculty)))
.style('stroke', 'black');
const group = svg.selectAll('g')
.data(filtered)
.enter()
.append('g');
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING)
.text(d => d.name)
.style('font-weight', 700)
.style("font-size", "12px");
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING + 15)
.text(d => d.faculty)
.style("font-size", "10px");
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING + 30)
.text(d => {
const fn = (t) => {
const hh = Math.floor(t / 60);
const mm = t % 60;
const h = (hh > 12) ? hh - 12 : hh;
const ap = (hh >= 12) ? "PM" : "AM";
return h + ":" + String(mm).padStart(2, '0') + ap;
};
return fn(d.start) + "-" + fn(d.start + d.duration);
})
.style("font-size", "10px");
}
}
function displayFacultySchedule(scheduleData) {
const facultyContainer = document.getElementById('faculty');
facultyContainer.innerHTML = '';
// Extract unique faculty members
const facultyMembers = new Set();
for (const c of scheduleData) {
if (c.faculty) {
facultyMembers.add(c.faculty);
}
}
const facultyList = Array.from(facultyMembers).sort();
for (const faculty of facultyList) {
const div = d3.select("#faculty")
.append("div")
.style("padding", "5px")
.style("background", "white")
.style("width", (LEFT_MARGIN + (5 * DAY_WIDTH)) + "px");
div.append("h2")
.text(faculty)
.style("margin-top", "0")
.style("margin-bottom", "8px")
.style("margin-left", "5px")
.style("text-align", "center");
const days = div.append("div");
days.append('div')
.style('width', '40px')
.style("display", "inline-block");
const DAYS = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
for (const i in DAYS) {
days.append('span')
.text(DAYS[i])
.style("font-size", "10px")
.style("width", DAY_WIDTH + "px")
.style("display", "inline-block")
.style("text-align", "center");
}
// Compute time range for this faculty member
let minHour = 24;
let maxHour = 0;
for (const c of scheduleData) {
if (c.faculty === faculty) {
for (const t in c.times) {
const classData = c.times[t];
const startHour = Math.floor(classData.start / 60);
const endHour = Math.ceil((classData.start + classData.duration) / 60);
minHour = Math.min(minHour, startHour);
maxHour = Math.max(maxHour, endHour);
}
// Check lab time if it exists
if (c.lab && c.lab_index !== undefined) {
const labData = c.times[c.lab_index];
const startHour = Math.floor(labData.start / 60);
const endHour = Math.ceil((labData.start + labData.duration) / 60);
minHour = Math.min(minHour, startHour);
maxHour = Math.max(maxHour, endHour);
}
}
}
if (minHour === 24 || maxHour === 0) {
minHour = 8;
maxHour = 17;
}
const TIMES = [];
for (let hour = minHour; hour <= maxHour; hour++) {
TIMES.push(hour);
}
const svgHeight = (maxHour - minHour) * 60 + (2 * SVG_PADDING);
const svg = div.append("svg")
.attr("width", LEFT_MARGIN + (5 * DAY_WIDTH))
.attr("height", svgHeight);
svg.selectAll('line')
.data(TIMES)
.enter()
.append('line')
.style("stroke", "lightgrey")
.style("stroke-width", 1)
.attr('x1', 0).attr('y1', d => (d - minHour) * 60 + SVG_PADDING)
.attr('x2', LEFT_MARGIN + (5 * DAY_WIDTH)).attr('y2', d => (d - minHour) * 60 + SVG_PADDING);
svg.selectAll('text')
.data(TIMES)
.enter()
.append('text')
.attr('x', 0).attr('y', d => (d - minHour) * 60 + SVG_PADDING)
.attr('dy', 12)
.text(d => {
const h = (d > 12) ? d - 12 : d;
const ap = (d >= 12) ? "PM" : "AM";
return h + ":00" + ap;
})
.style("font-size", "10px");
// Create data for this faculty member's classes
const facultyData = [];
for (const c of scheduleData) {
if (c.faculty === faculty) {
for (const t in c.times) {
const entry = {...c.times[t]};
entry['name'] = c.course;
entry['faculty'] = c.faculty;
// Consolidate room and lab information
if (c.lab && t == c.lab_index) {
entry['room'] = `${c.room} (${c.lab})`;
} else {
entry['room'] = c.room;
}
facultyData.push(entry);
}
}
}
svg.selectAll('rect')
.data(facultyData)
.enter()
.append('rect')
.attr('x', d => (d.day - 1) * DAY_WIDTH + LEFT_MARGIN + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING)
.attr('width', DAY_WIDTH - 2 * DAY_PADDING)
.attr('height', d => d.duration)
.style('fill', d => intToHSL(getHashCode(d.faculty)))
.style('stroke', 'black');
const group = svg.selectAll('g')
.data(facultyData)
.enter()
.append('g');
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING)
.text(d => d.name)
.style('font-weight', 700)
.style("font-size", "12px");
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING + 15)
.text(d => d.room)
.style("font-size", "10px");
group.append('text')
.attr('dy', 12)
.attr('x', d => (d.day - 1) * DAY_WIDTH + TEXT_OFFSET + DAY_PADDING)
.attr('y', d => d.start - minHour * 60 + SVG_PADDING + 30)
.text(d => {
const fn = (t) => {
const hh = Math.floor(t / 60);
const mm = t % 60;
const h = (hh > 12) ? hh - 12 : hh;
const ap = (hh >= 12) ? "PM" : "AM";
return h + ":" + String(mm).padStart(2, '0') + ap;
};
return fn(d.start) + "-" + fn(d.start + d.duration);
})
.style("font-size", "10px");
}
}
// Initialize
document.addEventListener('DOMContentLoaded', function() {
// Set default values
document.getElementById('server-url').value = 'http://localhost:8000';
// Add event listener to delete session when page is closed
window.addEventListener('beforeunload', function() {
if (currentSessionId && !cleanupTriggered) {
cleanupTriggered = true;
const url = getBaseUrl();
navigator.sendBeacon(`${url}/schedules/${currentSessionId}/cleanup`);
}
});
// Add event listener to automatically check server status when URL changes
let statusCheckTimeout;
document.getElementById('server-url').addEventListener('input', function() {
// Clear previous timeout
clearTimeout(statusCheckTimeout);
// Set new timeout to check status after user stops typing
statusCheckTimeout = setTimeout(checkServerStatus, 500);
});
// Check initial status
checkServerStatus();
});
</script>
</body>
</html>