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