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