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