Bug 30576: (follow-up) Corrections to behaviour to reflect unit tests
[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                                 [% SET standard = Koha.Preference('DefaultPatronSearchFields') || 'firstname,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" 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         [% IF do_not_defer_loading %]
253             let defer_loading = 0;
254         [% ELSE %]
255             let defer_loading = 1;
256         [% END %]
257
258         /* popstate event triggered by forward and back button. Need to refresh search */
259         window.addEventListener('popstate', (event) => {
260             getSearchByLocation( false );
261         });
262
263         $(document).ready(function(){
264
265             $("#info").hide();
266             $("#error").hide();
267
268             // Build the aLengthMenu
269             var aLengthMenu = [
270                 [% Koha.Preference('PatronsPerPage') | html %], 10, 20, 50, 100, -1
271             ];
272             jQuery.unique(aLengthMenu);
273             aLengthMenu.sort(function( a, b ){
274                 // Put "All" at the end
275                 if ( a == -1 ) {
276                     return 1;
277                 } else if ( b == -1 ) {
278                     return -1;
279                 }
280                 return parseInt(a) < parseInt(b) ? -1 : 1;}
281             );
282             var aLengthMenuLabel = [];
283             $(aLengthMenu).each(function(){
284                 if ( this == -1 ) {
285                     // Label for -1 is "All"
286                     aLengthMenuLabel.push(_("All"));
287                 } else {
288                     aLengthMenuLabel.push(this);
289                 }
290             });
291
292             let additional_filters = {
293                 surname: function(){
294                     let start_with = $("#firstletter_filter").val()
295                     if (!start_with) return "";
296                     return { "like": start_with + "%" }
297                 },
298                 "-and": function(){
299                     let filter = $("#search_patron_filter").val();
300                     if (!filter) return "";
301
302                     let filters = [];
303                     let search_type = $("#searchtype_filter").val() || "contain";
304                     let search_fields = $("#searchfieldstype_filter").val();
305                     if ( !search_fields ) {
306                         search_fields = "[% Koha.Preference('DefaultPatronSearchFields') || 'firstname,surname,othernames,cardnumber,userid' | html %]";
307                     }
308                     search_fields.split(',').forEach(function(e,i){
309                         filters.push({["me."+e]:{"like":(search_type == "contain" ? "%" : "" ) + filter + "%"}});
310                     });
311                     [% IF Koha.Preference('ExtendedPatronAttributes') && extended_attribute_types %]
312                         filters.push({
313                             "extended_attributes.value": { "like": "%" + filter + (search_type == "contain" ? "%" : "" )},
314                             "extended_attributes.code": extended_attribute_types
315                         });
316                     [% END %]
317                     return filters;
318                 }
319             };
320             [% UNLESS default_sort_column %]
321                 [% default_sort_column = "name" %]
322             [% END %]
323             [% SET order_column_index = 0 %]
324             [% SET embed = ['extended_attributes'] %]
325             patrons_table = $("#[% table_id | html %]").kohaTable({
326                 "ajax": {
327                     [% SWITCH filter %]
328                     [% CASE 'suggestions_managers' %]
329                         "url": '/api/v1/suggestions/managers',
330                     [% CASE 'baskets_managers' %]
331                         "url": '/api/v1/acquisitions/baskets/managers',
332                     [% CASE 'funds_owners' %]
333                         "url": '/api/v1/acquisitions/funds/owners',
334                     [% CASE 'funds_users' %]
335                         "url": '/api/v1/acquisitions/funds/users',
336                     [% CASE %]
337                         "url": '/api/v1/patrons',
338                     [% END %]
339                     "dataSrc": function ( json ) {
340                         [% IF redirect_if_one_result %]
341                             // redirect if there is only 1 result.
342                             if ( first_draw && json.recordsFiltered == 1 ) {
343                                 let url = '[% redirect_url | url %]'.indexOf("?") != -1
344                                     ? '[% redirect_url | url %]&borrowernumber=' + json.data[0].patron_id
345                                     : '[% redirect_url | url %]?borrowernumber=' + json.data[0].patron_id;
346                                 document.location.href = url;
347                                 return false;
348                             }
349                             first_draw = 0;
350                         [% END %]
351                         return json.data;
352                     }
353                 },
354                 [% IF open_on_row_click OR preview_on_name_click %]
355                 "drawCallback": function( settings ) {
356                     var api = this.api();
357                     var data = api.data();
358                     if ( data.length == 0 ) return;
359
360                     [% IF open_on_row_click %]
361                     $.each($(this).find("tbody tr"), function(index, tr) {
362                         let url = "[% on_click_url | url %]&borrowernumber=" + data[index].patron_id;
363                         $(tr).off('click').on('click', function() {
364                             document.location.href = url;
365                         }).addClass('clickable');
366                         $(tr).find("a.patron_name").attr('href', url);
367                     });
368                     [% END %]
369                     [% IF preview_on_name_click %]
370                     $.each($(this).find("tbody tr"), function(index, tr) {
371                         $(tr).find("a.patron_name").addClass("patron_preview");
372                     });
373                     [% END %]
374                 },
375                 [% END %]
376                 "iDeferLoading": defer_loading,
377                 "columns": [
378                     [% FOR column IN columns %]
379                         [% IF default_sort_column == column %]
380                             [% order_column_index = loop.count - 1%]
381                         [% END %]
382                         [% SWITCH column %]
383                             [% CASE 'checkbox' %]
384                             {
385                                 "data": "patron_id",
386                                 "searchable": false,
387                                 "orderable": false,
388                                 "render": function( data, type, row, meta ) {
389                                     return "<label for='check" + data + "' class='content_hidden'>" + _("Select patron") + "</label><input type='checkbox' id='check" + data + "' class='selection' name='borrowernumber' value='" + data + "' />";
390                                 }
391                             }
392                             [% CASE 'cardnumber' %]
393                             {
394                                 "data": "cardnumber",
395                                 "searchable": true,
396                                 "orderable": true,
397                                 "render": function( data, type, row, meta ) {
398                                     let patron_id = encodeURIComponent(row.patron_id);
399                                     [% IF !open_on_row_click AND CAN_user_circulate_circulate_remaining_permissions %]
400                                         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>";
401                                     [% ELSE %]
402                                         return escape_str(data);
403                                     [% END %]
404                                 }
405
406                             }
407                             [% CASE 'dateofbirth' %]
408                             {
409                                 "data": "date_of_birth",
410                                 "searchable": true,
411                                 "orderable": true,
412                                 "render": function( data, type, row, meta ) {
413                                     return data ? escape_str($date(data) + " (" + _("%s years").format($get_age(data)) + ")") : "";
414                                 }
415                             }
416                             [% CASE 'address' %]
417                             {
418                                 "data": "me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
419                                 "searchable": true,
420                                 "orderable": true,
421                                  "render": function( data, type, row, meta ) {
422                                     let r = '<div class="address"><ul>';
423                                     r += $format_address(row, { no_line_break: 1 });
424                                     r += '</div></ul>';
425                                     return r;
426                                 }
427                             }
428                             [% CASE 'address-library' %]
429                             {
430                                 "data": "me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
431                                 "searchable": true,
432                                 "orderable": true,
433                                 "render": function( data, type, row, meta ) {
434                                     let r = '<div class="address"><ul>';
435                                     r += $format_address(row, { no_line_break: 1 });
436                                     r += '</div></ul>';
437                                     r += " " + escape_str(libraries_map[row.library_id].branchname);
438                                     return r;
439                                 }
440                             }
441                             [% CASE 'name-address' %]
442                             {
443                                 "data": "me.surname:me.firstname:me.othernames:me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
444                                 "searchable": true,
445                                 "orderable": true,
446                                 "render": function( data, type, row, meta ) {
447                                     let patron_id = encodeURIComponent(row.patron_id);
448                                     let r = '';
449                                     [% IF ! open_on_row_click %]
450                                     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>";
451                                     [% ELSE %]
452                                     r += $patron_to_html(row, { invert_name: 1 });
453                                     [% END %]
454                                     r += '<br/>';
455                                     r += '<div class="address"><ul>';
456                                     r += $format_address(row, { no_line_break: 1 });
457
458                                     if ( row.email ) {
459                                         r += "<li>" + _("Email: ") + "<a href='mailto:" + encodeURIComponent(row.email) + "'>" + escape_str(row.email) + "</a></li>";
460                                     }
461                                     r += '</ul></div>'
462
463                                     return r;
464                                 }
465                             }
466                             [% CASE 'name-address' %]
467                             {
468                                 "data": "me.surname:me.firstname:me.othernames:me.street_number:me.address:me.address2:me.city:me.state:me.postal_code:me.country",
469                                 "searchable": true,
470                                 "orderable": true,
471                                 "render": function( data, type, row, meta ) {
472                                     let patron_id = encodeURIComponent(row.patron_id);
473                                     let r = '';
474                                     [% IF ! open_on_row_click %]
475                                     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>";
476                                     [% ELSE %]
477                                     r += $patron_to_html(row, { invert_name: 1 });
478                                     [% END %]
479                                     r += '<br/>';
480                                     r += '<div class="address"><ul>';
481                                     r += $format_address(row, { no_line_break: 1 });
482
483                                     if ( row.email ) {
484                                         r += "<li>" + _("Email: ") + "<a href='mailto:" + encodeURIComponent(row.email) + "'>" + escape_str(row.email) + "</a></li>";
485                                     }
486                                     r += '</ul></div>'
487
488                                     return r;
489                                 }
490                             }
491                             [% CASE 'name' %]
492                             {
493                                 "data": "me.surname:me.firstname:me.othernames",
494                                 "searchable": true,
495                                 "orderable": true,
496                                 "render": function( data, type, row, meta ) {
497                                     let patron_id = encodeURIComponent(row.patron_id);
498                                     [% IF ! open_on_row_click %]
499                                     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>";
500                                     [% ELSE %]
501                                     return $patron_to_html(row, { invert_name: 1 });
502                                     [% END %]
503                                 }
504                             }
505                             [% CASE 'branch' %]
506                             {
507                                 "data": "library_id",
508                                 "searchable": true,
509                                 "orderable": true,
510                                 "render": function( data, type, row, meta ) {
511                                     let library_name = libraries_map[data].branchname
512                                     if( !singleBranchMode && data == logged_in_library_id ) {
513                                         return "<span class=\"currentlibrary\">" + escape_str(library_name) + "</span>";
514                                     } else {
515                                         return escape_str(library_name);
516                                     }
517                                 }
518                             }
519                             [% CASE 'category' %]
520                             {
521                                 "data": "category_id",
522                                 "searchable": true,
523                                 "orderable": true,
524                                 "render": function( data, type, row, meta ) {
525                                     return escape_str(categories_map[data].description);
526                                 }
527                             }
528                             [% CASE 'dateexpiry' %]
529                             {
530                                 "data": "expiry_date",
531                                 "searchable": true,
532                                 "orderable": true,
533                                 "render": function( data, type, row, meta ) {
534                                     return data ? escape_str($date(data)) : "";
535                                 }
536                             }
537                             [% CASE 'borrowernotes' %]
538                             {
539                                 "data": "staff_notes",
540                                 "searchable": true,
541                                 "orderable": true,
542                                 [%# We don't escape here, we allow html tag in staff notes %]
543                             }
544                             [% CASE 'phone' %]
545                             {
546                                 "data": "phone",
547                                 "searchable": true,
548                                 "orderable": true,
549                                 "render": function( data, type, row, meta ) {
550                                     return escape_str(data);
551                                 }
552                             }
553                             [% CASE 'checkouts' %][% embed.push('checkouts+count', 'overdues+count') %]
554                             {
555                                 "data": "",
556                                 "searchable": false,
557                                 "orderable": false,
558                                 "render": function( data, type, row, meta ) {
559                                     if ( row.overdues_count ) {
560                                         return "<span class='overdue'><strong>"+row.overdues_count + "</strong></span>";
561                                     } else {
562                                         return "0 / " + row.checkouts_count;
563                                     }
564                                 }
565                             }
566                             [% CASE 'account_balance' %][% embed.push('account_balance') %]
567                             {
568                                 "data": "",
569                                 "searchable": false,
570                                 "orderable": false,
571                                 "render": function( data, type, row, meta ) {
572                                     let r = "<span style='text-align: right; display: block;'><a href=\"/cgi-bin/koha/members/boraccount.pl?borrowernumber="+row.patron_id+"\">";
573                                     let balance_str = row.account_balance || 0;
574                                     balance_str = balance_str.escapeHtml().format_price();
575                                     if ( row.account_balance < 0 ) {
576                                         // FIXME Format price here
577                                         r += "<span class='credit'>" + balance_str + "</span>";
578                                     } else if ( row.account_balance > 0 ) {
579                                         r += "<span class='debit'><strong>" + balance_str  + "</strong></span>"
580                                     } else {
581                                         r += balance_str;
582                                     }
583                                     r += "</a></span>";
584                                     return r;
585                                 }
586                             }
587
588                             [% CASE 'action' %]
589                             {
590                                 "data": function( row, type, val, meta ) {
591
592                                     let patron_id = encodeURIComponent(row.patron_id);
593                                     let action_node = "";
594                                     [% FOR action IN actions %]
595                                     [% SWITCH action %]
596                                     [% CASE 'select' %]
597                                         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)+'\' />';
598                                     [% CASE 'add' %]
599                                         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 + '" />';
600                                     [% CASE 'edit' %]
601                                         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>';
602                                     [% CASE 'checkout' %]
603                                         [% IF CAN_user_circulate_circulate_remaining_permissions %]
604                                             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>';
605                                         [% END %]
606                                     [% END %]
607                                     [% END %]
608                                     return action_node;
609                                 },
610                                 "searchable": false,
611                                 "orderable": false
612                             }
613                         [% END %]
614                         [% UNLESS loop.last %],[% END %]
615                     [% END %]
616                 ],
617                 'embed': [% To.json(embed) | $raw %],
618                 "order": [[ [% order_column_index | html %], "asc" ]],
619                 'bAutoWidth': false,
620                 'lengthMenu': [aLengthMenu, aLengthMenuLabel],
621                 'sPaginationType': 'full_numbers',
622                 "pageLength": [% Koha.Preference('PatronsPerPage') | html %],
623                 [% IF sticky_header %]
624                 "initComplete": function(settings, json) {
625                     $("#[% sticky_header | html %]").show();
626                     Sticky = $("#[% sticky_header | html %]");
627                     Sticky.hcSticky({
628                         stickTo: "#[% sticky_to | html %]",
629                         stickyClass: "floating"
630                     });
631                 },
632                 [% END %]
633             }, typeof table_settings !== 'undefined' ? table_settings : null, 1, additional_filters);
634
635             $("#patron_search_form").on('submit', filter);
636             $(".filterByLetter").on("click",function(e){
637                 e.preventDefault();
638                 filterByFirstLetterSurname($(this).text(), true);
639             });
640             $("body").on("click",".add_user",function(e){
641                 e.preventDefault();
642                 var borrowernumber = $(this).data("borrowernumber");
643                 var firstname = $(this).data("firstname");
644                 var surname = $(this).data("surname");
645                 add_user( borrowernumber, firstname + " " + surname );
646             });
647
648             $("body").on("click",".select_user",function(e){
649                 e.preventDefault();
650                 var borrowernumber = $(this).data("borrowernumber");
651                 var borrower_data = $("#borrower_data"+borrowernumber).val();
652                 select_user( borrowernumber, JSON.parse(borrower_data) );
653             });
654
655             $("body").on("click",".patron_preview", function( e ){
656                 e.preventDefault();
657                 var borrowernumber = $(this).data("borrowernumber");
658                 var page = "/cgi-bin/koha/members/moremember.pl?print=brief&borrowernumber=" + borrowernumber;
659                 $("#patronPreview .modal-body").load( page + " div.container-fluid" );
660                 $('#patronPreview').modal({show:true});
661             });
662
663             $("#patronPreview").on('hidden.bs.modal', function (e) {
664                 $("#patronPreview .modal-body").html("<img src=\"[% interface | html %]/[% theme | html %]/img/spinner-small.gif\" alt=\"\" /> Loading");
665             });
666
667             $("#clear_search").on("click",function(e){
668                 e.preventDefault();
669                 clearFilters();
670                 $("#searchpattern").parent().hide();
671             });
672
673             if ( !defer_loading ) {
674                 $("#patron_search_form").submit();
675             }
676
677             /* Initial page load does not trigger the popstate event, so we explicitly call this */
678             getSearchByLocation( false );
679
680         });
681
682         function getSearchByLocation( setstate ){
683             /* Check to see if the URL contains a search parameter */
684             if( location.search != ""){
685                 var params = new URLSearchParams( location.search );
686                 var firstletter = params.get("firstletter");
687                 /* Check to see if search is a first letter param */
688                 if( firstletter ){
689                     /* Trigger function to return search results by letter */
690                     filterByFirstLetterSurname( firstletter, setstate );
691                 }
692             }
693         }
694
695         function update_search_description(){
696             var searched = $("#searchfieldstype_filter").find("option:selected").text();
697             if ( $("#search_patron_filter").val() ) {
698                 if ( $("#searchtype_filter").val() == 'start_with' ) {
699                     searched += _(" starting with ");
700                 } else {
701                     searched += _(" containing ");
702                 }
703                 searched += "'" + $("#search_patron_filter").val() + "'";
704             }
705             if ( $("#firstletter_filter").val() ) {
706                 searched += _(" begins with ") + "'" + $("#firstletter_filter").val() +"'";
707             }
708             if ( $("#categorycode_filter").val() ) {
709                 searched += _(" with category ") + "'" + $("#categorycode_filter").find("option:selected").text() + "'";
710             }
711             if ( $("#branchcode_filter").val() ) {
712                 searched += _(" in library ") + $("#branchcode_filter").find("option:selected").text();
713             }
714             $("#searchpattern").text(searched);
715             $("#searchpattern").parent().show();
716         }
717
718         function filter() {
719             $("#firstletter_filter").val('');
720             $("#[% table_id | html %]_search_results").show();
721
722             let table_dt = patrons_table.DataTable();
723             [% FOR c IN columns %]
724                 [% SWITCH c %]
725                 [% CASE 'branch' %]
726                     library_id = $("#branchcode_filter").val() || "";
727                     patrons_table.find('thead tr:eq(1) th[data-filter="libraries"] select').val(library_id);
728                     table_dt.column([% loop.count - 1 %]).search(library_id ? '^'+library_id+'$' : '');
729                 [% CASE 'category' %]
730                     let category_id = $("#categorycode_filter").val() || "";
731                     patrons_table.find('thead tr:eq(1) th[data-filter="categories"] select').val(category_id);
732                     table_dt.column([% loop.count - 1 %]).search(category_id ? '^'+category_id+'$' : '');
733                 [% END %]
734             [% END %]
735             table_dt.search("");
736             first_draw = 1; // Only redirect if we are coming from here
737             table_dt.draw();
738             [% IF display_search_description %]
739                 update_search_description();
740             [% END %]
741             return false;
742         }
743
744         function clearFilters() {
745             $("#searchfieldstype_filter option:first").prop("selected", true);
746             $("#searchtype_filter option[value='contain']").prop("selected", true);
747             $("#categorycode_filter option:first").prop("selected", true);
748             $("#branchcode_filter option:first").prop("selected", true);
749             $("#firstletter_filter").val('');
750             $("#search_patron_filter").val('');
751             /* remove any search string added by firstletter search */
752             history.pushState( {}, null, window.location.href.split("?" )[0]);
753             $("#[% table_id | html %]_search_results").hide();
754             [% IF display_search_description %]
755                 update_search_description();
756             [% END %]
757         }
758
759         // User has clicked on a letter
760         function filterByFirstLetterSurname(letter, setstate ) {
761             $("#firstletter_filter").val(letter);
762
763             $("#[% table_id | html %]_search_results").show();
764
765             if ( setstate ) {
766                 history.pushState( null, null, "?firstletter=" + letter );
767             }
768
769             patrons_table.DataTable().draw();
770             [% IF display_search_description %]
771                 update_search_description();
772             [% END %]
773         }
774
775         // modify parent window owner element
776         function add_user(borrowernumber, borrowername) {
777             var p = window.opener;
778             // In one place (serials/routing.tt), the page is reload on every add
779             // We have to wait for the page to be there
780             function wait_for_opener () {
781                 if ( ! $(opener.document).find('body').size() ) {
782                     setTimeout(wait_for_opener, 500);
783                 } else {
784                     [%# Note that add_user could sent data instead of borrowername too %]
785                     $("#info").hide();
786                     $("#error").hide();
787                     if ( p.add_user(borrowernumber, borrowername) < 0 ) {
788                         $("#error").html(_("Patron '%s' is already in the list.").format(borrowername));
789                         $("#error").show();
790                     } else {
791                         $("#info").html(_("Patron '%s' added.").format(borrowername));
792                         $("#info").show();
793                     }
794                 }
795             }
796             wait_for_opener();
797         }
798         function select_user(borrowernumber, data) {
799             var p = window.opener;
800             [%  IF callback %]
801                 p.[% callback | html %](borrowernumber, data);
802             [%  ELSE %]
803                 p.select_user(borrowernumber, data);
804             [%  END %]
805             window.close();
806         }
807     </script>
808 [% END %]