File size: 8,227 Bytes
2fcec7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/** A function that adds event listeners to a DOM objects. */
function addEventListeners() {
    document.getElementById("timeslot-form").addEventListener('submit', event => {
        event.preventDefault();
        addTimeSlot();
    });
}

/** Tells the server to add a timeslot for a tutor. */
function addTimeSlot() {
    return addTimeSlotHelper(window);
}

//Helper function for addTimeSlot, used for testing.
function addTimeSlotHelper(window) {
    var today = new Date();
    var sessionDate = document.getElementById('date');
    var startTime = document.getElementById('startTime');

    // Return early if user tried to schedule session in the past
    if (checkMinTime(today.getFullYear(), today.getMonth()+1, today.getDate(), today.getHours(), today.getMinutes(), sessionDate.value, startTime.value, window)) {
        return;
    }

    const params = new URLSearchParams();

    params.append('startTime', startTime.value);
    params.append('date', sessionDate.value);

    fetch('/manage-availability', {method: 'POST', body: params}).then((response) => {
        //if the tutor is not the current user or not signed in
        if(response.redirected) {
            window.location.href = response.url;
            alert("You must be signed in to edit availability.");
            return;
        }
        window.location.href = "/manage-availability.html";
    });
}

// Checks if the tutor tried to add a timeslot with a time in the past, returns true if they did
function checkMinTime(year, month, day, hour, minute, sessionDate, startTime, window) {
    // Add 0's when month and day are less than 10 so it matches HTML value format
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }
    var yearMonthDay = year + '-' + month + '-' + day;
    var startTimeArr = startTime.split(':');

    // Add check to see if user-inputted time is in the past
    if (yearMonthDay == sessionDate) {
        if (parseInt(startTimeArr[0]*60, 10) + parseInt(startTimeArr[1], 10) < hour*60 + minute) {
            alert("You cannot add an available timeslot in the past!");
            return true;
        }
    }

    return false;
}

// Sets the minimum date and time that the user can enter into the timeslot form
function setMinDate() {
    var today = new Date();
    var year = today.getFullYear();
    var month = today.getMonth() + 1; 
    var day = today.getDate(); 
    setMinDateHelper(document, year, month, day);
}

// Helper function for setMinDate, used for testing
function setMinDateHelper(document, year, month, day) {
    // Add a 0 before the month and day if they're less than 10 so the min value is properly set
    if (month < 10) {
        month = "0" + month;
    }
    if (day < 10) {
        day = "0" + day;
    }

    document.getElementById('date').min = year + '-' + month + '-' + day;
}

// Fetches info used to create the calendar
function fetchTimeslotInfo() {
    fetchTimeslotInfoHelper(window);
}

// Helper function for fetchCalendarInfo, used for testing
function fetchTimeslotInfoHelper(window) {
    fetch('/manage-availability', {method: 'GET'}).then((response) => {
        //if the student is not the current user or not signed in
        if(response.redirected) {
            window.location.href = response.url;
            alert("You must be signed in to manage availability.");
            return [];
        }
        return response.json();
    }).then((timeslots) => {
        const container = document.getElementById('calendar');
        
        if(timeslots.error) {
            var message = document.createElement("p");
            message.innerText = timeslots.error;
            document.getElementById('calendar').appendChild(message);
            return;
        }

        // Don't create a calendar if there are no available timeslots
        if (timeslots === undefined || timeslots.length == 0) {
            var errorMessage = document.createElement("p");
            errorMessage.innerText = "This user has not set any available timeslots.";
            container.appendChild(errorMessage);
            return;
        }

        createCalendar(timeslots, container);
    });
}

/** Creates a calendar with the Charts API and renders it on the page  */
function createCalendar(timeslots, container) {
    const chart = new google.visualization.Timeline(container);

    const dataTable = new google.visualization.DataTable();
    dataTable.addColumn({type: 'string', id: 'Date'});
    dataTable.addColumn({type: 'date', id: 'Start'});
    dataTable.addColumn({type: 'date', id: 'End'});

    // Sort timeslots in chronological order
    sortTimeslots(timeslots);
    
    for (var slot of timeslots) {
        // Add 1 to the month so it displays correctly (January's default value is 0, February's is 1, etc.)
        var date = (slot.date.month+1) + '/' + slot.date.dayOfMonth + '/' + slot.date.year;
        dataTable.addRow([
            date, asDate(slot.start), asDate(slot.end)
        ]);
    }

    // Have timeline span 24 hours regardless of what's scheduled
    var min = new Date();
    min.setHours(0);
    var max = new Date();
    max.setHours(24);

    const options = {
        width: 1000,
        height: 300,
        timeline: { singleColor: '#437f97' },
        hAxis: {
            minValue: min,
            maxValue: max
        }
    };

    google.visualization.events.addListener(chart, 'select', function() {
        var selection = chart.getSelection()[0];
        if (selection) {
            deleteSession(dataTable, selection);
        }
    });

    chart.draw(dataTable, options);
}

// Sorts all available time slots in chronological order
function sortTimeslots(timeslots) {
    timeslots.sort(function(a, b) {
        return (a.date.year + a.date.month/12 + a.date.dayOfMonth/365) - (b.date.year + b.date.month/12 + b.date.dayOfMonth/365);
    });
}

/** Function to tell the server to delete an available time slot for tutor.  */
function deleteSession(dataTable, selection) {
    // Add confirmation popup in case user accidentally clicked on time slot
    var deleteSession = confirm("Delete available time slot?");

    if (deleteSession) {
        var start = asMinutes(dataTable.getValue(selection.row, 1));
        var end = asMinutes(dataTable.getValue(selection.row, 2));
        var date = dataTable.getValue(selection.row, 0).split('/');
        const params = new URLSearchParams();
        params.append('year', date[2]);
        params.append('month', date[0]-1);
        params.append('day', date[1]);
        params.append('start', start);
        params.append('end', end);

        fetch('/delete-availability', {method: 'POST', body: params}).then((response) => {
            //if the tutor is not the current user or not signed in
            if(response.redirected) {
                window.location.href = response.url;
                alert("You must be signed in to edit availability.");
                return;
            }
        }).then(location.reload());
    }
}

/**
 * Converts "minutes since midnight" into a JavaScript Date object.
 * Code used from the week 5 unit testing walkthrough of Google's STEP internship trainings
 */
function asDate(minutes) {
  const date = new Date();
  date.setHours(Math.floor(minutes / 60));
  date.setMinutes(minutes % 60);
  return date;
}

// Converts a JavaScript Date object into "minutes since midnight"
function asMinutes(date) {
    return date.getHours()*60 + date.getMinutes();
}

google.charts.load('current', {'packages': ['timeline']});
google.charts.setOnLoadCallback(fetchTimeslotInfo);