Refine the rendering of myopac account summary table and dashboard
[sitka/overdrive-evergreen-opac.git] / src / overdrive.coffee
CommitLineData
8ebc3fff
SC
1# TODO memory leaks
2#
3# TODO Author/Title links could specify ebook filter
4#
5# TODO If logged in, could bypass place hold page and use action dialogue directly
6#
7# TODO Simple, cheap two-way data binding:
8# We could publish a partial request object as an abstract way of making
9# an API request, ie, od.$.triggerHandler 'od.metadata', id: id
10# Subscribe to same event to receive reply object, ie,
11# od.$.on 'od.metadata', (ev, reply) -> # do something with reply
12
13require.config
14
15 paths:
16 jquery: 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min'
17 'jquery-ui': 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min'
18 lodash: 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min'
19 moment: 'https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.5.1/moment.min'
20 cookies: 'https://cdnjs.cloudflare.com/ajax/libs/Cookies.js/0.3.1/cookies.min'
21 json: 'https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.0/json3.min'
22
23 waitSeconds: 120
24
25require [
26 'jquery'
27 'lodash'
28 'cookies'
29 'od_api'
2221a640 30 'od_config'
8ebc3fff
SC
31 'od_pages_opac'
32 'od_pages_myopac'
33 'od_action'
2221a640 34], ($, _, C, od, config) ->
8ebc3fff
SC
35
36 # Indicate the logged in status; the value is determined within document
37 # ready handler.
38 logged_in = false
39
40 # Various debugging functions; not used in production
41 log_page = -> console.log window.location.pathname
42 notify = (what) -> console.log "#{what} is in progress"
43 failed = (what) -> console.log "#{what} failed"
44 reload_page = -> window.location.reload true
45 replace_page = (href) -> window.location.replace href
46
47 # Query a search string of the current page for the value or existence of a
48 # property
49 search_params = (p) ->
895eed6f
SC
50 # Convert for example, '?a=1&b=2' to { a:1, b:2 }.
51 # Also, convert any pluses to spaces.
8ebc3fff 52 o =
cef83683 53 if xs = (decodeURIComponent window.location.search)?.split('?')?[1]?.split(/&|;/)
895eed6f 54 _.zipObject( x.replace(/\+/g, ' ').split('=') for x in xs )
8ebc3fff
SC
55 else
56 {}
57 # Return either the value of a specific property, whether the property
58 # exists, or the whole object
59 if arguments.length is 1 then o[p] or o.hasOwnProperty p else o
60
61
62 # Return an abbreviation of the pathname of the current page,
63 # eg, if window.location.pathname equals 'eg/opac/record' or
64 # 'eg/opac/record/123', then return 'record', otherwise return ''
65 page_name = ->
66 xs = window.location.pathname.match /eg\/opac\/(.+)/
67 if xs then xs[1].replace /\/\d+/, '' else ''
68
8ebc3fff
SC
69 # Routing table: map an URL pattern to a handler that will perform actions
70 # or modify areas on the screen.
71 routes =
72
73 # Scan through property names and execute the function value if the
74 # name pattern matches against the window.location.pathname, eg,
75 # routes.handle(). handle() does not try to execute itself. Returns a
76 # list of results for each handler that was executed. A result is
77 # undefined if no subscriptions to an OD service was needed.
78 handle: (p = window.location.pathname) ->
c6c9faec 79 for own n, v of @ when n isnt 'handle'
8ebc3fff
SC
80 v() if (new RegExp n).test p
81
82 'eg\/opac': ->
83
84 # Add a new dashboard to show total counts of e-items.
85 # Start the dashboard w/ zero counts.
86 $dash = $('#dash_wrapper')._dashboard()
87
88 od.$.on
89
90 # Set the dashboard counts to summarize the patron's account
91 'od.interests': (ev, x) -> $dash._dashboard
92 ncheckouts: x.nCheckouts
93 nholds: x.nHolds
94 nholdsready: x.nHoldsReady
95
96 # Decrement the dashboard counts because an item has been
97 # removed from the holds or checkout list
98 'od.hold.delete': -> $dash._dashboard nholds: -1
99 'od.checkout.delete': -> $dash._dashboard ncheckouts: -1
100
101 # Log out of EG if we are logged in and if an OD patron access
102 # token seems to have expired
103 'od.logout': (ev, x) ->
104 if x is 'od'
d0717859 105 window.location.replace '/eg/opac/logout' if logged_in
8ebc3fff
SC
106
107 'opac\/myopac': ( this_page = page_name() ) ->
108
109 # Add a new tab for e-items to the current page if it is showing a
110 # system of tabs
111 $('#acct_holds_tabs, #acct_checked_tabs')._etabs this_page, search_params 'e_items'
112 # Relabel history tabs if they are showing on current page
113 $('#tab_holds_history, #tab_circs_history')._tab_history()
114 return
115
116 'opac\/home': ->
117
118 # Signal that EG may have logged out
119 od.$.triggerHandler 'od.logout', 'eg' unless logged_in
120
121 'opac\/login': ->
122
123 # On submitting the login form, we initiate the login sequence with the
124 # username/password from the login form
125 $('form', '#login-form-box').one 'submit', ->
126 od.login
127 username: $('[name=username]').val()
128 password: $('[name=password]').val()
129
130
131 # TODO In order to perform OD login after EG login, we could
132 # automatically get the prefs page and scrape the barcode value,
133 # but in the general case, we would also need the password value
134 # that was previously submitted on the login page.
135
136 # We could scrape the barcode value from the prefs page by having it
137 # being parsed into DOM within an iframe (using an inscrutable sequence
138 # of DOM traversal). Unfortunately, it will reload script tags and
139 # make XHR calls unnecessarily.
140 #
141 # The alternative is to GET the prefs page and parse the HTML string
142 # directly for the barcode value, but admittedly, we need to use an
143 # inscrutable regex pattern.
144
145 # On the myopac account summary area, add links to hold list and
146 # checkout list of e-items
147 'myopac\/main': ( $table = $('.acct_sum_table') ) ->
148 return unless $table.length
149
c34f0459 150 $table._account_summary()
8ebc3fff
SC
151
152 od.$.on 'od.interests', (ev, x) ->
153
154 $table._account_summary
8ebc3fff
SC
155 n_checkouts: x.nCheckouts
156 n_holds: x.nHolds
157 n_ready: x.nHoldsReady
158
159 # Each time the patron's preferences page is shown, publish values that
160 # might have changed because the patron has edited them. Example
161 # scenario: patron changes email address on the prefs page and then
162 # places hold, expecting the place hold form to default to the newer
163 # address.
164 'myopac\/prefs': ->
165 $tr = $('#myopac_summary_tbody > tr')
166 em = $tr.eq(6).find('td').eq(1).text()
167 bc = $tr.eq(7).find('td').eq(1).text()
168 hl = $tr.eq(8).find('td').eq(1).text()
169 od.$.triggerHandler 'od.prefs', email_address:em, barcode:bc, home_library:hl
170
171 'opac\/results': (interested = {}) ->
172
173 # List of hrefs which correspond to Overdrive e-items
174 # TODO this list is duplicated in module od_pages_opac
175 hrefs = [
176 'a[href*="downloads.bclibrary.ca"]' # Used in OPAC
177 'a[href*="elm.lib.overdrive.com"]' # Used in XUL staff client
178 ]
179
180 # Prepare each row of the results table which has an embedded
181 # Overdrive product ID. A list of Overdrive product IDs is
182 # returned, which can be used to find each row directly.
183 ids = $(hrefs.join ',').closest('.result_table_row')._results()
184 return if ids?.length is 0
185
186 od.$.on
187
188 # When patron holds and checkouts become available...
189 'od.interests': (ev, x) ->
190
191 # Initiate request for each Overdrive product ID
192 for id in ids
8ebc3fff 193 od.apiAvailability id: id
e07737bf
SC
194 # If the user isn't logged in, the format list will
195 # always be found from Metadata
196 od.apiMetadata id: id unless logged_in
8ebc3fff
SC
197
198 # Cache the relationship between product IDs and patron
199 # holds and checkouts, ie, has the patron placed a hold on
200 # an ID or checked out an ID?
201 interested = x.byID
202
203 # Fill in format values when they become available
204 'od.metadata': (ev, x) -> $("##{x.id}")._results_meta x
205
206 # Fill in availability values when they become available
207 'od.availability': (ev, x) ->
208 $("##{x.id}")
209 ._results_avail x
210 ._replace_place_hold_link x, interested[x.id]?.type
211
e07737bf
SC
212 # Irregular logic warning: If the user is logged in, the
213 # format list might be found from Availability if the item
214 # is available for checkout, otherwise it will be found
215 # from Metadata.
216 if logged_in
217 if x.available then $("##{x.id}")._results_meta x else od.apiMetadata id: x.id
218
219
8ebc3fff
SC
220 'opac\/record': (interested = {}) ->
221
222 # Add an empty container of format and availability values
223 return unless id = $('div.rdetail_uris')._record()
224
225 od.$.on
226
227 # When patron holds and checkouts become available...
228 'od.interests': (ev, x) ->
229
230 # Initiate request for metadata and availability values when
e07737bf 231 od.apiMetadata id: id unless logged_in
8ebc3fff
SC
232 od.apiAvailability id: id
233
234 # Has the user placed a hold on an ID or checked out an ID?
235 interested = x.byID
236
237 # Fill in format values when they become available
238 'od.metadata': (ev, x) -> $("##{x.id}")._record_meta x
239
240 # Fill in availability values when they become available
241 'od.availability': (ev, x) ->
242 $("##{x.id}")._record_avail x
243 $('#rdetail_actions_div')._replace_place_hold_link x, interested[x.id]?.type
244
e07737bf
SC
245 if logged_in
246 if x.available then $("##{x.id}")._record_meta x else od.apiMetadata id: x.id
247
8ebc3fff
SC
248 # For the case where the patron is trying to place a hold if not logged
249 # in, there is a loophole in the Availability API; if using a patron
250 # access token and patron already has a hold on it, avail.actions.hold
251 # will still be present, falsely indicating that patron may place a
252 # hold, which will lead to a server error. The same situation will
253 # occur if patron has already checked out. It seems the OD server does
254 # not check the status of the item wrt the patron before generating the
255 # server response.
256 #
257 # To fix the problem, we will check if avail.id is already held or
258 # checked out, and if so, then go back history two pages so that
259 # original result list or record page is shown, with the proper action
260 # link generated when the page reloads.
261
262 # Replace the original Place Hold form with a table row to show
263 # available actions, either 'Check out' or 'Place hold', depending on
264 # whether the item is available or not, respectively.
265 #
266 # The following page handler does not replace the place_hold page, but
267 # is meant to be called by the place hold link.
268 # If the place_hold page is encountered, the handler will return
269 # without doing anything, because no id is passed in.
270 'opac\/place_hold': (id, interested = {}) ->
271 return unless id
272
273 $('#myopac_holds_div')._replace_title 'Place E-Item on Hold'
274 $('#myopac_checked_div')._replace_title 'Check out E-Item'
275
276 $('#holds_main, #checked_main, .warning_box').remove()
277
278 $div = $('<div id="#holds_main">')
279 ._holds_main() # Add an empty table
280 ._holdings_row id # Add an empty row
281 .appendTo $('#myopac_holds_div, #myopac_checked_div')
282
07895f87 283 # Fill in empty row when data becomes available
8ebc3fff
SC
284 od.$.on
285
286 'od.interests': (ev, x) ->
e07737bf 287
8ebc3fff
SC
288 # Has the user placed a hold on an ID or checked out an ID?
289 interested = x.byID
290
e07737bf
SC
291 $.when(
292 od.apiMetadata id: id
293 od.apiAvailability id: id
294 )
295 .then (x, y) ->
296
297 # Check if this patron has checked out or placed a hold on
298 # avail.id and if so, then go back two pages to the result list
299 # or record page. The page being skipped over is the login page
300 # that comes up because the user needs to log in before being
301 # able to see the place hold page. Thus, the logic is only
302 # relevant if the user has not logged in before trying to place
303 # a hold.
304 if interested[y.id]?.type
305 window.history.go -2
306
307 else
308 $("##{x.id}")._row_meta(x, 'thumbnail', 'title', 'author')
309 $("##{x.id}")._row_meta (if y.available then y else x), 'formats'
310
311 $("##{y.id}")
312 # Fill in availability column
313 ._holdings_row_avail y
314 # Auto-focus on place hold or checkout button
315 .find '.opac-button.hold, .opac-button.checkout'
316 .focus()
317 .end()
8ebc3fff
SC
318
319 'myopac\/holds': ->
320
321 # If we arrive here with an interested ID value, we are intending
322 # to place a hold on an e-item
323 if id = search_params 'interested'
324 return routes['opac\/place_hold'] id
325
326 # Rewrite the text in the warning box to distinguish physical items from e-items
327 unless search_params 'e_items'
328 $('.warning_box').text $('.warning_box').text().replace ' holds', ' physical holds'
329 return
330
331 return unless ($holds_div = $('#myopac_holds_div')).length
332
333 $holds_div._replace_title 'Current E-Items on Hold'
334
335 $('#holds_main, .warning_box').remove()
336
337 # Replace with an empty table for a list of holds for e-items
338 $div = $('<div id="#holds_main">')
339 ._holds_main()
340 .appendTo $holds_div
341
342 # Subscribe to notifications of relevant data objects
343 od.$.on
344
345 'od.interests': (ev, x) ->
346
347 # Focus on patron's hold interests, and if the search
348 # parameters say so, further focus on holds of items that
349 # are ready to be checked out
350 holds = x?.ofHolds
351 holds = _.filter(holds, (x) -> x.actions.checkout) if search_params 'available'
352
353 # Add an empty list of holds
354 ids = $div._holds_rows holds
355
356 # Try to get the metadata and availability values for
357 # this hold
358 for id in ids
359 od.apiMetadata id: id
360 od.apiAvailability id: id
361
362 # Add metadata values to a hold
363 'od.metadata': (ev, x) -> $("##{x.id}")._row_meta x, 'thumbnail', 'title', 'author', 'formats'
364 # Add availability values to a hold
365 'od.availability': (ev, x) -> $("##{x.id}")._holds_row_avail x
366
9669700c
SC
367 'od.hold.update': (ev, x) ->
368 x = x.holds[0]
369 $("##{x.reserveId}")._holds_row x
370
371 'od.hold.delete': (ev, id) -> $("##{id}").remove()
8ebc3fff
SC
372
373 'myopac\/circs': ->
374
375 # If we arrive here with an interested ID value, we are intending
376 # to checking out an e-item
377 if id = search_params 'interested'
378 return routes['opac\/place_hold'] id
379
3865fb23
SC
380 # If there is an error message embedded in the search parameters
381 # that resulted from an attempt at downloading content, show it in
382 # a floating notification box.
639929ef
SC
383 if code = search_params 'read_error'
384 $('<div>')._notify 'Error message', """
385 <p>Could not get content</p>
386 <div>Error code: #{code}</div>
387 <div>Reserve ID: #{search_params 'reserveid'}</div>
388 """
389 else if code = search_params 'ErrorCode'
3865fb23
SC
390 $('<div>')._notify 'Error message', """
391 <p>#{search_params 'ErrorDescription'}</p>
639929ef
SC
392 <div>Error code: #{code}</div>
393 <div>Details: #{search_params 'ErrorDetails'}</div>
3865fb23
SC
394 """
395
8ebc3fff
SC
396 # Rewrite the text in the warning box to distinguish physical items from e-items
397 unless search_params 'e_items'
398 $('.warning_box').text $('.warning_box').text().replace ' items', ' physical items'
399 return
400
401 return unless ($checked_div = $('#myopac_checked_div')).length
402
403 $checked_div._replace_title 'Current E-Items Checked Out'
404
405 $('#checked_main, .warning_box').remove()
406
407 # Build an empty table for a list of checkouts of e-items
408 $div = $('<div id="#checked_main">')
409 ._checkouts_main()
410 .appendTo $checked_div
411
412 # Subscribe to notifications of relevant data objects
413 od.$.on
414
415 'od.interests': (ev, x) ->
416
417 # Fill in checkout list
418 ids = $div._checkouts_rows x?.ofCheckouts
419
420 # Try to get metadata values for these checkouts
421 od.apiMetadata id: id for id in ids
422
423 # Add metadata values to a checkout
424 'od.metadata': (ev, x) -> $("##{x.id}")._row_meta x, 'thumbnail', 'title', 'author'
425
9669700c
SC
426 'od.checkout.update': (ev, x) ->
427 x = x.checkouts[0]
428 $("##{x.reserveId}")._row_checkout x
429
430 'od.checkout.delete': (ev, id) -> $("##{id}").remove()
8ebc3fff
SC
431
432 # Begin sequence after the DOM is ready...
433 $ ->
434
435 return if window.IAMXUL # Comment out to run inside XUL staff client
436
2221a640
SC
437 # Do not implement if hostname is blacklisted
438 return if config.blacklisted()
439
8ebc3fff
SC
440 # We are logged into EG if indicated by a cookie or if running
441 # inside XUL staff client.
442 logged_in = Boolean C('eg_loggedin') or window.IAMXUL
443
444 # Dispatch handlers corresponding to the current location
445 # and return immediately if none of them require OD services
446 return if _.every routes.handle() , (r) -> r is undefined
447
448 # Try to get library account info
9669700c 449 od.apiLibraryInfo()
8ebc3fff
SC
450
451 # If we are logged in, we 'compute' the patron's interests in product
452 # IDs; otherwise, we set patron interests to an empty object.
453 .then ->
454
455 # If logged in, ensure that we have a patron access token from OD
456 # before getting patron's 'interests'
457 if logged_in
458 od.login().then od.apiInterestsGet
459
460 # Otherwise, return no interests
461 # TODO should do the following in od_api module
462 else
463 interests = byID: {}
464 od.$.triggerHandler 'od.interests', interests
465 return interests
466
467 return
468 return