Bug 35284: Add DT delay to kohaTable
[koha.git] / koha-tmpl / intranet-tmpl / prog / js / datatables.js
1 // These default options are for translation but can be used
2 // for any other datatables settings
3 // To use it, write:
4 //  $("#table_id").dataTable($.extend(true, {}, dataTableDefaults, {
5 //      // other settings
6 //  } ) );
7 var dataTablesDefaults = {
8     "language": {
9         "paginate": {
10             "first"    : __('First'),
11             "last"     : __('Last'),
12             "next"     : __('Next'),
13             "previous" : __('Previous'),
14         },
15         "emptyTable"       : __('No data available in table'),
16         "info"             : __('Showing _START_ to _END_ of _TOTAL_ entries'),
17         "infoEmpty"        : __('No entries to show'),
18         "infoFiltered"     : __('(filtered from _MAX_ total entries)'),
19         "lengthMenu"       : __('Show _MENU_ entries'),
20         "loadingRecords"   : __('Loading...'),
21         "processing"       : __('Processing...'),
22         "search"           : __('Search:'),
23         "zeroRecords"      : __('No matching records found'),
24         buttons: {
25             "copyTitle"     : __('Copy to clipboard'),
26             "copyKeys"      : __('Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.'),
27             "copySuccess": {
28                 _: __('Copied %d rows to clipboard'),
29                 1: __('Copied one row to clipboard'),
30             }
31         }
32     },
33     "dom": '<"dt-info"i><"top pager"<"table_entries"lp><"table_controls"fB>>tr<"bottom pager"ip>',
34     "buttons": [{
35         fade: 100,
36         className: "dt_button_clear_filter",
37         titleAttr: __('Clear filter'),
38         enabled: false,
39         text: '<i class="fa fa-lg fa-times"></i> <span class="dt-button-text">' + __('Clear filter') + '</span>',
40         available: function ( dt ) {
41             // The "clear filter" button is made available if this test returns true
42             if( dt.settings()[0].aanFeatures.f ){ // aanFeatures.f is null if there is no search form
43                 return true;
44             }
45         },
46         action: function ( e, dt, node ) {
47             dt.search( "" ).draw("page");
48             node.addClass("disabled");
49         }
50     }],
51     "lengthMenu": [[10, 20, 50, 100, -1], [10, 20, 50, 100, __('All')]],
52     "pageLength": 20,
53     "fixedHeader": true,
54     initComplete: function( settings ) {
55         var tableId = settings.nTable.id
56         var state =  settings.oLoadedState;
57         state && toggledClearFilter(state.search.search, tableId);
58         // When the DataTables search function is triggered,
59         // enable or disable the "Clear filter" button based on
60         // the presence of a search string
61         $(this).on( 'search.dt', function ( e, settings ) {
62             toggledClearFilter(settings.oPreviousSearch.sSearch, tableId);
63         });
64
65         if (settings.ajax) {
66             _dt_add_delay($("#"+tableId));
67         }
68     }
69 };
70
71 function toggledClearFilter(searchText, tableId){
72     if( searchText == "" ){
73         $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").addClass("disabled");
74     } else {
75         $("#" + tableId + "_wrapper").find(".dt_button_clear_filter").removeClass("disabled");
76     }
77 }
78
79
80 // Return an array of string containing the values of a particular column
81 $.fn.dataTableExt.oApi.fnGetColumnData = function ( oSettings, iColumn, bUnique, bFiltered, bIgnoreEmpty ) {
82     // check that we have a column id
83     if ( typeof iColumn == "undefined" ) return new Array();
84     // by default we only wany unique data
85     if ( typeof bUnique == "undefined" ) bUnique = true;
86     // by default we do want to only look at filtered data
87     if ( typeof bFiltered == "undefined" ) bFiltered = true;
88     // by default we do not wany to include empty values
89     if ( typeof bIgnoreEmpty == "undefined" ) bIgnoreEmpty = true;
90     // list of rows which we're going to loop through
91     var aiRows;
92     // use only filtered rows
93     if (bFiltered == true) aiRows = oSettings.aiDisplay;
94     // use all rows
95     else aiRows = oSettings.aiDisplayMaster; // all row numbers
96
97     // set up data array
98     var asResultData = new Array();
99     for (var i=0,c=aiRows.length; i<c; i++) {
100         iRow = aiRows[i];
101         var aData = this.fnGetData(iRow);
102         var sValue = aData[iColumn];
103         // ignore empty values?
104         if (bIgnoreEmpty == true && sValue.length == 0) continue;
105         // ignore unique values?
106         else if (bUnique == true && jQuery.inArray(sValue, asResultData) > -1) continue;
107         // else push the value onto the result data array
108         else asResultData.push(sValue);
109     }
110     return asResultData;
111 }
112
113 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
114 // These keys must not launch filtering
115 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
116
117 // Set a filtering delay for global search field
118 jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) {
119     /*
120      * Inputs:      object:oSettings - dataTables settings object - automatically given
121      *              integer:iDelay - delay in milliseconds
122      * Usage:       $('#example').dataTable().fnSetFilteringDelay(250);
123      * Author:      Zygimantas Berziunas (www.zygimantas.com) and Allan Jardine
124      * License:     GPL v2 or BSD 3 point style
125      * Contact:     zygimantas.berziunas /AT\ hotmail.com
126      */
127     var
128         _that = this,
129         iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay;
130
131     this.each( function ( i ) {
132         $.fn.dataTableExt.iApiIndex = i;
133         var
134             $this = this,
135             oTimerId = null,
136             sPreviousSearch = null,
137             anControl = $( 'input', _that.fnSettings().aanFeatures.f );
138
139         anControl.unbind( 'keyup.DT' ).bind( 'keyup.DT', function(event) {
140             var $$this = $this;
141             if (blacklist_keys.indexOf(event.keyCode) != -1) {
142                 return this;
143             }else if ( event.keyCode == '13' ) {
144                 $.fn.dataTableExt.iApiIndex = i;
145                 _that.fnFilter( $(this).val() );
146             } else {
147                 if (sPreviousSearch === null || sPreviousSearch != anControl.val()) {
148                     window.clearTimeout(oTimerId);
149                     sPreviousSearch = anControl.val();
150                     oTimerId = window.setTimeout(function() {
151                         $.fn.dataTableExt.iApiIndex = i;
152                         _that.fnFilter( anControl.val() );
153                     }, iDelay);
154                 }
155             }
156         });
157
158         return this;
159     } );
160     return this;
161 }
162
163 // Add a filtering delay on general search and on all input (with a class 'filter')
164 jQuery.fn.dataTableExt.oApi.fnAddFilters = function ( oSettings, sClass, iDelay ) {
165     var table = this;
166     this.fnSetFilteringDelay(iDelay);
167     var filterTimerId = null;
168     $(table).find("input."+sClass).keyup(function(event) {
169       if (blacklist_keys.indexOf(event.keyCode) != -1) {
170         return this;
171       }else if ( event.keyCode == '13' ) {
172         table.fnFilter( $(this).val(), $(this).attr('data-column_num') );
173       } else {
174         window.clearTimeout(filterTimerId);
175         var input = this;
176         filterTimerId = window.setTimeout(function() {
177           table.fnFilter($(input).val(), $(input).attr('data-column_num'));
178         }, iDelay);
179       }
180     });
181     $(table).find("select."+sClass).on('change', function() {
182         table.fnFilter($(this).val(), $(this).attr('data-column_num'));
183     });
184 }
185
186 // Sorting on html contains
187 // <a href="foo.pl">bar</a> sort on 'bar'
188 function dt_overwrite_html_sorting_localeCompare() {
189     jQuery.fn.dataTableExt.oSort['html-asc']  = function(a,b) {
190         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
191         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
192         if (typeof(a.localeCompare == "function")) {
193            return a.localeCompare(b);
194         } else {
195            return (a > b) ? 1 : ((a < b) ? -1 : 0);
196         }
197     };
198
199     jQuery.fn.dataTableExt.oSort['html-desc'] = function(a,b) {
200         a = a.replace(/<.*?>/g, "").replace(/\s+/g, " ");
201         b = b.replace(/<.*?>/g, "").replace(/\s+/g, " ");
202         if(typeof(b.localeCompare == "function")) {
203             return b.localeCompare(a);
204         } else {
205             return (b > a) ? 1 : ((b < a) ? -1 : 0);
206         }
207     };
208
209     jQuery.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
210         var x = a.replace( /<.*?>/g, "" );
211         var y = b.replace( /<.*?>/g, "" );
212         x = parseFloat( x );
213         y = parseFloat( y );
214         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
215     };
216
217     jQuery.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
218         var x = a.replace( /<.*?>/g, "" );
219         var y = b.replace( /<.*?>/g, "" );
220         x = parseFloat( x );
221         y = parseFloat( y );
222         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
223     };
224 }
225
226 $.fn.dataTableExt.oSort['num-html-asc']  = function(a,b) {
227     var x = a.replace( /<.*?>/g, "" );
228     var y = b.replace( /<.*?>/g, "" );
229     x = parseFloat( x );
230     y = parseFloat( y );
231     return ((x < y) ? -1 : ((x > y) ?  1 : 0));
232 };
233
234 $.fn.dataTableExt.oSort['num-html-desc'] = function(a,b) {
235     var x = a.replace( /<.*?>/g, "" );
236     var y = b.replace( /<.*?>/g, "" );
237     x = parseFloat( x );
238     y = parseFloat( y );
239     return ((x < y) ?  1 : ((x > y) ? -1 : 0));
240 };
241
242 (function() {
243
244 /*
245  * Natural Sort algorithm for Javascript - Version 0.7 - Released under MIT license
246  * Author: Jim Palmer (based on chunking idea from Dave Koelle)
247  * Contributors: Mike Grier (mgrier.com), Clint Priest, Kyle Adams, guillermo
248  * See: http://js-naturalsort.googlecode.com/svn/trunk/naturalSort.js
249  */
250 function naturalSort (a, b) {
251     var re = /(^-?[0-9]+(\.?[0-9]*)[df]?e?[0-9]?$|^0x[0-9a-f]+$|[0-9]+)/gi,
252         sre = /(^[ ]*|[ ]*$)/g,
253         dre = /(^([\w ]+,?[\w ]+)?[\w ]+,?[\w ]+\d+:\d+(:\d+)?[\w ]?|^\d{1,4}[\/\-]\d{1,4}[\/\-]\d{1,4}|^\w+, \w+ \d+, \d{4})/,
254         hre = /^0x[0-9a-f]+$/i,
255         ore = /^0/,
256         // convert all to strings and trim()
257         x = a.toString().replace(sre, '') || '',
258         y = b.toString().replace(sre, '') || '',
259         // chunk/tokenize
260         xN = x.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
261         yN = y.replace(re, '\0$1\0').replace(/\0$/,'').replace(/^\0/,'').split('\0'),
262         // numeric, hex or date detection
263         xD = parseInt(x.match(hre), 10) || (xN.length != 1 && x.match(dre) && Date.parse(x)),
264         yD = parseInt(y.match(hre), 10) || xD && y.match(dre) && Date.parse(y) || null;
265     // first try and sort Hex codes or Dates
266     if (yD)
267         if ( xD < yD ) return -1;
268         else if ( xD > yD )  return 1;
269     // natural sorting through split numeric strings and default strings
270     for(var cLoc=0, numS=Math.max(xN.length, yN.length); cLoc < numS; cLoc++) {
271         // find floats not starting with '0', string or 0 if not defined (Clint Priest)
272         var oFxNcL = !(xN[cLoc] || '').match(ore) && parseFloat(xN[cLoc]) || xN[cLoc] || 0;
273         var oFyNcL = !(yN[cLoc] || '').match(ore) && parseFloat(yN[cLoc]) || yN[cLoc] || 0;
274         // handle numeric vs string comparison - number < string - (Kyle Adams)
275         if (isNaN(oFxNcL) !== isNaN(oFyNcL)) return (isNaN(oFxNcL)) ? 1 : -1;
276         // rely on string comparison if different types - i.e. '02' < 2 != '02' < '2'
277         else if (typeof oFxNcL !== typeof oFyNcL) {
278             oFxNcL += '';
279             oFyNcL += '';
280         }
281         if (oFxNcL < oFyNcL) return -1;
282         if (oFxNcL > oFyNcL) return 1;
283     }
284     return 0;
285 }
286
287 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
288     "natural-asc": function ( a, b ) {
289         return naturalSort(a,b);
290     },
291
292     "natural-desc": function ( a, b ) {
293         return naturalSort(a,b) * -1;
294     }
295 } );
296
297 }());
298
299 /* Plugin to allow sorting on data stored in a span's title attribute
300  *
301  * Ex: <td><span title="[% ISO_date %]">[% formatted_date %]</span></td>
302  *
303  * In DataTables config:
304  *     "aoColumns": [
305  *        { "sType": "title-string" },
306  *      ]
307  * http://datatables.net/plug-ins/sorting#hidden_title_string
308  */
309 jQuery.extend( jQuery.fn.dataTableExt.oSort, {
310     "title-string-pre": function ( a ) {
311         var m = a.match(/title="(.*?)"/);
312         if ( null !== m && m.length ) {
313             return m[1].toLowerCase();
314         }
315         return "";
316     },
317
318     "title-string-asc": function ( a, b ) {
319         return ((a < b) ? -1 : ((a > b) ? 1 : 0));
320     },
321
322     "title-string-desc": function ( a, b ) {
323         return ((a < b) ? 1 : ((a > b) ? -1 : 0));
324     }
325 } );
326
327 (function() {
328
329     /* Plugin to allow text sorting to ignore articles
330      *
331      * In DataTables config:
332      *     "aoColumns": [
333      *        { "sType": "anti-the" },
334      *      ]
335      * Based on the plugin found here:
336      * http://datatables.net/plug-ins/sorting#anti_the
337      * Modified to exclude HTML tags from sorting
338      * Extended to accept a string of space-separated articles
339      * from a configuration file (in English, "a," "an," and "the")
340      */
341
342     var config_exclude_articles_from_sort = __('a an the');
343     if (config_exclude_articles_from_sort){
344         var articles = config_exclude_articles_from_sort.split(" ");
345         var rpattern = "";
346         for(i=0;i<articles.length;i++){
347             rpattern += "^" + articles[i] + " ";
348             if(i < articles.length - 1){ rpattern += "|"; }
349         }
350         var re = new RegExp(rpattern, "i");
351     }
352
353     jQuery.extend( jQuery.fn.dataTableExt.oSort, {
354         "anti-the-pre": function ( a ) {
355             var x = String(a).replace( /<[\s\S]*?>/g, "" );
356             var y = x.trim();
357             var z = y.replace(re, "").toLowerCase();
358             return z;
359         },
360
361         "anti-the-asc": function ( a, b ) {
362             return ((a < b) ? -1 : ((a > b) ? 1 : 0));
363         },
364
365         "anti-the-desc": function ( a, b ) {
366             return ((a < b) ? 1 : ((a > b) ? -1 : 0));
367         }
368     });
369
370 }());
371
372 // Remove string between NSB NSB characters
373 $.fn.dataTableExt.oSort['nsb-nse-asc'] = function(a,b) {
374     var pattern = new RegExp("\x88.*\x89");
375     a = a.replace(pattern, "");
376     b = b.replace(pattern, "");
377     return (a > b) ? 1 : ((a < b) ? -1 : 0);
378 }
379 $.fn.dataTableExt.oSort['nsb-nse-desc'] = function(a,b) {
380     var pattern = new RegExp("\x88.*\x89");
381     a = a.replace(pattern, "");
382     b = b.replace(pattern, "");
383     return (b > a) ? 1 : ((b < a) ? -1 : 0);
384 }
385
386 /* Define two custom functions (asc and desc) for basket callnumber sorting */
387 jQuery.fn.dataTableExt.oSort['callnumbers-asc']  = function(x,y) {
388         var x_array = x.split("<div>");
389         var y_array = y.split("<div>");
390
391         /* Pop the first elements, they are empty strings */
392         x_array.shift();
393         y_array.shift();
394
395         x_array = jQuery.map( x_array, function( a ) {
396             return parse_callnumber( a );
397         });
398         y_array = jQuery.map( y_array, function( a ) {
399             return parse_callnumber( a );
400         });
401
402         x_array.sort();
403         y_array.sort();
404
405         x = x_array.shift();
406         y = y_array.shift();
407
408         if ( !x ) { x = ""; }
409         if ( !y ) { y = ""; }
410
411         return ((x < y) ? -1 : ((x > y) ?  1 : 0));
412 };
413
414 jQuery.fn.dataTableExt.oSort['callnumbers-desc'] = function(x,y) {
415         var x_array = x.split("<div>");
416         var y_array = y.split("<div>");
417
418         /* Pop the first elements, they are empty strings */
419         x_array.shift();
420         y_array.shift();
421
422         x_array = jQuery.map( x_array, function( a ) {
423             return parse_callnumber( a );
424         });
425         y_array = jQuery.map( y_array, function( a ) {
426             return parse_callnumber( a );
427         });
428
429         x_array.sort();
430         y_array.sort();
431
432         x = x_array.pop();
433         y = y_array.pop();
434
435         if ( !x ) { x = ""; }
436         if ( !y ) { y = ""; }
437
438         return ((x < y) ?  1 : ((x > y) ? -1 : 0));
439 };
440
441 function parse_callnumber ( html ) {
442     var array = html.split('<span class="callnumber">');
443     if ( array[1] ) {
444         array = array[1].split('</span>');
445         return array[0];
446     } else {
447         return "";
448     }
449 }
450
451 // see http://www.datatables.net/examples/advanced_init/footer_callback.html
452 function footer_column_sum( api, column_numbers ) {
453     // Remove the formatting to get integer data for summation
454     var intVal = function ( i ) {
455         if ( typeof i === 'number' ) {
456             if ( isNaN(i) ) return 0;
457             return i;
458         } else if ( typeof i === 'string' ) {
459             var value = i.replace(/[a-zA-Z ,.]/g, '')*1;
460             if ( isNaN(value) ) return 0;
461             return value;
462         }
463         return 0;
464     };
465
466
467     for ( var indice = 0 ; indice < column_numbers.length ; indice++ ) {
468         var column_number = column_numbers[indice];
469
470         var total = 0;
471         var cells = api.column( column_number, { page: 'current' } ).nodes().to$().find("span.total_amount");
472         var budgets_totaled = [];
473         $(cells).each(function(){ budgets_totaled.push( $(this).data('self_id') ); });
474         $(cells).each(function(){
475             if( $(this).data('parent_id') && $.inArray( $(this).data('parent_id'), budgets_totaled) > -1 ){
476                 return;
477             } else {
478                 total += intVal( $(this).html() );
479             }
480
481         });
482         total /= 100; // Hard-coded decimal precision
483
484         // Update footer
485         $( api.column( column_number ).footer() ).html(total.format_price());
486     };
487 }
488
489 function filterDataTable( table, column, term ){
490     if( column ){
491         table.column( column ).search( term ).draw("page");
492     } else {
493         table.search( term ).draw("page");
494     }
495 }
496
497 jQuery.fn.dataTable.ext.errMode = function(settings, note, message) {
498     if ( settings && settings.jqXHR ) {
499         console.log("Got %s (%s)".format(settings.jqXHR.status, settings.jqXHR.statusText));
500         alert(__("Something went wrong when loading the table.\n%s: %s. \n%s").format(
501             settings.jqXHR.status,
502             settings.jqXHR.statusText,
503             ( settings.jqXHR.responseJSON && settings.jqXHR.responseJSON.errors ) ? settings.jqXHR.responseJSON.errors.map(m => m.message).join("\n") : ''
504         ));
505     } else {
506         alert(__("Something went wrong when loading the table."));
507     }
508     console.log(message);
509 };
510
511 function _dt_default_ajax (params){
512     let default_filters = params.default_filters;
513     let options = params.options;
514
515     if(!options.criteria || ['contains', 'starts_with', 'ends_with', 'exact'].indexOf(options.criteria.toLowerCase()) === -1) options.criteria = 'contains';
516     options.criteria = options.criteria.toLowerCase();
517
518     return {
519         'type': 'GET',
520         'cache': true,
521         'dataSrc': 'data',
522         'beforeSend': function(xhr, settings) {
523             this._xhr = xhr;
524             if(options.embed) {
525                 xhr.setRequestHeader('x-koha-embed', Array.isArray(options.embed)?options.embed.join(','):options.embed);
526             }
527         },
528         'dataFilter': function(data, type) {
529             var json = {data: JSON.parse(data)};
530             if (total = this._xhr.getResponseHeader('x-total-count')) {
531                 json.recordsTotal = total;
532                 json.recordsFiltered = total;
533             }
534             if (total = this._xhr.getResponseHeader('x-base-total-count')) {
535                 json.recordsTotal = total;
536             }
537             if (draw = this._xhr.getResponseHeader('x-koha-request-id')) {
538                 json.draw = draw;
539             }
540
541             return JSON.stringify(json);
542         },
543         'data': function( data, settings ) {
544             var length = data.length;
545             var start  = data.start;
546
547             var dataSet = {
548                 _page: Math.floor(start/length) + 1,
549                 _per_page: length
550             };
551
552             function build_query(col, value){
553
554                 var parts = [];
555                 var attributes = col.data.split(':');
556                 for (var i=0;i<attributes.length;i++){
557                     var part = {};
558                     var attr = attributes[i];
559                     let criteria = options.criteria;
560                     if ( value.match(/^\^(.*)\$$/) ) {
561                         value = value.replace(/^\^/, '').replace(/\$$/, '');
562                         criteria = "exact";
563                     } else {
564                         // escape SQL LIKE special characters %
565                         value = value.replace(/(\%|\\)/g, "\\$1");
566                     }
567
568                     let built_value;
569                     if ( col.type == 'date' ) {
570                         let rfc3339 = $date_to_rfc3339(value);
571                         if ( rfc3339 != 'Invalid Date' ) {
572                             built_value = rfc3339;
573                         }
574                     }
575
576                     if ( col.datatype !== undefined ) {
577                         if (col.datatype == 'related-object') {
578                             let query_term = value;
579
580                             if (criteria != 'exact') {
581                                 query_term = { like: (['contains', 'ends_with'].indexOf(criteria) !== -1 ? '%' : '') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1 ? '%' : '') };
582                             }
583
584                             part = {
585                                 [col.related + '.' + col.relatedKey]: col.relatedValue,
586                                 [col.related + '.' + col.relatedSearchOn]: query_term
587                             };
588                         } else {
589                             console.log("datatype %s not supported yet".format(col.datatype));
590                         }
591                     }
592
593                     if (col.datatype != 'related-object') {
594                         let value_part;
595                         if ( criteria === 'exact' ) {
596                             value_part = built_value ? [value, built_value] : value
597                         } else {
598                             let like = {like: (['contains', 'ends_with'].indexOf(criteria) !== -1?'%':'') + value + (['contains', 'starts_with'].indexOf(criteria) !== -1?'%':'')};
599                             value_part = built_value ? [like, built_value] : like;
600                         }
601
602                         part[!attr.includes('.')?'me.'+attr:attr] = value_part;
603                     }
604
605                     parts.push(part);
606                 }
607                 return parts;
608             }
609
610             var filter = data.search.value;
611             // Build query for each column filter
612             var and_query_parameters = settings.aoColumns
613             .filter(function(col) {
614                 return col.bSearchable && typeof col.data == 'string' && data.columns[col.idx].search.value != ''
615             })
616             .map(function(col) {
617                 var value = data.columns[col.idx].search.value;
618                 return build_query(col, value)
619             })
620             .map(function r(e){
621                 return ($.isArray(e) ? $.map(e, r) : e);
622             });
623
624             // Build query for the global search filter
625             var or_query_parameters = settings.aoColumns
626             .filter(function(col) {
627                 return col.bSearchable && filter != ''
628             })
629             .map(function(col) {
630                 var value = filter;
631                 return build_query(col, value)
632             })
633             .map(function r(e){
634                 return ($.isArray(e) ? $.map(e, r) : e);
635             });
636
637             if ( default_filters ) {
638                 let additional_filters = {};
639                 for ( f in default_filters ) {
640                     let k; let v;
641                     if ( typeof(default_filters[f]) === 'function' ) {
642                         let val = default_filters[f]();
643                         if ( val != undefined && val != "" ) {
644                             k = f; v = val;
645                         }
646                     } else {
647                         k = f; v = default_filters[f];
648                     }
649
650                     // Pass to -or if you want a separate OR clause
651                     // It's not the usual DBIC notation!
652                     if ( f == '-or' ) {
653                         if (v) or_query_parameters.push(v)
654                     } else if ( f == '-and' ) {
655                         if (v) and_query_parameters.push(v)
656                     } else if ( v ) {
657                         additional_filters[k] = v;
658                     }
659                 }
660                 if ( Object.keys(additional_filters).length ) {
661                     and_query_parameters.push(additional_filters);
662                 }
663             }
664             query_parameters = and_query_parameters;
665             if ( or_query_parameters.length) {
666                 query_parameters.push(or_query_parameters);
667             }
668
669             if(query_parameters.length) {
670                 query_parameters = JSON.stringify(query_parameters.length === 1?query_parameters[0]:{"-and": query_parameters});
671                 if(options.header_filter) {
672                     options.query_parameters = query_parameters;
673                 } else {
674                     dataSet.q = query_parameters;
675                     delete options.query_parameters;
676                 }
677             } else {
678                 delete options.query_parameters;
679             }
680
681             dataSet._match = options.criteria;
682
683             if ( data["draw"] !== undefined ) {
684                 settings.ajax.headers = { 'x-koha-request-id': data.draw }
685             }
686
687             if(options.columns) {
688                 var order = data.order;
689                 var orderArray = new Array();
690                 order.forEach(function (e,i) {
691                     var order_col      = e.column;
692                     var order_by       = options.columns[order_col].data;
693                     order_by           = order_by.split(':');
694                     var order_dir      = e.dir == 'asc' ? '+' : '-';
695                     Array.prototype.push.apply(orderArray,order_by.map(x => order_dir + (!x.includes('.')?'me.'+x:x)));
696                 });
697                 dataSet._order_by = orderArray.filter((v, i, a) => a.indexOf(v) === i).join(',');
698             }
699
700             return dataSet;
701         }
702     }
703 }
704
705 function _dt_buttons(params){
706     let included_ids = params.included_ids || [];
707     let settings = params.settings || {};
708     let table_settings = params.table_settings;
709
710     var exportColumns = ":visible:not(.noExport)";
711     if( settings.hasOwnProperty("exportColumns") ){
712         // A custom buttons configuration has been passed from the page
713         exportColumns = settings["exportColumns"];
714     }
715
716     var export_format = {
717         body: function ( data, row, column, node ) {
718             var newnode = $(node);
719
720             if ( newnode.find(".noExport").length > 0 ) {
721                 newnode = newnode.clone();
722                 newnode.find(".noExport").remove();
723             }
724
725             return newnode.text().replace( /\n/g, ' ' ).trim();
726         }
727     }
728
729     var export_buttons = [
730         {
731             extend: 'excelHtml5',
732             text: __("Excel"),
733             exportOptions: {
734                 columns: exportColumns,
735                 format:  export_format
736             },
737         },
738         {
739             extend: 'csvHtml5',
740             text: __("CSV"),
741             exportOptions: {
742                 columns: exportColumns,
743                 format:  export_format
744             },
745         },
746         {
747             extend: 'copyHtml5',
748             text: __("Copy"),
749             exportOptions: {
750                 columns: exportColumns,
751                 format:  export_format
752             },
753         },
754         {
755             extend: 'print',
756             text: __("Print"),
757             exportOptions: {
758                 columns: exportColumns,
759                 format:  export_format
760             },
761         }
762     ];
763
764     let buttons = [];
765     buttons.push(
766         {
767             fade: 100,
768             className: "dt_button_clear_filter",
769             titleAttr: __("Clear filter"),
770             enabled: false,
771             text: '<i class="fa fa-lg fa-remove"></i> <span class="dt-button-text">' + __("Clear filter") + '</span>',
772             action: function ( e, dt, node, config ) {
773                 dt.search( "" ).draw("page");
774                 node.addClass("disabled");
775             }
776         }
777     );
778
779     if( included_ids.length > 0 ){
780         buttons.push(
781             {
782                 extend: 'colvis',
783                 fade: 100,
784                 columns: included_ids,
785                 className: "columns_controls",
786                 titleAttr: __("Columns settings"),
787                 text: '<i class="fa fa-lg fa-gear"></i> <span class="dt-button-text">' + __("Columns") + '</span>',
788                 exportOptions: {
789                     columns: exportColumns
790                 }
791             }
792         );
793     }
794
795     buttons.push(
796         {
797             extend: 'collection',
798             autoClose: true,
799             fade: 100,
800             className: "export_controls",
801             titleAttr: __("Export or print"),
802             text: '<i class="fa fa-lg fa-download"></i> <span class="dt-button-text">' + __("Export") + '</span>',
803             buttons: export_buttons
804         }
805     );
806
807     if ( table_settings && CAN_user_parameters_manage_column_config ) {
808         buttons.push(
809             {
810                 className: "dt_button_configure_table",
811                 fade: 100,
812                 titleAttr: __("Configure table"),
813                 text: '<i class="fa fa-lg fa-wrench"></i> <span class="dt-button-text">' + __("Configure") + '</span>',
814                 action: function() {
815                     window.location = '/cgi-bin/koha/admin/columns_settings.pl?module=' + table_settings['module'] + '&page=' + table_settings['page'] + '&table=' + table_settings['table'];
816                 },
817             }
818         );
819     }
820
821     return buttons;
822 }
823
824 function _dt_visibility(table_settings, settings){
825     var counter = 0;
826     let hidden_ids = [];
827     let included_ids = [];
828     if ( table_settings ) {
829         var columns_settings = table_settings['columns'];
830         $(columns_settings).each( function() {
831             var named_id = $( 'thead th[data-colname="' + this.columnname + '"]', this ).index( 'th' );
832             var used_id = settings.bKohaColumnsUseNames ? named_id : counter;
833             if ( used_id == -1 ) return;
834
835             if ( this['is_hidden'] == "1" ) {
836                 hidden_ids.push( used_id );
837             }
838             if ( this['cannot_be_toggled'] == "0" ) {
839                 included_ids.push( used_id );
840             }
841             counter++;
842         });
843     }
844     return [hidden_ids, included_ids];
845 }
846
847 function _dt_on_visibility(add_filters, table_node, table_dt){
848     if ( add_filters ) {
849         let visible_columns = table_dt.columns().visible();
850         $(table_node).find('thead tr:eq(1) th').each( function (i) {
851             let th_id = $(this).data('th-id');
852             if ( visible_columns[th_id] == false ) {
853                 $(this).hide();
854             } else {
855                 $(this).show();
856             }
857         });
858     }
859
860     if( typeof columnsInit == 'function' ){
861         // This function can be created separately and used to trigger
862         // an event after the DataTable has loaded AND column visibility
863         // has been updated according to the table's configuration
864         columnsInit();
865     }
866 }
867
868 function _dt_add_filters(table_node, table_dt, filters_options = {}) {
869     $(table_node).find('thead tr').clone().appendTo( $(table_node).find('thead') );
870
871     $(table_node).find('thead tr:eq(1) th').each( function (i) {
872         var is_searchable = table_dt.settings()[0].aoColumns[i].bSearchable;
873         $(this).removeClass('sorting').removeClass("sorting_asc").removeClass("sorting_desc");
874         $(this).data('th-id', i);
875         if ( is_searchable ) {
876             let input_type = 'input';
877             if ( $(this).data('filter') || filters_options.hasOwnProperty(i)) {
878                 input_type = 'select'
879                 let filter_type = $(this).data('filter');
880                 let existing_search = table_dt.column(i).search();
881                 let select = $('<select><option value=""></option></select');
882
883                 // FIXME eval here is bad and dangerous, how do we workaround that?
884                 if ( !filters_options.hasOwnProperty(i) ) {
885                     filters_options[i] = eval(filter_type)
886                 } else if ( typeof filters_options[i] === "function" ) {
887                     filters_options[i] = filters_options[i]()
888                 }
889                 $(filters_options[i]).each(function(){
890                     let o = $('<option value="%s">%s</option>'.format(this._id, this._str));
891                     if ( existing_search === this._id ) {
892                         o.prop("selected", "selected");
893                     }
894                     o.appendTo(select);
895                 });
896                 $(this).html( select );
897             } else {
898                 var title = $(this).text();
899                 var existing_search = table_dt.column(i).search();
900                 if ( existing_search ) {
901                     $(this).html( '<input type="text" value="%s" style="width: 100%" />'.format(existing_search) );
902                 } else {
903                     var search_title = __("%s search").format(title);
904                     $(this).html( '<input type="text" placeholder="%s" style="width: 100%" />'.format(search_title) );
905                 }
906             }
907
908             $( input_type, this ).on( 'keyup change', function () {
909                 if ( table_dt.column(i).search() !== this.value ) {
910                     if ( input_type == "input" ) {
911                         table_dt
912                             .column(i)
913                             .search( this.value )
914                             .draw();
915                     } else {
916                         table_dt
917                             .column(i)
918                             .search( this.value.length ? '^'+this.value+'$' : '', true, false )
919                             .draw();
920                     }
921                 }
922             } );
923         } else {
924             $(this).html('');
925         }
926     } );
927 }
928
929 // List of unbind keys (Ctrl, Alt, Direction keys, etc.)
930 // These keys must not launch filtering
931 var blacklist_keys = new Array(0, 16, 17, 18, 37, 38, 39, 40);
932
933 function _dt_add_delay(table_node, delay_ms) {
934
935     let dt = table_node.DataTable();
936     delay = (typeof delay == 'undefined') ? 500 : delay;
937
938     var previousSearch = null;
939     var timerId = null;
940     $("#"+table_node.attr('id')+"_wrapper").find(".dataTables_filter input")
941     .unbind()
942     .bind("keyup", function(event) {
943         var input = $(this);
944         if (blacklist_keys.indexOf(event.keyCode) != -1) {
945             return;
946         } else if ( event.keyCode == '13' ) {
947             dt.search($(input).val()).draw();
948         } else {
949             let val = $(input).val();
950             if (previousSearch === null || previousSearch != val){
951                 window.clearTimeout(timerId);
952                 previousSearch = val;
953                 timerId = window.setTimeout(function(){
954                     dt.search($(input).val()).draw();
955                 }, delay);
956             }
957         }
958
959         return;
960     });
961 }
962
963 (function($) {
964
965     /**
966     * Create a new dataTables instance that uses the Koha RESTful API's as a data source
967     * @param  {Object}  options                      Please see the dataTables settings documentation for further
968     *                                                details
969     * @param  {string}  [options.criteria=contains]  A koha specific extension to the dataTables settings block that
970     *                                                allows setting the 'comparison operator' used in searches
971     *                                                Supports `contains`, `starts_with`, `ends_with` and `exact` match
972     * @param  {string}  [options.columns.*.type      Data type the field is stored in so we may impose some additional
973     *                                                manipulation to search strings. Supported types are currenlty 'date'
974     * @param  {Object}  table_settings               The arrayref as returned by TableSettings.GetTableSettings function
975     *                                                available from the columns_settings template toolkit include
976     * @param  {Boolean} add_filters                  Add a filters row as the top row of the table
977     * @param  {Object}  default_filters              Add a set of default search filters to apply at table initialisation
978     * @return {Object}                               The dataTables instance
979     */
980     $.fn.kohaTable = function(options, table_settings, add_filters, default_filters) {
981         var settings = null;
982
983         if(options) {
984             // Don't redefine the default initComplete
985             if ( options.initComplete ) {
986                 let our_initComplete = options.initComplete;
987                 options.initComplete = function(settings, json){
988                     our_initComplete(settings, json);
989                     dataTablesDefaults.initComplete(settings, json)
990                 };
991             }
992
993             settings = $.extend(true, {}, dataTablesDefaults, {
994                         'deferRender': true,
995                         "paging": true,
996                         'serverSide': true,
997                         'searching': true,
998                         'pagingType': 'full_numbers',
999                         'processing': true,
1000                         'language': {
1001                             'emptyTable': (options.emptyTable) ? options.emptyTable : __("No data available in table")
1002                         },
1003                         'ajax': _dt_default_ajax({default_filters, options}),
1004                     }, options);
1005         }
1006
1007         let hidden_ids, included_ids;
1008         [hidden_ids, included_ids] = _dt_visibility(table_settings, settings)
1009
1010         settings["buttons"] = _dt_buttons({included_ids, settings, table_settings});
1011
1012         $(".dt_button_clear_filter, .columns_controls, .export_controls, .dt_button_configure_table").tooltip();
1013
1014         if ( add_filters ) {
1015             settings['orderCellsTop'] = true;
1016         }
1017
1018         if ( table_settings ) {
1019             if ( table_settings.hasOwnProperty('default_display_length') && table_settings['default_display_length'] != null ) {
1020                 settings["pageLength"] = table_settings['default_display_length'];
1021             }
1022             if ( table_settings.hasOwnProperty('default_sort_order') && table_settings['default_sort_order'] != null ) {
1023                 settings["order"] = [[ table_settings['default_sort_order'], 'asc' ]];
1024             }
1025         }
1026
1027         var table = $(this).dataTable(settings);
1028
1029         var table_dt = table.DataTable();
1030         if ( add_filters ) {
1031             _dt_add_filters(this, table_dt);
1032         }
1033
1034         table.DataTable().on("column-visibility.dt", function(){_dt_on_visibility(add_filters, table, table_dt);})
1035             .columns( hidden_ids ).visible( false );
1036
1037         return table;
1038     };
1039
1040 })(jQuery);