Bug 29407: Make the pickup locations dropdown JS reusable
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / holds.js
1 function display_pickup_location (state) {
2     var $text;
3     if ( state.needs_override === true ) {
4         $text = $(
5             '<span>' + state.text + '</span> <span style="float:right;" title="' +
6             _("This pickup location is not allowed according to circulation rules") +
7             '"><i class="fa fa-exclamation-circle" aria-hidden="true"></i></span>'
8         );
9     }
10     else {
11         $text = $('<span>'+state.text+'</span>');
12     }
13
14     return $text;
15 };
16
17 (function ($) {
18
19     /**
20      * Generate a Select2 dropdown for pickup locations
21      *
22      * It expects the select object to contain several data-* attributes
23      * - data-pickup-location-source: 'biblio', 'item' or 'hold' (default)
24      * - data-patron-id: required for 'biblio' and 'item'
25      * - data-biblio-id: required for 'biblio' only
26      * - data-item-id: required for 'item' only
27      *
28      * @return {Object} The Select2 instance
29      */
30
31     $.fn.pickup_locations_dropdown = function () {
32         var select = $(this);
33         var pickup_location_source = $(this).data('pickup-location-source');
34         var patron_id = $(this).data('patron-id');
35         var biblio_id = $(this).data('biblio-id');
36         var item_id = $(this).data('item-id');
37         var hold_id = $(this).data('hold-id');
38
39         var url;
40
41         if ( pickup_location_source === 'biblio' ) {
42             url = '/api/v1/biblios/' + encodeURIComponent(biblio_id) + '/pickup_locations';
43         }
44         else if ( pickup_location_source === 'item' ) {
45             url = '/api/v1/items/' + encodeURIComponent(item_id) + '/pickup_locations';
46         }
47         else { // hold
48             url = '/api/v1/holds/' + encodeURIComponent(hold_id) + '/pickup_locations';
49         }
50
51         select.select2({
52             width: 'style',
53             allowClear: false,
54             ajax: {
55                 url: url,
56                 delay: 300, // wait 300 milliseconds before triggering the request
57                 cache: true,
58                 dataType: 'json',
59                 data: function (params) {
60                     var search_term = (params.term === undefined) ? '' : params.term;
61                     var query = {
62                         "q": JSON.stringify({"name":{"-like":'%'+search_term+'%'}}),
63                         "_order_by": "name",
64                         "_page": params.page
65                     };
66
67                     if ( pickup_location_source !== 'hold' ) {
68                         query["patron_id"] = patron_id;
69                     }
70
71                     return query;
72                 },
73                 processResults: function (data) {
74                     var results = [];
75                     data.results.forEach( function ( pickup_location ) {
76                         results.push(
77                             {
78                                 "id": pickup_location.library_id.escapeHtml(),
79                                 "text": pickup_location.name.escapeHtml(),
80                                 "needs_override": pickup_location.needs_override
81                             }
82                         );
83                     });
84                     return { "results": results, "pagination": { "more": data.pagination.more } };
85                 },
86                 transport: kohaSelect2Transport,
87             },
88             templateResult: display_pickup_location
89         });
90
91         return select;
92     };
93 })(jQuery);
94
95 /* global __ dataTablesDefaults borrowernumber SuspendHoldsIntranet */
96 $(document).ready(function() {
97     var holdsTable;
98
99     // Don't load holds table unless it is clicked on
100     $("#holds-tab").on( "click", function(){ load_holds_table() } );
101
102     // If the holds tab is preselected on load, we need to load the table
103     if ( $("#holds-tab").parent().hasClass('ui-state-active') ) { load_holds_table() }
104
105     function load_holds_table() {
106         var holds = new Array();
107         if ( ! holdsTable ) {
108             var title;
109             holdsTable = $("#holds-table").dataTable($.extend(true, {}, dataTablesDefaults, {
110                 "bAutoWidth": false,
111                 "sDom": "rt",
112                 "columns": [
113                     {
114                         "data": { _: "reservedate_formatted", "sort": "reservedate" }
115                     },
116                     {
117                         "mDataProp": function ( oObj ) {
118                             title = "<a href='/cgi-bin/koha/reserve/request.pl?biblionumber="
119                                   + oObj.biblionumber
120                                   + "'>"
121                                   + oObj.title.escapeHtml();
122
123                             $.each(oObj.subtitle, function( index, value ) {
124                                 title += " " + value.escapeHtml();
125                             });
126
127                             title += " " + oObj.part_number + " " + oObj.part_name;
128
129                             if ( oObj.enumchron ) {
130                                 title += " (" + oObj.enumchron.escapeHtml() + ")";
131                             }
132
133                             title += "</a>";
134
135                             if ( oObj.author ) {
136                                 title += " " + __("by _AUTHOR_").replace("_AUTHOR_", oObj.author.escapeHtml());
137                             }
138
139                             if ( oObj.itemnotes ) {
140                                 var span_class = "";
141                                 if ( flatpickr.formatDate( new Date(oObj.issuedate), "Y-m-d" ) == ymd ){
142                                     span_class = "circ-hlt";
143                                 }
144                                 title += " - <span class='" + span_class + "'>" + oObj.itemnotes.escapeHtml() + "</span>"
145                             }
146
147                             return title;
148                         }
149                     },
150                     {
151                         "mDataProp": function( oObj ) {
152                             return oObj.itemcallnumber && oObj.itemcallnumber.escapeHtml() || "";
153                         }
154                     },
155                     {
156                         "mDataProp": function( oObj ) {
157                             var data = "";
158                             if ( oObj.barcode ) {
159                                 data += " <a href='/cgi-bin/koha/catalogue/moredetail.pl?biblionumber="
160                                   + oObj.biblionumber
161                                   + "&itemnumber="
162                                   + oObj.itemnumber
163                                   + "#item"
164                                   + oObj.itemnumber
165                                   + "'>"
166                                   + oObj.barcode.escapeHtml()
167                                   + "</a>";
168                             }
169                             return data;
170                         }
171                     },
172                     {
173                         "mDataProp": function( oObj ) {
174                             if( oObj.branches.length > 1 && oObj.found !== 'W' && oObj.found !== 'T' ){
175                                 var branchSelect='<select priority='+oObj.priority+' class="hold_location_select" data-hold-id="'+oObj.reserve_id+'" reserve_id="'+oObj.reserve_id+'" name="pick-location" data-pickup-location-source="hold">';
176                                 for ( var i=0; i < oObj.branches.length; i++ ){
177                                     var selectedbranch;
178                                     var setbranch;
179                                     if( oObj.branches[i].selected ){
180
181                                         selectedbranch = " selected='selected' ";
182                                         setbranch = __(" (current) ");
183                                     } else if ( oObj.branches[i].pickup_location == 0 ) {
184                                         continue;
185                                     } else{
186                                         selectedbranch = '';
187                                         setbranch = '';
188                                     }
189                                     branchSelect += '<option value="'+ oObj.branches[i].branchcode.escapeHtml() +'"'+selectedbranch+'>'+oObj.branches[i].branchname.escapeHtml()+setbranch+'</option>';
190                                 }
191                                 branchSelect +='</select>';
192                                 return branchSelect;
193                             }
194                             else { return oObj.branchcode.escapeHtml() || ""; }
195                         }
196                     },
197                     { "data": { _: "expirationdate_formatted", "sort": "expirationdate" } },
198                     {
199                         "mDataProp": function( oObj ) {
200                             if ( oObj.priority && parseInt( oObj.priority ) && parseInt( oObj.priority ) > 0 ) {
201                                 return oObj.priority;
202                             } else {
203                                 return "";
204                             }
205                         }
206                     },
207                     {
208                         "bSortable": false,
209                         "mDataProp": function( oObj ) {
210                             return "<select name='rank-request'>"
211                                  +"<option value='n'>" + __("No") + "</option>"
212                                  +"<option value='del'>" + __("Yes") + "</option>"
213                                  + "</select>"
214                                  + "<input type='hidden' name='biblionumber' value='" + oObj.biblionumber + "'>"
215                                  + "<input type='hidden' name='borrowernumber' value='" + borrowernumber + "'>"
216                                  + "<input type='hidden' name='reserve_id' value='" + oObj.reserve_id + "'>";
217                         }
218                     },
219                     {
220                         "bSortable": false,
221                         "visible": SuspendHoldsIntranet,
222                         "mDataProp": function( oObj ) {
223                             holds[oObj.reserve_id] = oObj; //Store holds for later use
224
225                             if ( oObj.found ) {
226                                 return "";
227                             } else if ( oObj.suspend == 1 ) {
228                                 return "<a class='hold-resume btn btn-default btn-xs' id='resume" + oObj.reserve_id + "'>"
229                                      +"<i class='fa fa-play'></i> " + __("Resume") + "</a>";
230                             } else {
231                                 return "<a class='hold-suspend btn btn-default btn-xs' id='suspend" + oObj.reserve_id + "'>"
232                                      +"<i class='fa fa-pause'></i> " + __("Suspend") + "</a>";
233                             }
234                         }
235                     },
236                     {
237                         "mDataProp": function( oObj ) {
238                             var data = "";
239
240                             if ( oObj.suspend == 1 ) {
241                                 data += "<p>" + __("Hold is <strong>suspended</strong>");
242                                 if ( oObj.suspend_until ) {
243                                     data += " " + __("until %s").format(oObj.suspend_until_formatted);
244                                 }
245                                 data += "</p>";
246                             }
247
248                             if ( oObj.itemtype_limit ) {
249                                 data += __("Next available %s item").format(oObj.itemtype_limit);
250                             }
251
252                             if ( oObj.barcode ) {
253                                 data += "<em>";
254                                 if ( oObj.found == "W" ) {
255
256                                     if ( oObj.waiting_here ) {
257                                         data += __("Item is <strong>waiting here</strong>");
258                                         if (oObj.desk_name) {
259                                             data += ", " + __("at %s").format(oObj.desk_name.escapeHtml());
260                                         }
261                                     } else {
262                                         data += __("Item is <strong>waiting</strong>");
263                                         data += " " + __("at %s").format(oObj.waiting_at);
264                                         if (oObj.desk_name) {
265                                             data += ", " + __("at %s").format(oObj.desk_name.escapeHtml());
266                                         }
267
268                                     }
269
270                                 } else if ( oObj.transferred ) {
271                                     data += __("Item is <strong>in transit</strong> from %s since %s").format(oObj.from_branch, oObj.date_sent);
272                                 } else if ( oObj.not_transferred ) {
273                                     data += __("Item hasn't been transferred yet from %s").format(oObj.not_transferred_by);
274                                 }
275                                 data += "</em>";
276                             }
277                             return data;
278                         }
279                     }
280                 ],
281                 "bPaginate": false,
282                 "bProcessing": true,
283                 "bServerSide": false,
284                 "ajax": {
285                     "url": '/cgi-bin/koha/svc/holds',
286                     "data": function ( d ) {
287                         d.borrowernumber = borrowernumber;
288                     }
289                 },
290             }));
291
292             $('#holds-table').on( 'draw.dt', function () {
293                 $(".hold-suspend").on( "click", function() {
294                     var id = $(this).attr("id").replace("suspend", "");
295                     var hold = holds[id];
296                     $("#suspend-modal-title").html( hold.title );
297                     $("#suspend-modal-reserve_id").val( hold.reserve_id );
298                     $('#suspend-modal').modal('show');
299                 });
300
301                 $(".hold-resume").on( "click", function() {
302                     var id = $(this).attr("id").replace("resume", "");
303                     var hold = holds[id];
304                     $.post('/cgi-bin/koha/svc/hold/resume', { "reserve_id": hold.reserve_id }, function( data ){
305                       if ( data.success ) {
306                           holdsTable.api().ajax.reload();
307                       } else {
308                         if ( data.error == "HOLD_NOT_FOUND" ) {
309                             alert( __("Unable to resume, hold not found") );
310                             holdsTable.api().ajax.reload();
311                         }
312                       }
313                     });
314                 });
315
316                 $(".hold_location_select").each(function(){ $(this).pickup_locations_dropdown(); });
317
318                 $(".hold_location_select").on("change", function(){
319                     $(this).prop("disabled",true);
320                     var cur_select = $(this);
321                     var res_id = $(this).attr('reserve_id');
322                     $(this).after('<div id="updating_reserveno'+res_id+'" class="waiting"><img src="/intranet-tmpl/prog/img/spinner-small.gif" alt="" /><span class="waiting_msg"></span></div>');
323                     var api_url = '/api/v1/holds/' + encodeURIComponent(res_id) + '/pickup_location';
324                     $.ajax({
325                         method: "PUT",
326                         url: api_url,
327                         data: JSON.stringify({ "pickup_library_id": $(this).val() }),
328                         headers: { "x-koha-override": "any" },
329                         success: function( data ){ holdsTable.api().ajax.reload(); },
330                         error: function( jqXHR, textStatus, errorThrown) {
331                             alert('There was an error:'+textStatus+" "+errorThrown);
332                             cur_select.prop("disabled",false);
333                             $("#updating_reserveno"+res_id).remove();
334                             cur_select.val( cur_select.children('option[selected="selected"]').val() );
335                         },
336                     });
337                 });
338
339             });
340
341             if ( $("#holds-table").length ) {
342                 $("#holds-table_processing").position({
343                     of: $( "#holds-table" ),
344                     collision: "none"
345                 });
346             }
347         }
348     }
349
350     $("body").append("\
351         <div id='suspend-modal' class='modal fade' role='dialog' aria-hidden='true'>\
352             <div class='modal-dialog'>\
353             <div class='modal-content'>\
354             <form id='suspend-modal-form' class='form-inline'>\
355                 <div class='modal-header'>\
356                     <button type='button' class='closebtn' data-dismiss='modal' aria-hidden='true'>×</button>\
357                     <h3 id='suspend-modal-label'>" + __("Suspend hold on") + " <i><span id='suspend-modal-title'></span></i></h3>\
358                 </div>\
359 \
360                 <div class='modal-body'>\
361                     <input type='hidden' id='suspend-modal-reserve_id' name='reserve_id' />\
362 \
363                     <label for='suspend-modal-until'>" + __("Suspend until:") + "</label>\
364                     <input name='suspend_until' id='suspend-modal-until' class='suspend-until' size='10' />\
365 \
366                     <p><a class='btn btn-link' id='suspend-modal-clear-date' >" + __("Clear date to suspend indefinitely") + "</a></p>\
367 \
368                 </div>\
369 \
370                 <div class='modal-footer'>\
371                     <button id='suspend-modal-submit' class='btn btn-primary' type='submit' name='submit'>" + __("Suspend") + "</button>\
372                     <a href='#' data-dismiss='modal' aria-hidden='true' class='cancel'>" + __("Cancel") + "</a>\
373                 </div>\
374             </form>\
375             </div>\
376             </div>\
377         </div>\
378     ");
379
380     $("#suspend-modal-until").flatpickr({
381         minDate: new Date().fp_incr(1) // Require that "until date" be in the future
382     });
383     $("#suspend-modal-clear-date").on( "click", function() { $("#suspend-modal-until").val(""); } );
384
385     $("#suspend-modal-submit").on( "click", function( e ) {
386         e.preventDefault();
387         $.post('/cgi-bin/koha/svc/hold/suspend', $('#suspend-modal-form').serialize(), function( data ){
388           $('#suspend-modal').modal('hide');
389           if ( data.success ) {
390               holdsTable.api().ajax.reload();
391           } else {
392             if ( data.error == "INVALID_DATE" ) {
393                 alert( __("Unable to suspend hold, invalid date") );
394             }
395             else if ( data.error == "HOLD_NOT_FOUND" ) {
396                 alert( __("Unable to suspend hold, hold not found") );
397                 holdsTable.api().ajax.reload();
398             }
399           }
400         });
401     });
402 });