Bug 28377: (28937 follow-up) Flatpickr change
[srvgit] / 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
98     function suspend_hold(hold_id, end_date) {
99
100         var params;
101         if ( end_date !== null && end_date !== '' ) params = JSON.stringify({ "end_date": end_date });
102
103         return $.ajax({
104             method: 'POST',
105             url: '/api/v1/holds/'+encodeURIComponent(hold_id)+'/suspension',
106             contentType: 'application/json',
107             data: params
108         });
109     }
110
111     function resume_hold(hold_id) {
112         return $.ajax({
113             method: 'DELETE',
114             url: '/api/v1/holds/'+encodeURIComponent(hold_id)+'/suspension'
115         });
116     }
117
118     var holdsTable;
119
120     // Don't load holds table unless it is clicked on
121     $("#holds-tab").on( "click", function(){ load_holds_table() } );
122
123     // If the holds tab is preselected on load, we need to load the table
124     if ( $("#holds-tab").parent().hasClass('ui-state-active') ) { load_holds_table() }
125
126     function load_holds_table() {
127         var holds = new Array();
128         if ( ! holdsTable ) {
129             var title;
130             holdsTable = $("#holds-table").dataTable($.extend(true, {}, dataTablesDefaults, {
131                 "bAutoWidth": false,
132                 "sDom": "rt",
133                 "columns": [
134                     {
135                         "data": { _: "reservedate_formatted", "sort": "reservedate" }
136                     },
137                     {
138                         "mDataProp": function ( oObj ) {
139                             title = "<a href='/cgi-bin/koha/reserve/request.pl?biblionumber="
140                                   + oObj.biblionumber
141                                   + "'>"
142                                   + oObj.title.escapeHtml();
143
144                             $.each(oObj.subtitle, function( index, value ) {
145                                 title += " " + value.escapeHtml();
146                             });
147
148                             title += " " + oObj.part_number + " " + oObj.part_name;
149
150                             if ( oObj.enumchron ) {
151                                 title += " (" + oObj.enumchron.escapeHtml() + ")";
152                             }
153
154                             title += "</a>";
155
156                             if ( oObj.author ) {
157                                 title += " " + __("by _AUTHOR_").replace("_AUTHOR_", oObj.author.escapeHtml());
158                             }
159
160                             if ( oObj.itemnotes ) {
161                                 var span_class = "";
162                                 if ( flatpickr.formatDate( new Date(oObj.issuedate), "Y-m-d" ) == ymd ){
163                                     span_class = "circ-hlt";
164                                 }
165                                 title += " - <span class='" + span_class + "'>" + oObj.itemnotes.escapeHtml() + "</span>"
166                             }
167
168                             return title;
169                         }
170                     },
171                     {
172                         "mDataProp": function( oObj ) {
173                             return oObj.itemcallnumber && oObj.itemcallnumber.escapeHtml() || "";
174                         }
175                     },
176                     {
177                         "mDataProp": function( oObj ) {
178                             var data = "";
179                             if ( oObj.barcode ) {
180                                 data += " <a href='/cgi-bin/koha/catalogue/moredetail.pl?biblionumber="
181                                   + oObj.biblionumber
182                                   + "&itemnumber="
183                                   + oObj.itemnumber
184                                   + "#item"
185                                   + oObj.itemnumber
186                                   + "'>"
187                                   + oObj.barcode.escapeHtml()
188                                   + "</a>";
189                             }
190                             return data;
191                         }
192                     },
193                     {
194                         "mDataProp": function( oObj ) {
195                             if( oObj.branches.length > 1 && oObj.found !== 'W' && oObj.found !== 'T' ){
196                                 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">';
197                                 for ( var i=0; i < oObj.branches.length; i++ ){
198                                     var selectedbranch;
199                                     var setbranch;
200                                     if( oObj.branches[i].selected ){
201
202                                         selectedbranch = " selected='selected' ";
203                                         setbranch = __(" (current) ");
204                                     } else if ( oObj.branches[i].pickup_location == 0 ) {
205                                         continue;
206                                     } else{
207                                         selectedbranch = '';
208                                         setbranch = '';
209                                     }
210                                     branchSelect += '<option value="'+ oObj.branches[i].branchcode.escapeHtml() +'"'+selectedbranch+'>'+oObj.branches[i].branchname.escapeHtml()+setbranch+'</option>';
211                                 }
212                                 branchSelect +='</select>';
213                                 return branchSelect;
214                             }
215                             else { return oObj.branchcode.escapeHtml() || ""; }
216                         }
217                     },
218                     { "data": { _: "expirationdate_formatted", "sort": "expirationdate" } },
219                     {
220                         "mDataProp": function( oObj ) {
221                             if ( oObj.priority && parseInt( oObj.priority ) && parseInt( oObj.priority ) > 0 ) {
222                                 return oObj.priority;
223                             } else {
224                                 return "";
225                             }
226                         }
227                     },
228                     {
229                         "bSortable": false,
230                         "mDataProp": function( oObj ) {
231                             return "<select name='rank-request'>"
232                                  +"<option value='n'>" + __("No") + "</option>"
233                                  +"<option value='del'>" + __("Yes") + "</option>"
234                                  + "</select>"
235                                  + "<input type='hidden' name='biblionumber' value='" + oObj.biblionumber + "'>"
236                                  + "<input type='hidden' name='borrowernumber' value='" + borrowernumber + "'>"
237                                  + "<input type='hidden' name='reserve_id' value='" + oObj.reserve_id + "'>";
238                         }
239                     },
240                     {
241                         "bSortable": false,
242                         "visible": SuspendHoldsIntranet,
243                         "mDataProp": function( oObj ) {
244                             holds[oObj.reserve_id] = oObj; //Store holds for later use
245
246                             if ( oObj.found ) {
247                                 return "";
248                             } else if ( oObj.suspend == 1 ) {
249                                 return "<a class='hold-resume btn btn-default btn-xs' data-hold-id='" + oObj.reserve_id + "'>"
250                                      +"<i class='fa fa-play'></i> " + __("Resume") + "</a>";
251                             } else {
252                                 return "<a class='hold-suspend btn btn-default btn-xs' data-hold-id='" + oObj.reserve_id + "' data-hold-title='"+ oObj.title +"'>"
253                                      +"<i class='fa fa-pause'></i> " + __("Suspend") + "</a>";
254                             }
255                         }
256                     },
257                     {
258                         "mDataProp": function( oObj ) {
259                             var data = "";
260
261                             if ( oObj.suspend == 1 ) {
262                                 data += "<p>" + __("Hold is <strong>suspended</strong>");
263                                 if ( oObj.suspend_until ) {
264                                     data += " " + __("until %s").format(oObj.suspend_until_formatted);
265                                 }
266                                 data += "</p>";
267                             }
268
269                             if ( oObj.itemtype_limit ) {
270                                 data += __("Next available %s item").format(oObj.itemtype_limit);
271                             }
272
273                             if ( oObj.barcode ) {
274                                 data += "<em>";
275                                 if ( oObj.found == "W" ) {
276
277                                     if ( oObj.waiting_here ) {
278                                         data += __("Item is <strong>waiting here</strong>");
279                                         if (oObj.desk_name) {
280                                             data += ", " + __("at %s").format(oObj.desk_name.escapeHtml());
281                                         }
282                                     } else {
283                                         data += __("Item is <strong>waiting</strong>");
284                                         data += " " + __("at %s").format(oObj.waiting_at);
285                                         if (oObj.desk_name) {
286                                             data += ", " + __("at %s").format(oObj.desk_name.escapeHtml());
287                                         }
288
289                                     }
290
291                                 } else if ( oObj.transferred ) {
292                                     data += __("Item is <strong>in transit</strong> from %s since %s").format(oObj.from_branch, oObj.date_sent);
293                                 } else if ( oObj.not_transferred ) {
294                                     data += __("Item hasn't been transferred yet from %s").format(oObj.not_transferred_by);
295                                 }
296                                 data += "</em>";
297                             }
298                             return data;
299                         }
300                     }
301                 ],
302                 "bPaginate": false,
303                 "bProcessing": true,
304                 "bServerSide": false,
305                 "ajax": {
306                     "url": '/cgi-bin/koha/svc/holds',
307                     "data": function ( d ) {
308                         d.borrowernumber = borrowernumber;
309                     }
310                 },
311             }));
312
313             $('#holds-table').on( 'draw.dt', function () {
314                 $(".hold-suspend").on( "click", function() {
315                     var hold_id    = $(this).data('hold-id');
316                     var hold_title = $(this).data('hold-title');
317                     $("#suspend-modal-title").html( hold_title );
318                     $("#suspend-modal-submit").data( 'hold-id', hold_id );
319                     $('#suspend-modal').modal('show');
320                 });
321
322                 $(".hold-resume").on("click", function () {
323                     var hold_id = $(this).data('hold-id');
324                     resume_hold(
325                         hold_id
326                     ).success(function () {
327                         holdsTable.api().ajax.reload();
328                     }).error(function (jqXHR, textStatus, errorThrown) {
329                         if (jqXHR.status === 404) {
330                             alert(__("Unable to resume, hold not found"));
331                             holdsTable.api().ajax.reload();
332                         }
333                     });
334                 });
335
336                 $(".hold_location_select").each(function(){ $(this).pickup_locations_dropdown(); });
337
338                 $(".hold_location_select").on("change", function(){
339                     $(this).prop("disabled",true);
340                     var cur_select = $(this);
341                     var res_id = $(this).attr('reserve_id');
342                     $(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>');
343                     var api_url = '/api/v1/holds/' + encodeURIComponent(res_id) + '/pickup_location';
344                     $.ajax({
345                         method: "PUT",
346                         url: api_url,
347                         data: JSON.stringify({ "pickup_library_id": $(this).val() }),
348                         headers: { "x-koha-override": "any" },
349                         success: function( data ){ holdsTable.api().ajax.reload(); },
350                         error: function( jqXHR, textStatus, errorThrown) {
351                             alert('There was an error:'+textStatus+" "+errorThrown);
352                             cur_select.prop("disabled",false);
353                             $("#updating_reserveno"+res_id).remove();
354                             cur_select.val( cur_select.children('option[selected="selected"]').val() );
355                         },
356                     });
357                 });
358
359             });
360
361             if ( $("#holds-table").length ) {
362                 $("#holds-table_processing").position({
363                     of: $( "#holds-table" ),
364                     collision: "none"
365                 });
366             }
367         }
368     }
369
370     $("body").append("\
371         <div id='suspend-modal' class='modal fade' role='dialog' aria-hidden='true'>\
372             <div class='modal-dialog'>\
373             <div class='modal-content'>\
374             <form id='suspend-modal-form' class='form-inline'>\
375                 <div class='modal-header'>\
376                     <button type='button' class='closebtn' data-dismiss='modal' aria-hidden='true'>×</button>\
377                     <h3 id='suspend-modal-label'>" + __("Suspend hold on") + " <i><span id='suspend-modal-title'></span></i></h3>\
378                 </div>\
379 \
380                 <div class='modal-body'>\
381                     <input type='hidden' id='suspend-modal-reserve_id' name='reserve_id' />\
382 \
383                     <label for='suspend-modal-until'>" + __("Suspend until:") + "</label>\
384                     <input name='suspend_until' id='suspend-modal-until' class='suspend-until' size='10' />\
385 \
386                     <p><a class='btn btn-link' id='suspend-modal-clear-date' >" + __("Clear date to suspend indefinitely") + "</a></p>\
387 \
388                 </div>\
389 \
390                 <div class='modal-footer'>\
391                     <button id='suspend-modal-submit' class='btn btn-primary' type='submit' name='submit'>" + __("Suspend") + "</button>\
392                     <a href='#' data-dismiss='modal' aria-hidden='true' class='cancel'>" + __("Cancel") + "</a>\
393                 </div>\
394             </form>\
395             </div>\
396             </div>\
397         </div>\
398     ");
399
400     $("#suspend-modal-until").flatpickr({
401         minDate: new Date().fp_incr(1) // Require that "until date" be in the future
402     });
403     $("#suspend-modal-clear-date").on( "click", function() { $("#suspend-modal-until").val(""); } );
404
405     $("#suspend-modal-submit").on( "click", function( e ) {
406         e.preventDefault();
407         var suspend_until_date = $("#suspend-modal-until").val();
408         if ( suspend_until_date !== null ) suspend_until_date = $date(suspend_until_date, {dateformat:"rfc3339"});
409         suspend_hold(
410             $(this).data('hold-id'),
411             suspend_until_date
412         ).success(function () {
413             holdsTable.api().ajax.reload();
414         }).error(function (jqXHR, textStatus, errorThrown) {
415             if (jqXHR.status === 404) {
416                 alert(__("Unable to resume, hold not found"));
417                 holdsTable.api().ajax.reload();
418             }
419         }).done(function() {
420             $("#suspend-modal-until").val(""); // clean the input
421             $('#suspend-modal').modal('hide');
422         });
423     });
424 });