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