Bug 30063: Be more flexible for filters
[koha.git] / koha-tmpl / intranet-tmpl / prog / en / includes / patron-search.inc
1 [% USE Koha %]
2 [% USE I18N %]
3 [% USE Branches %]
4 [% USE raw %]
5 [% USE Asset %]
6 [% USE To %]
7
8 [%# Display a simple form %]
9 [% BLOCK patron_search_filters_simple  %]
10     <form id="patron_search_form">
11         <div class="hint">Enter patron card number or partial name:</div>
12         <input type="text" size="40" id="search_patron_filter" class="focus" autocomplete="off" />
13         <input type="submit" value="Search" />
14     </form>
15 [% END %]
16
17 [%# Display a complex patron search form %]
18 [%# - Search: <input> %]
19 [%# You can then pass a list of filters %]
20 [%# - branch: <select library list> %]
21 [%# - category: <select patron category list> %]
22 [%# - search_field: <select patron field list> %]
23 [%# - search_type: <select "contain" or "start with"> %]
24 [% BLOCK patron_search_filters %]
25     <form id="patron_search_form">
26         <fieldset class="brief">
27             <h3>Search for patron</h3>
28             <ol>
29                 <li>
30                     <label for="search_patron_filter">Search:</label>
31                     <input type="text" id="search_patron_filter" value="[% search_filter | html %]" class="focus" />
32                 </li>
33
34                 [% FOR f IN filters %]
35                     [% SWITCH f %]
36                     [% CASE 'branch' %]
37                         <li>
38                             <label for="branchcode_filter">Library:</label>
39                             <select id="branchcode_filter">
40                                 [% SET libraries = Branches.all( only_from_group => 1 ) %]
41                                 [% IF libraries.size != 1 %]
42                                     <option value="">Any</option>
43                                 [% END %]
44                                 [% FOREACH l IN libraries %]
45                                     <option value="[% l.branchcode | html %]">[% l.branchname | html %]</option>
46                                 [% END %]
47                             </select>
48                         </li>
49                     [% CASE 'category' %]
50                         <li>
51                             <label for="categorycode_filter">Category:</label>
52                             <select id="categorycode_filter">
53                                 <option value="">Any</option>
54                                 [% FOREACH category IN categories %]
55                                     <option value="[% category.categorycode | html %]">[% category.description | html %]</option>
56                                 [% END %]
57                             </select>
58                         </li>
59                     [% CASE 'search_field' %]
60                         <li>
61                             <label for="searchfieldstype_filter">Search field:</label>
62                             <select name="searchfieldstype" id="searchfieldstype_filter">
63                                 [% pref_fields = Koha.Preference('DefaultPatronSearchFields').split(',') %]
64                                 [% default_fields = [ 'surname,firstname,othernames,cardnumber,userid', 'surname', 'cardnumber', 'email', 'borrowernumber', 'userid', 'phone', 'address', 'dateofbirth', 'sort1', 'sort2' ] %]
65                                 [% search_options = default_fields.merge(pref_fields).unique %]
66                                 [% FOREACH s_o IN search_options %]
67                                     [% display_name = PROCESS patron_fields name=s_o %]
68                                     [% NEXT IF !display_name %]
69                                     [% IF searchfieldstype == s_o %]
70                                         <option selected="selected" value=[% s_o | html %]>[% display_name | $raw %]</option>
71                                     [% ELSE %]
72                                         <option value=[% s_o | html %]>[% display_name | $raw %]</option>
73                                     [% END %]
74                                 [% END %]
75                             </select>
76                         </li>
77                     [% CASE 'search_type' %]
78                         <li>
79                             <label for="searchtype_filter">Search type:</label>
80                             <select name="searchtype" id="searchtype_filter">
81                               [% IF searchtype == "start_with" %]
82                                 <option value='start_with' selected="selected">Starts with</option>
83                                 <option value="contain">Contains</option>
84                               [% ELSE %]
85                                 <option value='start_with'>Starts with</option>
86                                 <option value="contain" selected="selected">Contains</option>
87                               [% END %]
88                             </select>
89                         </li>
90                     [% END %]
91                 [% END %]
92             </ol>
93             <fieldset class="action">
94                 <input type="submit" value="Search" />
95                 <input type="button" value="Clear" id="clear_search" />
96             </fieldset>
97         </fieldset>
98     </form>
99 [% END %]
100
101 [%# Display the table with: %]
102 [%# - At the top a hint about a possible filter %]
103 [%# - Browse by last name %]
104 [%# - The table %]
105 [%# Get the following parameters: %]
106 [%# - filter: can be 'suggestions_managers', 'orders_managers', 'funds_owners' or 'funds_users' to filter patrons on their permissions %]
107 [%# - table_id: the ID of the table %]
108 [%# open_on_row_click: See patron_search_js %]
109 [%# columns: See patron_search_js %]
110 [% BLOCK patron_search_table %]
111
112     [% IF filter == 'suggestions_managers' %]
113         <div class="hint">Only staff with superlibrarian or suggestions_manage permissions are returned in the search results</div>
114     [% ELSIF filter == 'orders_managers' %]
115         <div class="hint">Only staff with superlibrarian or acquisitions permissions (or order_manage permission if granular permissions are enabled) are returned in the search results</div>
116     [% ELSIF filter == 'funds_owners' OR filter == 'funds_users' %]
117         <div class="hint">Only staff with superlibrarian or acquisitions permissions (or budget_modify permission if granular permissions are enabled) are returned in the search results</div>
118     [% END %]
119
120     <div class="browse">
121         Browse by last name:
122         [% SET alphabet = Koha.Preference('alphabet').split(' ') %]
123         [% UNLESS alphabet.size %]
124             [% alphabet = ['A' .. 'Z'] %]
125         [% END %]
126         [% FOREACH letter IN alphabet %]
127             <a href="#" class="filterByLetter">[% letter | html %]</a>
128         [% END %]
129     </div>
130
131
132     <h3 style="display: none;">Patrons found for: <span id="searchpattern"></span></h3>
133
134     <div id="[% table_id | html %]_search_results" style="display:none;">
135
136         <div id="info" class="dialog message" style="display: none;"></div>
137         <div id="error" class="dialog alert" style="display: none;"></div>
138
139         <input type="hidden" id="firstletter_filter" value="" />
140         [% IF open_on_row_click %]
141         <table id="[% table_id | html %]" class="selections-table">
142         [% ELSE %]
143         <table id="[% table_id | html %]">
144         [% END %]
145             <thead>
146                 <tr>
147                     [% FOR column IN columns %]
148                         [% SWITCH column %]
149                             [% CASE 'checkbox' %]<th class="noExport"></th>
150                             [% CASE 'cardnumber' %]<th>Card</th>
151                             [% CASE 'dateofbirth' %]<th>Date of birth</th>
152                             [% CASE 'name' %]<th>Name</th>
153                             [% CASE 'name-address' %]<th>Name</th>
154                             [% CASE 'address' %]<th>Address</th>
155                             [% CASE 'address-library' %]<th>Address</th>
156                             [% CASE 'branch' %]<th data-filter="libraries">Library</th>
157                             [% CASE 'category' %]<th data-filter="categories">Category</th>
158                             [% CASE 'dateexpiry' %]<th>Expires on</td>
159                             [% CASE 'borrowernotes' %]<th>Notes</th>
160                             [% CASE 'phone' %]<th>Phone</th>
161                             [% CASE 'checkouts' %]<th>Checkouts</th>
162                             [% CASE 'account_balance' %]<th>Fines</th>
163                             [% CASE 'action' %]<th>&nbsp;</th>
164                         [% END %]
165                     [% END %]
166                 </tr>
167               </thead>
168             <tbody></tbody>
169         </table>
170     </div>
171
172 <!-- Patron preview modal -->
173 <div class="modal" id="patronPreview" tabindex="-1" role="dialog" aria-labelledby="patronPreviewLabel">
174     <div class="modal-dialog" role="document">
175         <div class="modal-content">
176             <div class="modal-header">
177                 <button type="button" class="closebtn" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
178                 <h4 class="modal-title" id="patronPreviewLabel"></h4>
179             </div>
180             <div class="modal-body">
181                 <div id="loading">
182                     <img src="[% interface | html %]/[% theme | html %]/img/spinner-small.gif" alt="" /> Loading
183                 </div>
184             </div>
185             <div class="modal-footer">
186                 <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
187             </div>
188         </div>
189     </div>
190 </div>
191
192 [% END %]
193
194 [%# Integrate all the JS code, outside of a script tag %]
195 [%# Get the following parameters: %]
196 [%# - redirect_if_one_result: Redirect to the patron if the search returns only one result, note that it will not redirect if filters of the DT are used (this is a feature) %]
197 [%# - redirect_url: The URL to use, the borrowernumber parameter will be added %]
198 [%# filter: Same as patron_search_table %]
199 [%# open_on_row_click: boolean, default off. Will allow to select a patron by clicking on the whole tr element %]
200 [%# columns: list of columns that will be displayed. Possible values are: 'checkbox', 'cardnumber', 'dateofbirth', 'address', 'name', 'name-address', 'branch', 'category', 'dateexpiry', 'borrowernotes, 'phone', 'checkouts', 'account_balance', 'action' %]
201 [%# preview_on_name_click: Open a modal window with patron's info when the name is clicked %]
202 [%# actions: list of buttons to display in the action column. Possible values are: 'select', 'add', 'edit', 'checkout' %]
203 [%# sticky_header and sticky_to: If we need a sticky header %]
204 [%# callback: name of the JS function that will be called when a patron is selected. Only work with action=select %]
205 [%# display_search_description: boolean, default off. Display the description of the search %]
206 [% BLOCK patron_search_js %]
207
208     [% IF redirect_if_one_result && !redirect_url %]
209         <script>console.log("Wrong call of patron_searh_js - missing redirect_url");</script>
210     [% END %]
211     <script>
212         let categories = [% To.json(categories) | $raw %].map(e => {
213             e['_id'] = e.categorycode;
214             e['_str'] = e.description;
215             return e;
216         });
217         let categories_map = categories.reduce((map, e) => {
218             map[e._id] = e;
219             return map;
220         }, {});
221         let libraries  = [% To.json(libraries) | $raw %].map(e => {
222             e['_id'] = e.branchcode;
223             e['_str'] = e.branchname;
224             return e;
225         });
226         let libraries_map = libraries.reduce((map, e) => {
227             map[e._id] = e;
228             return map;
229         }, {});
230
231         [% IF Koha.Preference('ExtendedPatronAttributes') && extended_attribute_types %]
232             let extended_attribute_types = [% To.json(extended_attribute_types || []) | $raw %];
233         [% END %]
234
235     </script>
236
237     [% INCLUDE 'datatables.inc' %]
238     [% INCLUDE 'js-date-format.inc' %]
239     [% INCLUDE 'js-patron-get-age.inc' %]
240     [% INCLUDE 'js-patron-format.inc' %]
241     [% INCLUDE 'js-patron-format-address.inc' %]
242     [% IF sticky_header %]
243         [% Asset.js("lib/hc-sticky.js") | $raw %]
244     [% END %]
245
246     <script>
247         var first_draw = 0;
248         let patrons_table;
249         var Sticky;
250         var singleBranchMode = '[% singleBranchMode | html %]';
251         let logged_in_library_id = "[% Branches.GetLoggedInBranchcode | html %]";
252
253         /* popstate event triggered by forward and back button. Need to refresh search */
254         window.addEventListener('popstate', (event) => {
255             getSearchByLocation( false );
256         });
257
258         $(document).ready(function(){
259
260             $("#info").hide();
261             $("#error").hide();
262
263             // Build the aLengthMenu
264             var aLengthMenu = [
265                 [% Koha.Preference('PatronsPerPage') | html %], 10, 20, 50, 100, -1
266             ];
267             jQuery.unique(aLengthMenu);
268             aLengthMenu.sort(function( a, b ){
269                 // Put "All" at the end
270                 if ( a == -1 ) {
271                     return 1;
272                 } else if ( b == -1 ) {
273                     return -1;
274                 }
275                 return parseInt(a) < parseInt(b) ? -1 : 1;}
276             );
277             var aLengthMenuLabel = [];
278             $(aLengthMenu).each(function(){
279                 if ( this == -1 ) {
280                     // Label for -1 is "All"
281                     aLengthMenuLabel.push(_("All"));
282                 } else {
283                     aLengthMenuLabel.push(this);
284                 }
285             });
286
287             let additional_filters = {
288                 surname: function(){
289                     let start_with = $("#firstletter_filter").val()
290                     if (!start_with) return "";
291                     return { "like": start_with + "%" }
292                 },
293                 "-and": function(){
294                     let filter = $("#search_patron_filter").val();
295                     if (!filter) return "";
296
297                     let filters = [];
298                     let search_type = $("#searchtype_filter").val() || "contain";
299                     let search_fields = $("#searchfieldstype_filter").val();
300                     if ( !search_fields ) {
301                         search_fields = "[% Koha.Preference('DefaultPatronSearchFields') || 'surname,firstname,othernames,cardnumber,userid' | html %]";
302                     }
303                     search_fields.split(',').forEach(function(e,i){
304                         filters.push({["me."+e]:{"like":"%"+filter+(search_type == "contain" ? "%" : "" )}});
305                     });
306                     [% IF Koha.Preference('ExtendedPatronAttributes') && extended_attribute_types %]
307                         filters.push({
308                             "extended_attributes.value": { "like": "%" + filter + (search_type == "contain" ? "%" : "" )},
309                             "extended_attributes.code": extended_attribute_types
310                         });
311                     [% END %]
312                     return filters;
313                 }
314             };
315             [% UNLESS default_sort_column %]
316                 [% default_sort_column = "name" %]
317             [% END %]
318             [% SET order_column_index = 0 %]
319             [% SET embed = ['extended_attributes'] %]
320             patrons_table = $("#[% table_id | html %]").kohaTable({
321                 "ajax": {
322                     [% SWITCH filter %]
323                     [% CASE 'suggestions_managers' %]
324                         "url": '/api/v1/suggestions/managers',
325                     [% CASE 'baskets_managers' %]
326                         "url": '/api/v1/acquisitions/baskets/managers',
327                     [% CASE 'funds_owners' %]
328                         "url": '/api/v1/acquisitions/funds/owners',
329                     [% CASE 'funds_users' %]
330                         "url": '/api/v1/acquisitions/funds/users',
331                     [% CASE %]
332                         "url": '/api/v1/patrons',
333                     [% END %]
334                     "dataSrc": function ( json ) {
335                         [% IF redirect_if_one_result %]
336                             // redirect if there is only 1 result.
337                             if ( first_draw && json.recordsFiltered == 1 ) {
338                                 let url = '[% redirect_url | url %]'.indexOf("?") != -1
339                                     ? '[% redirect_url | url %]&borrowernumber=' + json.data[0].patron_id
340                                     : '[% redirect_url | url %]?borrowernumber=' + json.data[0].patron_id;
341                                 document.location.href = url;
342                                 return false;
343                             }
344                             first_draw = 0;
345                         [% END %]
346                         return json.data;
347                     }
348                 },
349                 [% IF open_on_row_click OR preview_on_name_click %]
350                 "drawCallback": function( settings ) {
351                     var api = this.api();
352                     var data = api.data();
353                     if ( data.length == 0 ) return;
354
355                     [% IF open_on_row_click %]
356                     $.each($(this).find("tbody tr"), function(index, tr) {
357                         let url = "[% on_click_url | url %]&borrowernumber=" + data[index].patron_id;
358                         $(tr).off('click').on('click', function() {
359                             document.location.href = url;
360                         }).addClass('clickable');
361                         $(tr).find("a.patron_name").attr('href', url);
362                     });
363                     [% END %]
364                     [% IF preview_on_name_click %]
365                     $.each($(this).find("tbody tr"), function(index, tr) {
366                         $(tr).find("a.patron_name").addClass("patron_preview");
367                     });
368                     [% END %]
369                 },
370                 [% END %]
371                 "iDeferLoading": 0,
372                 "columns": [
373                     [% FOR column IN columns %]
374                         [% IF default_sort_column == column %]
375                             [% order_column_index = loop.count - 1%]
376                         [% END %]
377                         [% SWITCH column %]
378                             [% CASE 'checkbox' %]
379                             {
380                                 "data": "patron_id",
381                                 "searchable": false,
382                                 "orderable": false,
383                                 "render": function( data, type, row, meta ) {
384                                     return "<label for='check" + data + "' class='content_hidden'>" + _("Select patron") + "</label><input type='checkbox' id='check" + data + "' class='selection' name='borrowernumber' value='" + data + "' />";
385                                 }
386                             }
387                             [% CASE 'cardnumber' %]
388                             {
389                                 "data": "cardnumber",
390                                 "searchable": true,
391                                 "orderable": true,
392                                 "render": function( data, type, row, meta ) {
393                                     let patron_id = encodeURIComponent(row.patron_id);
394                                     [% IF !open_on_row_click AND CAN_user_circulate_circulate_remaining_permissions %]
395                                         return "<a href=\"/cgi-bin/koha/circ/circulation.pl?borrowernumber=" + patron_id + "\" title=\"[% I18N.t("Check out") | html %]\" class=\"patron_name\" data-borrowernumber=\"" + patron_id + "\" style=\"white-space:nowrap\">" + escape_str(data) + "</a>";
396                                     [% ELSE %]
397                                         return escape_str(data);
398                                     [% END %]
399                                 }
400
401                             }
402                             [% CASE 'dateofbirth' %]
403                             {
404                                 "data": "date_of_birth",
405                                 "searchable": true,
406                                 "orderable": true,
407                                 "render": function( data, type, row, meta ) {
408                                     return data ? escape_str($date(data) + " (" + _("%s years").format($get_age(data)) + ")") : "";
409                                 }
410                             }
411                             [% CASE 'address' %]
412                             {
413                                 "data": "me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
414                                 "searchable": true,
415                                 "orderable": true,
416                                  "render": function( data, type, row, meta ) {
417                                     let r = '<div class="address"><ul>';
418                                     r += $format_address(row, { no_line_break: 1 });
419                                     r += '</div></ul>';
420                                     return r;
421                                 }
422                             }
423                             [% CASE 'address-library' %]
424                             {
425                                 "data": "me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
426                                 "searchable": true,
427                                 "orderable": true,
428                                 "render": function( data, type, row, meta ) {
429                                     let r = '<div class="address"><ul>';
430                                     r += $format_address(row, { no_line_break: 1 });
431                                     r += '</div></ul>';
432                                     r += " " + escape_str(libraries_map[row.library_id].branchname);
433                                     return r;
434                                 }
435                             }
436                             [% CASE 'name-address' %]
437                             {
438                                 "data": "me.firstname:me.surname:me.othernames:me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
439                                 "searchable": true,
440                                 "orderable": true,
441                                 "render": function( data, type, row, meta ) {
442                                     let patron_id = encodeURIComponent(row.patron_id);
443                                     let r = '';
444                                     [% IF ! open_on_row_click %]
445                                     r += "<a href=\"/cgi-bin/koha/members/moremember.pl?borrowernumber=" + patron_id + "\" class=\"patron_name\" data-borrowernumber=\"" + patron_id + "\" style=\"white-space:nowrap\">" + $patron_to_html(row, { invert_name: 1 }) + "</a>";
446                                     [% ELSE %]
447                                     r += $patron_to_html(row, { invert_name: 1 });
448                                     [% END %]
449                                     r += '<br/>';
450                                     r += '<div class="address"><ul>';
451                                     r += $format_address(row, { no_line_break: 1 });
452
453                                     if ( row.email ) {
454                                         r += "<li>" + _("Email: ") + "<a href='mailto:" + encodeURIComponent(row.email) + "'>" + escape_str(row.email) + "</a></li>";
455                                     }
456                                     r += '</ul></div>'
457
458                                     return r;
459                                 }
460                             }
461                             [% CASE 'name-address' %]
462                             {
463                                 "data": "me.firstname:me.surname:me.othernames:me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
464                                 "searchable": true,
465                                 "orderable": true,
466                                 "render": function( data, type, row, meta ) {
467                                     let patron_id = encodeURIComponent(row.patron_id);
468                                     let r = '';
469                                     [% IF ! open_on_row_click %]
470                                     r += "<a href=\"/cgi-bin/koha/members/moremember.pl?borrowernumber=" + patron_id + "\" class=\"patron_name\" data-borrowernumber=\"" + patron_id + "\" style=\"white-space:nowrap\">" + $patron_to_html(row, { invert_name: 1 }) + "</a>";
471                                     [% ELSE %]
472                                     r += $patron_to_html(row, { invert_name: 1 });
473                                     [% END %]
474                                     r += '<br/>';
475                                     r += '<div class="address"><ul>';
476                                     r += $format_address(row, { no_line_break: 1 });
477
478                                     if ( row.email ) {
479                                         r += "<li>" + _("Email: ") + "<a href='mailto:" + encodeURIComponent(row.email) + "'>" + escape_str(row.email) + "</a></li>";
480                                     }
481                                     r += '</ul></div>'
482
483                                     return r;
484                                 }
485                             }
486                             [% CASE 'name' %]
487                             {
488                                 "data": "me.firstname:me.surname:me.othernames",
489                                 "searchable": true,
490                                 "orderable": true,
491                                 "render": function( data, type, row, meta ) {
492                                     let patron_id = encodeURIComponent(row.patron_id);
493                                     [% IF ! open_on_row_click %]
494                                     return "<a href=\"/cgi-bin/koha/members/moremember.pl?borrowernumber=" + patron_id + "\" class=\"patron_name\" data-borrowernumber=\"" + patron_id + "\" style=\"white-space:nowrap\">" + $patron_to_html(row, { invert_name: 1 }) + "</a>";
495                                     [% ELSE %]
496                                     return $patron_to_html(row, { invert_name: 1 });
497                                     [% END %]
498                                 }
499                             }
500                             [% CASE 'branch' %]
501                             {
502                                 "data": "library_id",
503                                 "searchable": true,
504                                 "orderable": true,
505                                 "render": function( data, type, row, meta ) {
506                                     let library_name = libraries_map[data].branchname
507                                     if( !singleBranchMode && data == logged_in_library_id ) {
508                                         return "<span class=\"currentlibrary\">" + escape_str(library_name) + "</span>";
509                                     } else {
510                                         return escape_str(library_name);
511                                     }
512                                 }
513                             }
514                             [% CASE 'category' %]
515                             {
516                                 "data": "category_id",
517                                 "searchable": true,
518                                 "orderable": true,
519                                 "render": function( data, type, row, meta ) {
520                                     return escape_str(categories_map[data].description);
521                                 }
522                             }
523                             [% CASE 'dateexpiry' %]
524                             {
525                                 "data": "expiry_date",
526                                 "searchable": true,
527                                 "orderable": true,
528                                 "render": function( data, type, row, meta ) {
529                                     return data ? escape_str($date(data)) : "";
530                                 }
531                             }
532                             [% CASE 'borrowernotes' %]
533                             {
534                                 "data": "staff_notes",
535                                 "searchable": true,
536                                 "orderable": true,
537                                 [%# We don't escape here, we allow html tag in staff notes %]
538                             }
539                             [% CASE 'phone' %]
540                             {
541                                 "data": "phone",
542                                 "searchable": true,
543                                 "orderable": true,
544                                 "render": function( data, type, row, meta ) {
545                                     return escape_str(data);
546                                 }
547                             }
548                             [% CASE 'checkouts' %][% embed.push('checkouts+count', 'overdues+count') %]
549                             {
550                                 "data": "",
551                                 "searchable": false,
552                                 "orderable": false,
553                                 "render": function( data, type, row, meta ) {
554                                     if ( row.overdues_count ) {
555                                         return "<span class='overdue'><strong>"+row.overdues_count + "</strong></span>";
556                                     } else {
557                                         return "0 / " + row.checkouts_count;
558                                     }
559                                 }
560                             }
561                             [% CASE 'account_balance' %][% embed.push('account_balance') %]
562                             {
563                                 "data": "",
564                                 "searchable": false,
565                                 "orderable": false,
566                                 "render": function( data, type, row, meta ) {
567                                     let r = "<span style='text-align: right; display: block;'><a href=\"/cgi-bin/koha/members/boraccount.pl?borrowernumber="+row.patron_id+"\">";
568                                     let balance_str = row.account_balance || 0;
569                                     balance_str = balance_str.escapeHtml().format_price();
570                                     if ( row.account_balance < 0 ) {
571                                         // FIXME Format price here
572                                         r += "<span class='credit'>" + balance_str + "</span>";
573                                     } else if ( row.account_balance > 0 ) {
574                                         r += "<span class='debit'><strong>" + balance_str  + "</strong></span>"
575                                     } else {
576                                         r += balance_str;
577                                     }
578                                     r += "</a></span>";
579                                     return r;
580                                 }
581                             }
582
583                             [% CASE 'action' %]
584                             {
585                                 "data": function( row, type, val, meta ) {
586
587                                     let patron_id = encodeURIComponent(row.patron_id);
588                                     let action_node = "";
589                                     [% FOR action IN actions %]
590                                     [% SWITCH action %]
591                                     [% CASE 'select' %]
592                                         action_node += '<a href="#" class="btn btn-default btn-xs select_user" data-borrowernumber="' + patron_id + '">Select</a><input type="hidden" id="borrower_data' + patron_id + '" name="borrower_data'+ patron_id + '" value=\''+JSON.stringify(row)+'\' />';
593                                     [% CASE 'add' %]
594                                         action_node += '<a href="#" class="btn btn-default btn-xs add_user" data-borrowernumber="' + patron_id + '" data-firstname="' + encodeURIComponent(row.firstname) + '" data-surname="' + encodeURIComponent(row.surname) + '">Add</a><input type="hidden" id="borrower_data' + patron_id + '" name="borrower_data'+ patron_id + '" />';
595                                     [% CASE 'edit' %]
596                                         action_node += '<a href="/cgi-bin/koha/members/memberentry.pl?op=modify&amp;destination=circ&amp;borrowernumber=' + patron_id + '" class="btn btn-default btn-xs"><i class="fa fa-pencil"></i> Edit</a>';
597                                     [% CASE 'checkout' %]
598                                         [% IF CAN_user_circulate_circulate_remaining_permissions %]
599                                             action_node += '<a class="btn btn-default btn-xs" href="/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + patron_id + '"><i class="fa fa-barcode"></i> ' + _("Check out") + '</a>';
600                                         [% END %]
601                                     [% END %]
602                                     [% END %]
603                                     return action_node;
604                                 },
605                                 "searchable": false,
606                                 "orderable": false
607                             }
608                         [% END %]
609                         [% UNLESS loop.last %],[% END %]
610                     [% END %]
611                 ],
612                 'embed': [% To.json(embed) | $raw %],
613                 "order": [[ [% order_column_index | html %], "asc" ]],
614                 'bAutoWidth': false,
615                 'lengthMenu': [aLengthMenu, aLengthMenuLabel],
616                 'sPaginationType': 'full_numbers',
617                 "pageLength": [% Koha.Preference('PatronsPerPage') | html %],
618                 [% IF sticky_header %]
619                 "initComplete": function(settings, json) {
620                     $("#[% sticky_header %]").show();
621                     Sticky = $("#[% sticky_header | html %]");
622                     Sticky.hcSticky({
623                         stickTo: "#[% sticky_to | html %]",
624                         stickyClass: "floating"
625                     });
626                 },
627                 [% END %]
628             }, typeof table_settings !== 'undefined' ? table_settings : null, 1, additional_filters);
629
630             $("#patron_search_form").on('submit', filter);
631             $(".filterByLetter").on("click",function(e){
632                 e.preventDefault();
633                 filterByFirstLetterSurname($(this).text(), true);
634             });
635             $("body").on("click",".add_user",function(e){
636                 e.preventDefault();
637                 var borrowernumber = $(this).data("borrowernumber");
638                 var firstname = $(this).data("firstname");
639                 var surname = $(this).data("surname");
640                 add_user( borrowernumber, firstname + " " + surname );
641             });
642
643             $("body").on("click",".select_user",function(e){
644                 e.preventDefault();
645                 var borrowernumber = $(this).data("borrowernumber");
646                 var borrower_data = $("#borrower_data"+borrowernumber).val();
647                 select_user( borrowernumber, JSON.parse(borrower_data) );
648             });
649
650             $("body").on("click",".patron_preview", function( e ){
651                 e.preventDefault();
652                 var borrowernumber = $(this).data("borrowernumber");
653                 var page = "/cgi-bin/koha/members/moremember.pl?print=brief&borrowernumber=" + borrowernumber;
654                 $("#patronPreview .modal-body").load( page + " div.container-fluid" );
655                 $('#patronPreview').modal({show:true});
656             });
657
658             $("#patronPreview").on('hidden.bs.modal', function (e) {
659                 $("#patronPreview .modal-body").html("<img src=\"[% interface | html %]/[% theme | html %]/img/spinner-small.gif\" alt=\"\" /> Loading");
660             });
661
662             $("#clear_search").on("click",function(e){
663                 e.preventDefault();
664                 clearFilters();
665                 $("#searchpattern").parent().hide();
666             });
667
668             if ( $("#search_patron_filter").val().length > 0 ) {
669                 $("#patron_search_form").submit();
670             }
671
672             /* Initial page load does not trigger the popstate event, so we explicitly call this */
673             getSearchByLocation( false );
674
675         });
676
677         function getSearchByLocation( setstate ){
678             /* Check to see if the URL contains a search parameter */
679             if( location.search != ""){
680                 var params = new URLSearchParams( location.search );
681                 var firstletter = params.get("firstletter");
682                 /* Check to see if search is a first letter param */
683                 if( firstletter ){
684                     /* Trigger function to return search results by letter */
685                     filterByFirstLetterSurname( firstletter, setstate );
686                 }
687             }
688         }
689
690         function update_search_description(){
691             var searched = $("#searchfieldstype_filter").find("option:selected").text();
692             if ( $("#search_patron_filter").val() ) {
693                 if ( $("#searchtype_filter").val() == 'start_with' ) {
694                     searched += _(" starting with ");
695                 } else {
696                     searched += _(" containing ");
697                 }
698                 searched += "'" + $("#search_patron_filter").val() + "'";
699             }
700             if ( $("#firstletter_filter").val() ) {
701                 searched += _(" begins with ") + "'" + $("#firstletter_filter").val() +"'";
702             }
703             if ( $("#categorycode_filter").val() ) {
704                 searched += _(" with category ") + "'" + $("#categorycode_filter").find("option:selected").text() + "'";
705             }
706             if ( $("#branchcode_filter").val() ) {
707                 searched += _(" in library ") + $("#branchcode_filter").find("option:selected").text();
708             }
709             $("#searchpattern").text(searched);
710             $("#searchpattern").parent().show();
711         }
712
713         function filter() {
714             $("#firstletter_filter").val('');
715             $("#[% table_id | html %]_search_results").show();
716
717             let table_dt = patrons_table.DataTable();
718             [% FOR c IN columns %]
719                 [% SWITCH c %]
720                 [% CASE 'branch' %]
721                     library_id = $("#branchcode_filter").val() || "";
722                     patrons_table.find('thead tr:eq(1) th[data-filter="libraries"] select').val(library_id);
723                     table_dt.column([% loop.count - 1 %]).search(library_id ? '^'+library_id+'$' : '');
724                 [% CASE 'category' %]
725                     let category_id = $("#categorycode_filter").val() || "";
726                     patrons_table.find('thead tr:eq(1) th[data-filter="categories"] select').val(category_id);
727                     table_dt.column([% loop.count - 1 %]).search(category_id ? '^'+category_id+'$' : '');
728                 [% END %]
729             [% END %]
730             table_dt.search("");
731             first_draw = 1; // Only redirect if we are coming from here
732             table_dt.draw();
733             [% IF display_search_description %]
734                 update_search_description();
735             [% END %]
736             return false;
737         }
738
739         function clearFilters() {
740             $("#searchfieldstype_filter option:first").prop("selected", true);
741             $("#searchtype_filter option[value='contain']").prop("selected", true);
742             $("#categorycode_filter option:first").prop("selected", true);
743             $("#branchcode_filter option:first").prop("selected", true);
744             $("#firstletter_filter").val('');
745             $("#search_patron_filter").val('');
746             /* remove any search string added by firstletter search */
747             history.pushState( {}, null, window.location.href.split("?" )[0]);
748             $("#[% table_id | html %]_search_results").hide();
749             [% IF display_search_description %]
750                 update_search_description();
751             [% END %]
752         }
753
754         // User has clicked on a letter
755         function filterByFirstLetterSurname(letter, setstate ) {
756             $("#firstletter_filter").val(letter);
757
758             $("#[% table_id | html %]_search_results").show();
759
760             if ( setstate ) {
761                 history.pushState( null, null, "?firstletter=" + letter );
762             }
763
764             patrons_table.DataTable().draw();
765             [% IF display_search_description %]
766                 update_search_description();
767             [% END %]
768         }
769
770         // modify parent window owner element
771         function add_user(borrowernumber, borrowername) {
772             var p = window.opener;
773             // In one place (serials/routing.tt), the page is reload on every add
774             // We have to wait for the page to be there
775             function wait_for_opener () {
776                 if ( ! $(opener.document).find('body').size() ) {
777                     setTimeout(wait_for_opener, 500);
778                 } else {
779                     [%# Note that add_user could sent data instead of borrowername too %]
780                     $("#info").hide();
781                     $("#error").hide();
782                     if ( p.add_user(borrowernumber, borrowername) < 0 ) {
783                         $("#error").html(_("Patron '%s' is already in the list.").format(borrowername));
784                         $("#error").show();
785                     } else {
786                         $("#info").html(_("Patron '%s' added.").format(borrowername));
787                         $("#info").show();
788                     }
789                 }
790             }
791             wait_for_opener();
792         }
793         function select_user(borrowernumber, data) {
794             var p = window.opener;
795             [%  IF callback %]
796                 p.[% callback | html %](borrowernumber, data);
797             [%  ELSE %]
798                 p.select_user(borrowernumber, data);
799             [%  END %]
800             window.close();
801         }
802     </script>
803 [% END %]