Use action dialogue to guide download link process
[sitka/overdrive-evergreen-opac.git] / src / od_action.coffee
1 # TODO cannot auto-focus on close button of action dialog
2 # probably because it needs to be done asynchronously using setTimeout
3 #
4 define [
5         'jquery'
6         'lodash'
7         'json'
8         'od_api'
9         'jquery-ui'
10 ], ($, _, json, od) ->
11
12         # Load a CSS file related to our use of the jqueryui dialog widget.
13         # We manually load the file in order to avoid modifying any .tt2 files.
14         do (url = '//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.min.css') ->
15                 link = document.createElement('link')
16                 link.type = 'text/css'
17                 link.rel  = 'stylesheet'
18                 link.href = url
19                 document.getElementsByTagName('head')[0].appendChild(link)
20
21         # Return an abbreviation of the pathname of the current page,
22         # eg, if window.location.pathname equals 'eg/opac/record' or
23         # 'eg/opac/record/123', then return 'record', otherwise return ''
24         brief_name = ->
25                 xs = window.location.pathname.match /eg\/opac\/(.+)/
26                 if xs then xs[1].replace /\/\d+/, '' else ''
27         # TODO also defined in od_page_rewrite, but we don't want this module to
28         # depend on that module, because it depends on this module.
29
30         # Pluck out a sensible message from the reply to an action request
31         responseMessage = (x) -> (json.parse x.responseText).message
32
33         # Customize the dialog widget to guide a user through the intention of
34         # making a transaction
35         #
36         # Usage: $('<div>').dialogAction action: action, scenario: scenario
37         #
38         $.widget 'ui.dialogAction', $.ui.dialog,
39                 options:
40                         draggable: false
41                         resizable: true
42                         modal: true
43                         buttons: [
44                                 {
45                                         text: 'Yes'
46                                         click: (ev) ->
47                                                 ev.stopPropagation()
48                                                 $(@).dialogAction 'yes_action'
49                                                 return
50                                 }
51                                 {
52                                         text: 'No'
53                                         click: (ev) ->
54                                                 ev.stopPropagation()
55                                                 $(@).dialogAction 'autoclose'
56                                                 return
57                                 }
58                         ]
59
60                 # On create, perform custom positioning, and show custom title and
61                 # body.  When the dialog finally closes, destroy it.
62                 _create: ->
63
64                         intent = @options._scenario?.intent
65                         position = @options._action?._of
66
67                         # Text of Yes/No buttons in the intent scenario may be overridden
68                         if intent
69                                 ob = @options.buttons
70                                 ib = intent.buttons
71                                 ob[0].text = ib?[0] or 'Yes'
72                                 ob[1].text = ib?[1] or 'No'
73
74                         # Position of dialog box may be overridden
75                         @options.position = of: position, at: 'top', my: 'top' if position
76
77                         @_super()
78
79                         # On creation, dialog message may be overidden by the intent scenario
80                         f = @options._scenario.intent?.body
81                         @set_message 'intent', not intent, if $.isFunction f then f @options._action?._name else undefined
82
83                         @_on 'dialogactionclose': -> @_destroy()
84
85                 # Depending on the given scenario, the title and body of the dialog
86                 # screen may be set, and the close button may be shown or hidden.
87                 set_message: (scenario, close, body, title) ->
88                         @_close_button close
89                         # Get the scenario properties
90                         s = @options._scenario[scenario]
91                         # The body is a text string specified as an argument or as the
92                         # scenario's body property, or it defaults to a progress bar.
93                         @element.empty().append body or s?.body or $('<div>').progressbar value: false
94                         # The title is a text string specified as an argument or as the
95                         # scenario's title property, or it defaults to the etitle of the
96                         # attached action object.
97                         @option 'title', title or s?.title or @options._action._of._etitle()
98                         return @
99
100                 autoclose: ->
101                         @_on 'dialogactionclose': @options._scenario?.intent?.reroute or ->
102                         @close()
103                         return @
104
105                 # Respond to the Yes button by going ahead with the intended action
106                 yes_action: ->
107
108                         # At this point, dialog buttons are turned off.
109                         @option 'buttons', []
110
111                         # Define functions to close dialogue box and reroute to another window
112                         onclose_maybe_reroute = =>
113                                 @_on 'dialogactionclose': @options._scenario?.done?.reroute or ->
114                         close = =>
115                                 onclose_maybe_reroute()
116                                 @close()
117
118                         # Make an API call
119                         action = @options._action
120                         progress = => @set_message 'progress', true
121                         od.api action.href, action.method, fields: $('form', @element).serializeArray(), progress
122
123                         # Re-use the dialog to show notifications with a close button
124                         .then(
125                                 (x) =>
126                                         f = @options._scenario.done?.body
127                                         @set_message 'done', true, if $.isFunction f then f x else undefined
128                                         window.setTimeout close, @options._scenario.done?.timeout or 2000
129                                 (x) => @set_message 'fail', true, responseMessage x
130                         )
131
132                         # On done and when the user closes the dialog, reroute the page
133                         .done onclose_maybe_reroute
134
135                         return @
136
137                 # Show and focus, or hide, the dialog close button.
138                 _close_button: (show) ->
139                         $button = @element.parent().find('.ui-dialog-titlebar-close')
140                         if show then $button.show().focus() else $button.hide()
141                         return @
142
143
144         # Map action names to labels
145         # TODO also use this mapping in scenarios
146         Labels =
147                 hold: 'Place hold'
148                 addSuspension: 'Suspend'
149                 releaseSuspension: 'Activate'
150                 removeHold: 'Cancel'
151                 checkout: 'Check out'
152                 earlyReturn: 'Return title'
153                 format: 'Select format'
154
155
156         # We define custom jQuery extensions to perform the actions defined by the
157         # Labels object.  The main role of each of these extensions is to build a
158         # scenario object that specifies the layout and behaviour of an instance of
159         # the action dialog widget.  The specification is dependent on the content
160         # of a given action object and hence the scenario object must be built
161         # dynamically.
162         #
163         $.fn.extend
164
165                 # Build a dialog to place a hold
166                 _hold: (action) ->
167
168                         scenario =
169                                 intent:
170                                         body: $('<div>')._action_fields action.fields
171                                         buttons: [ 'Place hold', 'Cancel' ]
172                                         # TODO clicking cancel should return to search results, not
173                                         # to rerouted page
174                                         reroute: -> window.history.back()
175                                 done:
176                                         body: 'Hold was successfully placed. Close this box to be redirected to your holds list.'
177                                         reroute: -> window.location.replace '/eg/opac/myopac/holds?e_items'
178                                 fail: body: 'Hold was not placed. There may have been a network or server problem. Please try again.'
179
180                         @dialogAction _scenario: scenario, _action: action
181
182                 # Build a dialog to cancel a hold
183                 _removeHold: (action) ->
184
185                         scenario =
186                                 intent: body: 'Are you sure you want to cancel this hold?'
187                                 done: body: 'Hold was successfully cancelled.'
188                                 fail: body: 'Hold was not cancelled. There may have been a network or server problem. Please try again.'
189
190                         @dialogAction _scenario: scenario, _action: action
191
192                 # Build a dialog to suspend a hold
193                 _addSuspension: (action) ->
194
195                         scenario =
196                                 intent:
197                                         body: $('<div>')._action_fields action.fields
198                                         buttons: [ 'Suspend', 'Cancel' ]
199                                 done: body: 'Hold was successfully suspended'
200                                 fail: body: 'Hold was not suspended. There may have been a network or server problem. Please try again.'
201
202                         @dialogAction _scenario: scenario, _action: action
203
204                 # Build a dialog to release a suspension
205                 _releaseSuspension: (action) ->
206
207                         scenario =
208                                 intent: body: 'Are you sure you want this hold to activate again?'
209                                 done:
210                                         body: 'Suspension was successfully released. The page will reload to update your account status.'
211                                         reroute: -> window.location.reload true
212                                 fail: body: 'Suspension was not released. There may have been a network or server problem. Please try again.'
213
214                         @dialogAction _scenario: scenario, _action: action
215
216                 # Build a dialog to checkout a title
217                 _checkout: (action) ->
218
219                         scenario =
220                                 intent:
221                                         body: $('<div>')._action_fields action.fields
222                                         buttons: [ 'Check out', 'Cancel' ]
223                                         reroute: ->
224                                                 # if at placehold page, go back; otherwise, stay on same page
225                                                 # TODO place_hold no longer relevant
226                                                 window.history.back() if brief_name() is 'place_hold'
227                                 done:
228                                         body: 'Title was successfully checked out. Close this page to be redirected to your checkouts list.'
229                                         reroute: -> window.location.replace '/eg/opac/myopac/circs?e_items'
230                                 fail: body: 'Title was not checked out. There may have been a network or server problem. Please try again.'
231
232                         @dialogAction _scenario: scenario, _action: action
233
234                 # Build a dialog to select a format of a title
235                 _format: (action) ->
236
237                         scenario =
238                                 intent:
239                                         body: $('<div>')._action_fields action.fields
240                                         buttons: [ 'Select format', 'Cancel' ]
241                                 done: body: 'Format was successfully selected.'
242                                 fail: body: 'Format was not selected. There may have been a network or server problem. Please try again.'
243
244                         @dialogAction _scenario: scenario, _action: action
245
246                 # Build a dialog to return a title early
247                 _earlyReturn: (action) ->
248
249                         scenario =
250                                 intent: body: 'Are you sure you want to return this title before it expires?'
251                                 done: body: 'Title was successfully returned.'
252                                 fail: body: 'Title was not returned. There may have been a network or server problem. Please try again.'
253
254                         @dialogAction _scenario: scenario, _action: action
255
256                 _downloadLink: (action) ->
257
258                         scenario =
259                                 intent: body: (formatType) ->
260                                         if formatType is 'ebook-overdrive'
261                                                 'Download content to read in the browser?'
262                                         else
263                                                 'Download content for an e-book reader?'
264                                 done:
265                                         body: (x) ->
266                                                 $ """
267                                                 <div>Content is ready.</div>
268                                                 <a href=#{x.links.contentlink.href}>Right-click to download in a new tab or window.</a>
269                                                 <div>The link is valid for the next 60 seconds.</div>
270                                                 """
271                                         timeout: 59000
272                                 fail: body: 'could not download'
273
274                         @dialogAction _scenario: scenario, _action: action
275
276                 # Build action buttons and dialogs given specifications as follows.
277                 # actions = [ { name: { href: h, method: m, fields: [ { name: n, value: v, options: [...] } ] } ]
278                 _actions: (actions, id) ->
279
280                         tpl = _.template """
281                         <div>
282                                 <a href="<%= href %>" class="opac-button <%= action_name %>" style="margin-top: 0px; margin-bottom: 0px"><%= label %></a>
283                         </div>
284                         """
285
286                         # Find the related row
287                         $tr = @closest('tr')
288
289                         $buttons = for n, action of actions
290
291                                 # Extend the action object with context
292                                 $.extend action, _of: $tr, _name: n, _id: id
293
294                                 # Create a button for this action
295                                 $ tpl href: action.href, action_name: n, label: Labels?[n] or n
296
297                                 # On clicking the button, build a new dialog using the extended action object
298                                 .on 'click', action, (ev) ->
299                                         ev.preventDefault()
300                                         $('<div>')['_' + ev.data._name] ev.data
301                                         return false
302
303                         @empty().append $buttons
304
305                 # Build a form of input fields out of a list of action fields
306                 _action_fields: (fields) ->
307
308                         $('<form>')
309                         ._action_field_hidden  _.where(fields, name: 'reserveId')[0]
310                         ._action_field_email   _.where(fields, name: 'emailAddress')[0]
311                         ._action_field_radio   _.where(fields, name: 'formatType')[0]
312                         ._action_field_suspend _.where(fields, name: 'suspensionType')[0]
313                         ._action_field_date    _.where(fields, name: 'numberOfDays')[0]
314
315                         # Show a date field only if suspensionType of indefinite is selected
316                         .on 'click', '[name=suspensionType]', (ev) ->
317                                 $input = $('[name=numberOfDays]')
318                                 switch @defaultValue
319                                         when 'limited'    then $input.show()
320                                         when 'indefinite' then $input.hide()
321
322                         .on 'submit', (ev) ->
323                                 $input = $('[name=numberOfDays]')
324
325                 # Build a date field and initially hide it
326                 _action_field_date: (field) ->
327
328                         return @ unless field
329
330                         $input = $ """
331                         <input type="date" name="#{field.name}" value="#{field.value}" />
332                         """
333                         @append $input.hide()
334
335                 # Build a hidden input
336                 _action_field_hidden: (field) ->
337
338                         return @ unless field
339
340                         @append """
341                         <input type="hidden" name="#{field.name}" value="#{field.value}" />
342                         """
343
344                 # Build an email input
345                 _action_field_email: (field) ->
346
347                         return @ unless field
348
349                         $input = $ """
350                         <div>
351                                 You will be notified by email when a copy becomes available
352                         </div>
353                         <div>
354                                 <label>Email address: <input type="email" name="#{field.name}" value="#{field.value}" />
355                                 </label>
356                         </div>
357                         """
358                         $input.find('input').prop 'required', true unless Boolean field.optional
359
360                         @append $input
361
362                 # Build a group of radio buttons
363                 _action_field_radio: (field) ->
364
365                         return @ unless field
366
367                         # If one of the format types is ebook reader, omit it from the
368                         # list, because it is not a downloadable type
369                         _.remove field.options, (f) -> f is 'ebook-overdrive'
370
371                         # A hint specific to whether format types are optional or not is added to the form
372                         hint = switch
373                                 when field.options.length is 1 then """
374                                         <div>Only one #{field.name} is available and it has been selected for you</div>
375                                         """
376                                 when Boolean field.optional then """
377                                         <div>You may select a #{field.name} at this time</div>
378                                         """
379                                 else """
380                                         <div>Please select one of the available #{field.name}s</div>
381                                         """
382                         inputs = for v in field.options
383                                 $x = $ """
384                                 <div>
385                                         <input type="radio" name="#{field.name}" value="#{v}" />#{od.labels v}
386                                 </div>
387                                 """
388                                 $y = $x.find 'input'
389                                 $y.prop('required', true) unless Boolean field.optional
390                                 $y.prop('checked', true) unless field.options.length > 1
391                                 $x
392
393                         @append hint
394                         .append inputs
395
396                 _action_field_suspend: (field) ->
397
398                         return @ unless field
399
400                         label =
401                                 indefinite: 'Suspend this hold indefinitely'
402                                 limited: 'Suspend this hold for a limited time'
403
404                         inputs = for v in field.options
405                                 $x = $ """
406                                 <div><label>
407                                         <input type="radio" name="#{field.name}" value="#{v}" /> #{label[v]}
408                                 </label></div>
409                                 """
410                                 $y = $x.find 'input'
411                                 $y.prop('required', true) unless Boolean field.optional
412                                 $y.prop('checked', true) if v is 'indefinite'
413                                 $x
414
415                         @append inputs
416
417                 # Build format buttons given specifications as follows.
418                 # formats = [ { formatType: type, linkTemplates: { downloadLink: { href: href } } } ]
419                 #
420                 # We need to get from a download link to make the download request,
421                 # receive a content link as a response, and then perform a 'normal' get
422                 # of the content link.  A complexity is to handle the error responses.
423                 #
424                 # TODO The initial get could fail, in which case, the errorpageurl
425                 # will be used to convey the failure status as a query string. We
426                 # will redirect the error page to the current page and we recognize
427                 # the error condition by analysing the query parameters.
428                 #
429                 # TODO Another error condition could occur if an Overdrive Read
430                 # ebook is attempted to be downloaded.  Here, the odreadauthurl
431                 # will be used as a redirect location. We will also redirect to the
432                 # current page and hopefully will be able to discern the state and
433                 # show it accordingly.
434                 _formats: (formats, id) ->
435                         return @ unless formats
436
437                         tpl = _.template """
438                         <div>
439                                 <a href="<%= href %>" class="opac-button" style="margin-top: 0px; margin-bottom: 0px"><%= label %></a>
440                         </div>
441                         """
442
443                         $tr = @closest('tr')
444
445                         $buttons = for format in formats
446                                 {
447                                         formatType: n
448                                         linkTemplates:
449                                                 downloadLink:
450                                                         href: href
451                                                         type: type
452                                 } = format
453
454                                 x = encodeURIComponent window.location.href
455                                 href = href
456                                         .replace /\{errorpageurl\}/, x
457                                         .replace /\{odreadauthurl\}/, x
458
459                                 action = format.linkTemplates.downloadLink
460                                 $.extend action, _of: $tr, _name: n, _id: id, href: href
461
462                                 # Create a button for this action
463                                 $ tpl href: href, label: "Download #{od.labels n}"
464
465                                 # On clicking the button, build a new dialog using the extended action object
466                                 .on 'click', action, (ev) ->
467                                         ev.preventDefault()
468                                         $('<div>')['_downloadLink'] ev.data
469                                         return false
470
471                         @empty().append $buttons
472
473
474                 _notify: (title, text) ->
475
476                         @dialog
477                                 position: my: 'top', at: 'right top'
478                                 minHeight: 0
479                                 autoOpen: true
480                                 draggable: false
481                                 resizable: true
482                                 show: effect: 'slideDown'
483                                 hide: effect: 'slideUp'
484                                 close: -> $(@).dialog 'destroy'
485                                 title: title
486
487                         .text text
488
489                 # Get the title of e-item in a row context
490                 _etitle: -> @find('.title a').text()