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