5 angular.module('egPatronSearchMod', ['ngRoute', 'ui.bootstrap',
6 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod'])
12 ['$q','$timeout','$location','egCore','egUser','egConfirmDialog','$locale',
13 function($q , $timeout , $location , egCore, egUser , egConfirmDialog , $locale) {
16 // cached patron search results
19 // currently selected patron object
22 // patron circ stats (overdues, fines, holds)
25 // event types manually overridden, which should always be
26 // overridden for checkouts to this patron for this instance of
28 checkout_overrides : {},
29 //holds the searched barcode
30 search_barcode : null,
33 // when we change the default patron, we need to clear out any
34 // data collected on that patron
35 service.resetPatronLists = function() {
36 service.checkouts = [];
37 service.items_out = []
38 service.items_out_ids = [];
40 service.hold_ids = [];
41 service.checkout_overrides = {};
42 service.patron_stats = null;
43 service.noncat_ids = [];
44 service.hasAlerts = false;
45 service.patronExpired = false;
46 service.patronExpiresSoon = false;
47 service.invalidAddresses = false;
49 service.resetPatronLists(); // initialize
51 egCore.startup.go().then(
53 // Max recents setting is loaded and scrubbed during egStartup.
54 // Copy it to a local variable here for ease of local access
55 // after startup has run.
56 egCore.org.settings('ui.staff.max_recent_patrons')
58 service.maxRecentPatrons = s['ui.staff.max_recent_patrons'];
61 // This call requires orgs to be loaded, because it
62 // calls egCore.org.ancestors(), so call it after startup
63 egCore.pcrud.search('actsc',
64 {owner : egCore.org.ancestors(
65 egCore.auth.user().ws_ou(), true)},
67 ).then(function(cats) {
68 egCore.env.absorbList(cats, 'actsc');
73 // Returns true if the last alerted patron matches the current
74 // patron. Otherwise, the last alerted patron is set to the
75 // current patron and false is returned.
76 service.alertsShown = function() {
77 var key = 'eg.circ.last_alerted_patron';
78 var last_id = egCore.hatch.getSessionItem(key);
79 if (last_id && last_id == service.current.id()) return true;
80 egCore.hatch.setSessionItem(key, service.current.id());
84 // shortcut to force-reload the current primary
85 service.refreshPrimary = function() {
86 if (!service.current) return $q.when();
87 return service.setPrimary(service.current.id(), null, true);
90 // clear the currently focused user
91 service.clearPrimary = function() {
92 // reset with no patron
93 service.resetPatronLists();
94 service.current = null;
95 service.patron_stats = null;
99 service.getRecentPatrons = function() {
100 // avoid getting stuck in a show-recent loop
101 service.showRecent = false;
103 if (service.maxRecentPatrons < 1) return $q.when();
105 egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
107 // Ensure the cached list is no bigger than the current config.
108 // This can happen if the setting changes while logged in.
109 patrons = patrons.slice(0, service.maxRecentPatrons);
111 // add home_ou to the list of fleshed fields for recent patrons
112 var fleshFields = egUser.defaultFleshFields.slice(0);
113 fleshFields.push('home_ou');
115 var deferred = $q.defer();
117 if (patrons.length == 0) {
121 egUser.get(patrons[0], {useFields : fleshFields}).then(
122 function(usr) { // fetch first user
123 deferred.notify(usr);
124 patrons.splice(0, 1); // remove first user from list
131 return deferred.promise;
134 service.addRecentPatron = function(user_id) {
135 if (service.maxRecentPatrons < 1) return;
137 // no need to re-track same user
138 if (service.current && service.current.id() == user_id) return;
141 egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
142 patrons.splice(0, 0, user_id); // put this user at front
143 patrons.splice(service.maxRecentPatrons, 1); // remove excess
145 // remove any other occurrences of this user, which may have been
146 // added before the most recent user.
147 var idx = patrons.indexOf(user_id, 1);
148 if (idx > 0) patrons.splice(idx, 1);
150 egCore.hatch.setLoginSessionItem('eg.circ.recent_patrons', patrons);
153 // sets the primary display user, fetching data as necessary.
154 service.setPrimary = function(id, user, force) {
155 var user_id = id ? id : (user ? user.id() : null);
157 console.debug('setting primary user to: ' + user_id);
159 if (!user_id) return $q.reject();
161 service.addRecentPatron(user_id);
163 // avoid running multiple retrievals for the same patron, which
164 // can happen during dbl-click by maintaining a single running
165 // data retrieval promise
166 if (service.primaryUserPromise) {
167 if (service.primaryUserId == user_id) {
168 return service.primaryUserPromise.promise;
170 service.primaryUserPromise = null;
174 service.primaryUserPromise = $q.defer();
175 service.primaryUserId = user_id;
177 service.getPrimary(id, user, force)
179 service.checkAlerts();
180 var p = service.primaryUserPromise;
181 service.primaryUserId = null;
182 // clear before resolution just to be safe.
183 service.primaryUserPromise = null;
187 return service.primaryUserPromise.promise;
190 service.getPrimary = function(id, user, force) {
193 if (!force && service.current &&
194 service.current.id() == user.id()) {
195 if (service.patron_stats) {
198 return service.fetchUserStats();
202 service.resetPatronLists();
204 return service.checkOptIn(user).then(
206 service.current = user;
207 service.localFlesh(user);
208 return service.fetchUserStats();
216 if (!force && service.current && service.current.id() == id) {
217 if (service.patron_stats) {
220 return service.fetchUserStats();
224 service.resetPatronLists();
226 return egUser.get(id).then(
228 return service.checkOptIn(user).then(
230 service.current = user;
231 service.localFlesh(user);
232 return service.fetchUserStats();
241 "unable to fetch user "+id+': '+js2JSON(err))
246 // fetching a null user clears the primary user.
247 // NOTE: this should probably reject() and log an error,
248 // but calling clear for backwards compat for now.
249 return service.clearPrimary();
253 // flesh some additional user fields locally
254 service.localFlesh = function(user) {
255 if (!angular.isObject(typeof user.home_ou()))
256 user.home_ou(egCore.org.get(user.home_ou()));
259 user.standing_penalties(),
261 if (!angular.isObject(penalty.org_unit()))
262 penalty.org_unit(egCore.org.get(penalty.org_unit()));
266 // stat_cat_entries == stat_cat_entry_user_map
267 angular.forEach(user.stat_cat_entries(), function(map) {
268 if (angular.isObject(map.stat_cat())) return;
269 // At page load, we only retrieve org-visible stat cats.
270 // For the common case, ignore entries for remote stat cats.
271 var cat = egCore.env.actsc.map[map.stat_cat()];
274 cat.owner(egCore.org.get(cat.owner()));
279 // resolves to true if the patron account has expired or will
280 // expire soon, based on YAOUS circ.patron_expires_soon_warning
281 // note: returning a promise is no longer strictly necessary
282 // (no more async activity) if the calling function is changed too.
283 service.testExpire = function() {
285 var expire = Date.parse(service.current.expire_date());
286 if (expire < new Date()) {
287 return $q.when(service.patronExpired = true);
290 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
292 var preExpire = new Date();
293 preExpire.setDate(preExpire.getDate() + Number(soon));
294 if (expire < preExpire)
295 return $q.when(service.patronExpiresSoon = true);
298 return $q.when(false);
301 // resolves to true if the patron account has any invalid addresses.
302 service.testInvalidAddrs = function() {
304 if (service.invalidAddresses)
305 return $q.when(true);
310 service.current.addresses(),
311 function(addr) { if (addr.valid() == 'f') fail = true }
314 return $q.when(fail);
316 //resolves to true if the patron was fetched with an inactive card
317 service.fetchedWithInactiveCard = function() {
318 var bc = service.search_barcode
319 var cards = service.current.cards();
320 var card = cards.filter(function(c) { return c.barcode() == bc })[0];
321 return (card && card.active() == 'f');
323 // resolves to true if there is any aspect of the patron account
324 // which should produce a message in the alerts panel
325 service.checkAlerts = function() {
327 if (service.hasAlerts) // already checked
328 return $q.when(true);
330 var deferred = $q.defer();
331 var p = service.current;
333 if (service.alert_penalties.length ||
337 service.patron_stats.holds.ready) {
339 service.hasAlerts = true;
342 // see if the user was retrieved with an inactive card
343 if(service.fetchedWithInactiveCard()){
344 service.hasAlerts = true;
347 // regardless of whether we know of alerts, we still need
348 // to test/fetch the expire data for display
349 service.testExpire().then(function(bool) {
350 if (bool) service.hasAlerts = true;
351 deferred.resolve(service.hasAlerts);
354 service.testInvalidAddrs().then(function(bool) {
355 if (bool) service.invalidAddresses = true;
356 deferred.resolve(service.invalidAddresses);
359 return deferred.promise;
362 service.fetchGroupFines = function() {
363 return egCore.net.request(
365 'open-ils.actor.usergroup.members.balance_owed',
366 egCore.auth.token(), service.current.usrgroup()
367 ).then(function(list) {
369 angular.forEach(list, function(u) {
370 total += 100 * Number(u.balance_owed)
372 service.patron_stats.fines.group_balance_owed = total / 100;
376 service.getUserStats = function(id) {
377 return egCore.net.request(
379 'open-ils.actor.user.opac.vital_stats.authoritative',
380 egCore.auth.token(), id
383 // force numeric to ensure correct boolean handling in templates
384 stats.fines.balance_owed = Number(stats.fines.balance_owed);
385 stats.checkouts.overdue = Number(stats.checkouts.overdue);
386 stats.checkouts.claims_returned =
387 Number(stats.checkouts.claims_returned);
388 stats.checkouts.lost = Number(stats.checkouts.lost);
389 stats.checkouts.out = Number(stats.checkouts.out);
390 stats.checkouts.total_out =
391 stats.checkouts.out + stats.checkouts.overdue;
393 stats.checkouts.total_out += Number(stats.checkouts.long_overdue);
395 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
396 stats.checkouts.total_out += stats.checkouts.claims_returned;
398 if (egCore.env.aous['circ.tally_lost'])
399 stats.checkouts.total_out += stats.checkouts.lost
406 // Fetches the IDs of any active non-cat checkouts for the current
407 // user. Also sets the patron_stats non_cat count value to match.
408 service.getUserNonCats = function(id) {
409 return egCore.net.request(
411 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
412 egCore.auth.token(), id
413 ).then(function(noncat_ids) {
414 service.noncat_ids = noncat_ids;
415 service.patron_stats.checkouts.noncat = noncat_ids.length;
419 // grab additional circ info
420 service.fetchUserStats = function() {
421 return service.getUserStats(service.current.id())
422 .then(function(stats) {
423 service.patron_stats = stats
424 service.alert_penalties = service.current.standing_penalties()
425 .filter(function(pen) {
426 return pen.standing_penalty().staff_alert() == 't'
429 service.summary_stat_cats = [];
430 angular.forEach(service.current.stat_cat_entries(),
432 if (angular.isObject(map.stat_cat()) &&
433 map.stat_cat().usr_summary() == 't') {
434 service.summary_stat_cats.push(map);
439 // run these two in parallel
440 var p1 = service.getUserNonCats(service.current.id());
441 var p2 = service.fetchGroupFines();
442 return $q.all([p1, p2]);
446 service.createOptIn = function(user_id) {
447 return egCore.net.request(
449 'open-ils.actor.user.org_unit_opt_in.create',
450 egCore.auth.token(), user_id);
453 service.checkOptIn = function(user) {
454 var deferred = $q.defer();
457 'open-ils.actor.user.org_unit_opt_in.check',
458 egCore.auth.token(), user.id())
459 .then(function(optInResp) {
460 if (eg_evt = egCore.evt.parse(optInResp)) {
462 console.log('error on opt-in check: ' + eg_evt);
463 } else if (optInResp == 2) {
464 // opt-in disallowed at this location by patron's home library
466 alert(egCore.strings.OPT_IN_RESTRICTED);
467 } else if (optInResp == 1) {
468 // opt-in handled or not needed, do nothing
471 // opt-in needed, show the opt-in dialog
472 var org = egCore.org.get(user.home_ou());
473 egConfirmDialog.open(
474 egCore.strings.OPT_IN_DIALOG_TITLE,
475 egCore.strings.OPT_IN_DIALOG,
476 { family_name : user.family_name(),
477 first_given_name : user.first_given_name(),
478 org_name : org.name(),
479 org_shortname : org.shortname(),
481 service.createOptIn(user.id())
482 .then(function(resp) {
483 if (evt = egCore.evt.parse(resp)) {
491 cancel : function() { deferred.reject(); }
496 return deferred.promise;
499 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
500 // which is the Angular default.
501 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
502 // FIXME: This change needs to be moved into a project-wide collection
503 // of locale overrides.
504 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
505 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
511 * Manages patron search
513 .controller('BasePatronSearchCtrl',
514 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
515 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
517 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
518 $filter, egUser, patronSvc , egGridDataProvider , $document,
521 $scope.focusMe = true;
522 $scope.searchArgs = {
523 // default to searching globally
524 home_ou : egCore.org.tree()
527 // last used patron search form element
530 $scope.gridControls = {
531 selectedItems : function() {return []}
534 // The first time we encounter the show-recent CGI param, put the
535 // service into show-recent mode. The first time recents are shown,
536 // the service is taken out of show-recent mode so the page does not
537 // get stuck in a show-recent loop.
538 if (patronSvc.showRecent === undefined
539 && Boolean($location.path().match(/search/))
540 && Boolean($location.search().show_recent)) {
541 patronSvc.showRecent = true;
544 // Handle URL-encoded searches
545 if ($location.search().search) {
546 console.log('URL search = ' + $location.search().search);
547 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
549 // why the double-JSON encoded sort?
550 if (patronSvc.urlSearch.search.search_sort) {
551 patronSvc.urlSearch.sort =
552 JSON2js(patronSvc.urlSearch.search.search_sort);
554 patronSvc.urlSearch.sort = [];
556 delete patronSvc.urlSearch.search.search_sort;
558 // include inactive patrons if "inactive" param
559 if ($location.search().inactive) {
560 patronSvc.urlSearch.inactive = $location.search().inactive;
565 var propagate_inactive;
566 if (patronSvc.lastSearch && !patronSvc.showRecent) {
567 propagate = patronSvc.lastSearch.search;
568 // home_ou needs to be treated specially
569 propagate.home_ou = {
570 value : patronSvc.lastSearch.home_ou,
573 } else if (patronSvc.urlSearch) {
574 propagate = patronSvc.urlSearch.search;
575 if (patronSvc.urlSearch.inactive) {
576 propagate_inactive = patronSvc.urlSearch.inactive;
580 if (egCore.env.pgt) {
581 $scope.profiles = egCore.env.pgt.list;
583 egCore.pcrud.search('pgt', {parent : null},
584 {flesh : -1, flesh_fields : {pgt : ['children']}}
587 egCore.env.absorbTree(tree, 'pgt')
588 $scope.profiles = egCore.env.pgt.list;
594 // populate the search form with our cached / preexisting search info
595 angular.forEach(propagate, function(val, key) {
596 if (key == 'profile')
597 val.value = $scope.profiles.filter(function(p) { return p.id() == val.value })[0];
598 if (key == 'home_ou')
599 val.value = egCore.org.get(val.value);
600 $scope.searchArgs[key] = val.value;
602 if (propagate_inactive) {
603 $scope.searchArgs.inactive = propagate_inactive;
607 var provider = egGridDataProvider.instance({});
609 provider.get = function(offset, count) {
610 var deferred = $q.defer();
612 if (patronSvc.showRecent) {
613 // avoid getting stuck in show-recent mode
614 return patronSvc.getRecentPatrons();
618 if (patronSvc.urlSearch) {
619 fullSearch = patronSvc.urlSearch;
620 // enusre the urlSearch only runs once.
621 delete patronSvc.urlSearch;
624 patronSvc.search_barcode = $scope.searchArgs.card;
626 var search = compileSearch($scope.searchArgs);
627 if (Object.keys(search) == 0) return $q.when();
629 var home_ou = search.home_ou;
630 delete search.home_ou;
631 var inactive = search.inactive;
632 delete search.inactive;
636 sort : compileSort(),
642 fullSearch.count = count;
643 fullSearch.offset = offset;
645 if (patronSvc.lastSearch) {
646 // search repeated, return the cached results
647 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
648 console.log('patron search returning ' +
649 patronSvc.patrons.length + ' cached results');
651 // notify has to happen after returning the promise
654 angular.forEach(patronSvc.patrons, function(user) {
655 deferred.notify(user);
660 return deferred.promise;
664 patronSvc.lastSearch = fullSearch;
666 if (fullSearch.search.id) {
667 // search by user id performs a direct ID lookup
668 var userId = fullSearch.search.id.value;
671 egUser.get(userId).then(function(user) {
672 patronSvc.localFlesh(user);
673 patronSvc.patrons = [user];
674 deferred.notify(user);
679 return deferred.promise;
682 if (!Object.keys(fullSearch.search).length) {
683 // Empty searches are rejected by the server. Avoid
684 // running the the empty search that runs on page load.
688 var fleshFields = egUser.defaultFleshFields.slice(0);
689 if (fleshFields.indexOf('profile') == -1)
690 fleshFields.push('profile');
692 egProgressDialog.open(); // Indeterminate
694 patronSvc.patrons = [];
695 var which_sound = 'success';
698 'open-ils.actor.patron.search.advanced.fleshed',
712 function() { // onerror
713 which_sound = 'error';
716 // hide progress bar as soon as the first result appears.
717 egProgressDialog.close();
718 patronSvc.localFlesh(user); // inline
719 patronSvc.patrons.push(user);
720 deferred.notify(user);
722 )['finally'](function() { // close on 0-hits or error
723 if (which_sound == 'success' && patronSvc.patrons.length == 0) {
724 which_sound = 'warning';
726 egCore.audio.play(which_sound + '.patron.by_search');
727 egProgressDialog.close();
730 return deferred.promise;
733 $scope.patronSearchGridProvider = provider;
735 // determine the tree depth of the profile group
736 $scope.pgt_depth = function(grp) {
738 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
742 $scope.clearForm = function () {
743 $scope.searchArgs={};
744 if (lastFormElement) lastFormElement.focus();
747 $scope.applyShowExtras = function($event, bool) {
749 $scope.showExtras = true;
750 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
752 $scope.showExtras = false;
753 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
755 if (lastFormElement) lastFormElement.focus();
756 $event.preventDefault();
759 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
760 .then(function(val) {$scope.showExtras = val});
762 // check searchArgs.inactive setting
763 egCore.hatch.getItem('eg.circ.patron.search.include_inactive')
764 .then(function(searchInactive){
765 if (searchInactive) $scope.searchArgs.inactive = searchInactive;
768 $scope.onSearchInactiveChanged = function() {
769 egCore.hatch.setItem('eg.circ.patron.search.include_inactive', $scope.searchArgs.inactive);
772 // map form arguments into search params
773 function compileSearch(args) {
775 angular.forEach(args, function(val, key) {
777 if (key == 'profile' && args.profile) {
778 search.profile = {value : args.profile.id(), group : 5};
779 } else if (key == 'home_ou' && args.home_ou) {
780 search.home_ou = args.home_ou.id(); // passed separately
781 } else if (key == 'inactive') {
782 search.inactive = val;
783 } else if (key == 'name') { // name keywords search
784 search.name = {value: val};
786 search[key] = {value : val, group : 0};
788 if (key.match(/phone|ident/)) {
789 search[key].group = 2;
791 if (key.match(/street|city|state|post_code/)) {
792 search[key].group = 1;
793 } else if (key == 'card') {
794 search[key].group = 3
795 } else if (key.match(/dob_/)) {
796 // DOB should always be numeric
797 search[key].value = search[key].value.replace(/\D/g,'');
798 if (search[key].value.length == 0) {
802 if (!key.match(/year/)) {
803 search[key].value = ('0'+search[key].value).slice(-2);
805 search[key].group = 4;
814 function compileSort() {
816 if (!provider.sort.length) {
819 "first_given_name ASC",
820 "second_given_name ASC",
829 if (angular.isObject(sortdef)) {
830 var name = Object.keys(sortdef)[0];
831 var dir = sortdef[name];
832 sort.push(name + ' ' + dir);
842 $scope.setLastFormElement = function() {
843 lastFormElement = $document[0].activeElement;
846 // search form submit action; tells the results grid to
848 $scope.search = function(args) { // args === $scope.searchArgs
849 if (args && Object.keys(args).length)
850 $scope.gridControls.refresh();
851 if (lastFormElement) lastFormElement.focus();
854 // TODO: move this into the (forthcoming) grid row activate action
855 $scope.onPatronDblClick = function($event, user) {
856 $location.path('/circ/patron/' + user.id() + '/checkout');
859 if (patronSvc.urlSearch) {
860 // force the grid to load the url-based search on page load
864 $scope.need_two_selected = function() {
865 var items = $scope.gridControls.selectedItems();
866 return (items.length == 2) ? false : true;