This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
/
libcal.js
281 lines (249 loc) · 9.86 KB
/
libcal.js
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
import api from '~/utils/libcal-schema'
import jsonpPromise from 'jsonp-promise'
import { _ } from 'lodash'
import moment from 'moment'
// Set formatting strings for Moment's calendar method
// http://momentjs.com/docs/#/customization/calendar
moment.updateLocale('en', {
calendar: {
lastDay: 'LT [yesterday]',
sameDay: 'LT',
nextDay: 'LT [tomorrow]',
lastWeek: 'LT [last] dddd',
nextWeek: 'LT dddd',
sameElse: 'LT ddd, MMM D'
},
longDateFormat: {
LT: 'h:mm a'
}
})
const libCal = {
timeFormat: 'h:mm a',
alreadyClosed: function (hours) {
if (hours === null) return false
// If multiple openings/closings, compare against last one for the day
let lastClosing = moment(hours.pop().to, libCal.timeFormat)
lastClosing = libCal.earlyMorningClose(lastClosing)
return moment().isSameOrAfter(lastClosing)
},
availableSlot: function (start, end) {
// QUESTION: Unique ID necessary for available slots?
return {
bookId: 'avail_randomString',
fromDate: start,
toDate: end,
isAvailable: true,
startTime: libCal.parseDate(start)
}
},
buildSchedule: (bookings, location, spaces, opening, closing) => {
let schedule = {}
bookings
// Only include reservations for requested spaces
.filter(b => _.includes(Object.values(spaces).map(s => s.id), b.eid))
// Add schedule object for each space
.forEach(b => {
// console.log('include?', _.includes(Object.values(spaces).map(s => s.id), b.eid), '|', Object.values(spaces).map(s => s.id), '|', b.eid)
// Use room name from schema
// let room = Object.entries(spaces).find(s => s[1].id === b.eid)[0]
let name = Object.entries(spaces).find(s => s[1].id === b.eid)[0]
schedule[name] = {
id: b.eid,
schedule: libCal.bookingsYeah(bookings, b.eid, opening, closing)
}
})
return schedule
},
requestedSpaces: (location, category) => {
const spacesInCategory = api.locations[location].categories[category].spaces
let spaces = []
spacesInCategory
.forEach(s => spaces.push({ 'id': s.id, 'name': s.room }))
if (category === 'studyrooms') spaces.reverse()
return spaces
},
bookingsYeah: function (bookings, room, openingTime, closingTime) {
const roomAvailability = _(bookings)
// Filter bookings by room, status(confirmed), and while open
.filter(function (booking, index, allBookings) {
const confirmed = booking.status === 'Confirmed'
const thisRoom = booking.eid === room
const whileOpen = moment(booking.fromDate).isSameOrAfter(openingTime) && moment(booking.toDate).isSameOrBefore(closingTime)
return thisRoom &&
confirmed &&
whileOpen
})
// Fill gaps between & pad bookings with available slots
.flatMap(function (booking, index, allBookings) {
const paddedBooking = [booking]
const prevIndex = index - 1
booking.startTime = libCal.parseDate(booking.fromDate)
// If first booking & starts after opening, pad before
if (index === 0 &&
moment(booking.fromDate).isAfter(openingTime)
) {
const availableNow = libCal.availableSlot(openingTime, booking.fromDate)
paddedBooking.splice(0, 0, availableNow)
}
// If not back-to-back with previous booking, pad before (aka between)
if (prevIndex > -1 &&
!moment(booking.fromDate).isSame(allBookings[prevIndex].toDate)
) {
const availableSlot = libCal.availableSlot(allBookings[prevIndex].toDate, booking.fromDate)
paddedBooking.splice(0, 0, availableSlot)
}
// If final booking...
if (index + 1 === allBookings.length) {
// Pad after if it falls short of closing
if (moment(booking.toDate).isBefore(moment(closingTime))) {
const availableTilClose = libCal.availableSlot(booking.toDate, closingTime)
availableTilClose.lastUp = true
paddedBooking.push(availableTilClose)
// Otherwise, mark it as running through to closing
} else {
booking.lastUp = true
}
}
return paddedBooking
})
// Now filter out past bookings
.filter(function (booking, index, allBookings) {
return moment().isSameOrBefore(booking.toDate)
})
.value()
// console.log('----------------\nALL THE THINGS!\n----------------\n', roomAvailability)
return roomAvailability
},
earlyMorningClose: function (closing) {
return moment(closing, libCal.timeFormat).isBefore(moment('6am', libCal.timeFormat)) ? closing.add(1, 'day') : closing
},
formatFutureOpening: function (datetime) {
return datetime === null ? 'no upcoming openings' : moment(datetime).calendar()
},
formatDate: function (date) {
return moment(date).format('Y-MM-DD')
},
formatTime: function (date) {
return moment(date).format(libCal.timeFormat)
},
getHours: function (axios, location, date, isDesk = false, jsonp = false) {
const requestDate = typeof date === 'undefined' ? '' : '&date=' + libCal.formatDate(date)
const locId = isDesk ? api.desks[location].hoursId : api.locations[location].hoursId
const url = api.endpoints.hours + locId + requestDate
if (jsonp) {
// If fetching updates from client, need to deal with JSONP
// -- LibCal doesn't set Access-Control-Allow-Origin header
return jsonpPromise(url).promise
} else {
// Non-issue when proxied through server on initial load (thanks Nuxt)
return axios.$get(url)
}
},
async getReservations (axios, location, date = false) {
const requestDate = date ? '&date=' + libCal.formatDate(date) : ''
const scope = 'lid=' + api.locations[location].id
const url = api.endpoints.spaces.bookings + scope + requestDate
// console.log('where to?', url)
let authorize = await axios.$post(api.endpoints.auth)
axios.setToken(authorize.access_token, 'Bearer')
return axios.$get(url)
},
nextDay: function (lastUpdated) {
return moment().isAfter(moment(lastUpdated), 'd')
},
async nextOpening (axios, location, isDesk = false, jsonp = false) {
var bigWinner = null
// Check today plus next 14 days
for (var i = 0; i < 15; i++) {
var dateToCheck = moment().add(i, 'days')
var openingTime = await libCal.openingTime(axios, location, libCal.formatDate(dateToCheck), isDesk, jsonp)
if (openingTime !== null) {
// Use openingTime to update existing moment and set hours & mins
bigWinner = dateToCheck.set({
'hour': openingTime.get('hour'),
'minute': openingTime.get('minute')
})
break
}
}
return bigWinner
},
async hoursForDate (axios, location, date, isDesk = false, jsonp = false) {
let feed = await libCal.getHours(axios, location, date, isDesk, jsonp)
const hours = typeof feed.locations[0].times.hours === 'undefined' ? null : feed.locations[0].times.hours
return hours
},
async openingTime (axios, location, date, isDesk = false, jsonp = false) {
const hours = await libCal.hoursForDate(axios, location, date, isDesk, jsonp)
// Copy hours since it gets emptied after using as function param
// -- TODO: Consider immutable.js or seamless-immutable
const hoursClone = hours !== null ? hours.slice(0) : null
// If dealing with today, ensure we're not already closed
if (moment().isSame(moment(date), 'd') && libCal.alreadyClosed(hoursClone)) {
return null
}
return hours !== null ? moment(hours[0].from, libCal.timeFormat) : null
},
async closingTime (axios, location, date, isDesk = false, jsonp = false) {
const hours = await libCal.hoursForDate(axios, location, date, isDesk, jsonp)
let closingTime = hours !== null ? moment(hours[0].to, libCal.timeFormat) : null
if (closingTime) {
// Account for early morning closings the following day
// -- LibCal only returns time, no date, so add a day to early morning closings for true comparisons
closingTime = libCal.earlyMorningClose(closingTime)
}
return closingTime
},
async openNow (axios, location, libcalStatus, hours, isDesk = false, jsonp = false) {
let status = {
current: 'closed',
timestamp: moment() // Use for caching results from LibCal API
}
if (hours) {
// Account for potential of multiple openings/closings in a given day
const isOpen = hours.find((hoursBlock) => {
return (moment().isBetween(moment(hoursBlock.from, libCal.timeFormat), moment(hoursBlock.to, libCal.timeFormat), null, []))
})
if (isOpen !== undefined) {
status.current = 'open'
status.change = moment(isOpen.to, libCal.timeFormat)
return status
}
}
let statusChange = await libCal.nextOpening(axios, location, isDesk, jsonp)
status.change = statusChange
if (libcalStatus === 'ByApp') {
status.current = 'by appointment'
}
return status
},
parseDate: function (date) {
let startDate = moment(date)
let startTime = {}
startTime.hour = startDate.format('h')
startTime.minute = startDate.format('mm')
startTime.meridiem = startDate.format('a')
return startTime
},
pastChange: function (changeTime) {
return moment().isSameOrAfter(moment(changeTime))
},
staleCache: function (lastUpdated) {
// Cache LibCal API response for at least 2 minutes
// -- test float against 1.9 to account for synchronous calls
// TODO: Return promise & join async/await bandwagon
return moment().diff(lastUpdated, 'minutes', true) >= 1.9
},
statusLabel: function (desk, status) {
// Reference desk is considered 'reserved' when open
if (desk === 'reference' && status === 'open') {
return 'reserved'
}
// Abbreviate the mouthful
if (status === 'by appointment') {
return 'by appt'
}
return status
}
}
export default libCal