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