RT26084: Hide Suspend button on suspended holds
[sitka/overdrive-evergreen-opac.git] / src / od_action.coffee
CommitLineData
8ebc3fff
SC
1# TODO cannot auto-focus on close button of action dialog
2# probably because it needs to be done asynchronously using setTimeout
3#
4define [
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()
f1fb1882 55 $(@).dialogAction 'autoclose'
8ebc3fff
SC
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
f1fb1882
SC
80 f = @options._scenario.intent?.body
81 @set_message 'intent', not intent, if $.isFunction f then f @options._action?._name else undefined
8ebc3fff
SC
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.
f46ca691 87 set_message: (scenario, close, body, title) ->
8ebc3fff 88 @_close_button close
f46ca691
SC
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()
8ebc3fff
SC
98 return @
99
f1fb1882
SC
100 autoclose: ->
101 @_on 'dialogactionclose': @options._scenario?.intent?.reroute or ->
8ebc3fff
SC
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
f1fb1882
SC
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
8ebc3fff
SC
118 # Make an API call
119 action = @options._action
8546cdf5
SC
120 progress = => @set_message 'progress', true
121 od.api action.href, action.method, fields: $('form', @element).serializeArray(), progress
8ebc3fff
SC
122
123 # Re-use the dialog to show notifications with a close button
124 .then(
f1fb1882
SC
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
8ebc3fff
SC
129 (x) => @set_message 'fail', true, responseMessage x
130 )
131
132 # On done and when the user closes the dialog, reroute the page
f1fb1882 133 .done onclose_maybe_reroute
8ebc3fff
SC
134
135 return @
136
f1fb1882
SC
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 @
8ebc3fff
SC
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 #
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
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.'
8ebc3fff
SC
253
254 @dialogAction _scenario: scenario, _action: action
255
f1fb1882 256 _downloadLink: (action) ->
8ebc3fff 257
f1fb1882
SC
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'
8ebc3fff 273
f1fb1882 274 @dialogAction _scenario: scenario, _action: action
8ebc3fff
SC
275
276 # Build action buttons and dialogs given specifications as follows.
277 # actions = [ { name: { href: h, method: m, fields: [ { name: n, value: v, options: [...] } ] } ]
53ade1ec 278 _actions: (actions, id, suspended) ->
8ebc3fff
SC
279
280 tpl = _.template """
281 <div>
07895f87 282 <a href="<%= href %>" class="opac-button <%= action_name %>" style="margin-top: 0px; margin-bottom: 0px"><%= label %></a>
8ebc3fff
SC
283 </div>
284 """
285
286 # Find the related row
287 $tr = @closest('tr')
288
289 $buttons = for n, action of actions
290
53ade1ec 291 unless suspended? and n is 'addSuspension'
8ebc3fff 292
53ade1ec
JD
293 # Extend the action object with context
294 $.extend action, _of: $tr, _name: n, _id: id
8ebc3fff 295
53ade1ec
JD
296 # Create a button for this action
297 $ tpl href: action.href, action_name: n, label: Labels?[n] or n
298
299 # On clicking the button, build a new dialog using the extended action object
300 .on 'click', action, (ev) ->
301 ev.preventDefault()
302 $('<div>')['_' + ev.data._name] ev.data
303 return false
8ebc3fff
SC
304
305 @empty().append $buttons
306
307 # Build a form of input fields out of a list of action fields
308 _action_fields: (fields) ->
309
310 $('<form>')
311 ._action_field_hidden _.where(fields, name: 'reserveId')[0]
312 ._action_field_email _.where(fields, name: 'emailAddress')[0]
313 ._action_field_radio _.where(fields, name: 'formatType')[0]
314 ._action_field_suspend _.where(fields, name: 'suspensionType')[0]
315 ._action_field_date _.where(fields, name: 'numberOfDays')[0]
316
317 # Show a date field only if suspensionType of indefinite is selected
318 .on 'click', '[name=suspensionType]', (ev) ->
319 $input = $('[name=numberOfDays]')
320 switch @defaultValue
321 when 'limited' then $input.show()
322 when 'indefinite' then $input.hide()
323
324 .on 'submit', (ev) ->
325 $input = $('[name=numberOfDays]')
326
327 # Build a date field and initially hide it
328 _action_field_date: (field) ->
329
330 return @ unless field
331
332 $input = $ """
333 <input type="date" name="#{field.name}" value="#{field.value}" />
334 """
335 @append $input.hide()
336
337 # Build a hidden input
338 _action_field_hidden: (field) ->
339
340 return @ unless field
341
342 @append """
343 <input type="hidden" name="#{field.name}" value="#{field.value}" />
344 """
345
346 # Build an email input
347 _action_field_email: (field) ->
348
349 return @ unless field
350
351 $input = $ """
352 <div>
353 You will be notified by email when a copy becomes available
354 </div>
355 <div>
356 <label>Email address: <input type="email" name="#{field.name}" value="#{field.value}" />
357 </label>
358 </div>
359 """
360 $input.find('input').prop 'required', true unless Boolean field.optional
361
362 @append $input
363
364 # Build a group of radio buttons
365 _action_field_radio: (field) ->
366
367 return @ unless field
368
369 # If one of the format types is ebook reader, omit it from the
370 # list, because it is not a downloadable type
371 _.remove field.options, (f) -> f is 'ebook-overdrive'
372
373 # A hint specific to whether format types are optional or not is added to the form
374 hint = switch
375 when field.options.length is 1 then """
376 <div>Only one #{field.name} is available and it has been selected for you</div>
377 """
378 when Boolean field.optional then """
379 <div>You may select a #{field.name} at this time</div>
380 """
381 else """
382 <div>Please select one of the available #{field.name}s</div>
383 """
384 inputs = for v in field.options
385 $x = $ """
386 <div>
387 <input type="radio" name="#{field.name}" value="#{v}" />#{od.labels v}
388 </div>
389 """
390 $y = $x.find 'input'
391 $y.prop('required', true) unless Boolean field.optional
392 $y.prop('checked', true) unless field.options.length > 1
393 $x
394
395 @append hint
396 .append inputs
397
398 _action_field_suspend: (field) ->
399
400 return @ unless field
401
402 label =
403 indefinite: 'Suspend this hold indefinitely'
404 limited: 'Suspend this hold for a limited time'
405
406 inputs = for v in field.options
407 $x = $ """
408 <div><label>
409 <input type="radio" name="#{field.name}" value="#{v}" /> #{label[v]}
410 </label></div>
411 """
412 $y = $x.find 'input'
413 $y.prop('required', true) unless Boolean field.optional
414 $y.prop('checked', true) if v is 'indefinite'
415 $x
416
417 @append inputs
418
f1fb1882
SC
419 # Build format buttons given specifications as follows.
420 # formats = [ { formatType: type, linkTemplates: { downloadLink: { href: href } } } ]
421 #
422 # We need to get from a download link to make the download request,
423 # receive a content link as a response, and then perform a 'normal' get
424 # of the content link. A complexity is to handle the error responses.
9b152782
SC
425 #
426 # TODO The initial get could fail, in which case, the errorpageurl
427 # will be used to convey the failure status as a query string. We
428 # will redirect the error page to the current page and we recognize
429 # the error condition by analysing the query parameters.
430 #
431 # TODO Another error condition could occur if an Overdrive Read
432 # ebook is attempted to be downloaded. Here, the odreadauthurl
433 # will be used as a redirect location. We will also redirect to the
434 # current page and hopefully will be able to discern the state and
435 # show it accordingly.
f1fb1882
SC
436 _formats: (formats, id) ->
437 return @ unless formats
438
439 tpl = _.template """
440 <div>
441 <a href="<%= href %>" class="opac-button" style="margin-top: 0px; margin-bottom: 0px"><%= label %></a>
442 </div>
443 """
444
445 $tr = @closest('tr')
446
447 $buttons = for format in formats
448 {
449 formatType: n
450 linkTemplates:
451 downloadLink:
452 href: href
453 type: type
454 } = format
8ebc3fff 455
f1fb1882 456 href = href
639929ef
SC
457 .replace /\{errorpageurl\}/, encodeURIComponent window.location.href
458 .replace /\{odreadauthurl\}/, encodeURIComponent "#{window.location.href}&reserveid=[RESERVE_ID]&read_error=[READ_ERROR]"
8ebc3fff 459
f1fb1882
SC
460 action = format.linkTemplates.downloadLink
461 $.extend action, _of: $tr, _name: n, _id: id, href: href
462
463 # Create a button for this action
464 $ tpl href: href, label: "Download #{od.labels n}"
465
466 # On clicking the button, build a new dialog using the extended action object
467 .on 'click', action, (ev) ->
468 ev.preventDefault()
469 $('<div>')['_downloadLink'] ev.data
470 return false
471
472 @empty().append $buttons
8ebc3fff
SC
473
474
475 _notify: (title, text) ->
476
477 @dialog
3865fb23 478 #position: my: 'top', at: 'right top'
8ebc3fff
SC
479 minHeight: 0
480 autoOpen: true
481 draggable: false
482 resizable: true
483 show: effect: 'slideDown'
484 hide: effect: 'slideUp'
485 close: -> $(@).dialog 'destroy'
486 title: title
487
3865fb23 488 .html text
8ebc3fff
SC
489
490 # Get the title of e-item in a row context
491 _etitle: -> @find('.title a').text()