4 * Search, checkout, items out, holds, bills, edit, etc.
7 angular.module('egPatronApp', ['ngRoute', 'ui.bootstrap',
8 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod', 'ngToast'])
10 .config(['ngToastProvider', function(ngToastProvider) {
11 ngToastProvider.configure({
12 verticalPosition: 'bottom',
17 .config(function($routeProvider, $locationProvider, $compileProvider) {
18 $locationProvider.html5Mode(true);
19 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
21 // data loaded at startup which only requires an authtoken goes
22 // here. this allows the requests to be run in parallel instead of
23 // waiting until startup has completed.
24 var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
26 // fetch the org settings we care about during egStartup
27 // and toss them into egCore.env as egCore.env.aous[name] = value.
28 // note: only load settings here needed by all tabs; load tab-
29 // specific settings from within their respective controllers
30 egCore.env.classLoaders.aous = function() {
31 return egCore.org.settings([
32 'ui.staff.require_initials.patron_info_notes',
33 'circ.do_not_tally_claims_returned',
36 'ui.circ.show_billing_tab_on_bills',
37 'circ.patron_expires_soon_warning',
38 'ui.circ.items_out.lost',
39 'ui.circ.items_out.longoverdue',
40 'ui.circ.items_out.claimsreturned'
41 ]).then(function(settings) {
42 // local settings are cached within egOrg. Caching them
43 // again in egEnv just simplifies the syntax for access.
44 egCore.env.aous = settings;
48 egCore.env.loadClasses.push('aous');
50 // app-globally modify the default flesh fields for
51 // fleshed user retrieval.
52 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
53 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
63 return egCore.startup.go().then(function() {
65 // This call requires orgs to be loaded, because it
66 // calls egCore.org.ancestors(), so call it after startup
67 return egCore.pcrud.search('actsc',
68 {owner : egCore.org.ancestors(
69 egCore.auth.user().ws_ou(), true)},
71 ).then(function(cats) {
72 egCore.env.absorbList(cats, 'actsc');
77 $routeProvider.when('/circ/patron/search', {
78 templateUrl: './circ/patron/t_search',
79 controller: 'PatronSearchCtrl',
83 $routeProvider.when('/circ/patron/bcsearch', {
84 templateUrl: './circ/patron/t_bcsearch',
85 controller: 'PatronBarcodeSearchCtrl',
89 $routeProvider.when('/circ/patron/credentials', {
90 templateUrl: './circ/patron/t_credentials',
91 controller: 'PatronVerifyCredentialsCtrl',
95 $routeProvider.when('/circ/patron/last', {
96 templateUrl: './circ/patron/t_last_patron',
97 controller: 'PatronFetchLastCtrl',
101 // the following require a patron ID
103 $routeProvider.when('/circ/patron/:id/alerts', {
104 templateUrl: './circ/patron/t_alerts',
105 controller: 'PatronAlertsCtrl',
109 $routeProvider.when('/circ/patron/:id/checkout', {
110 templateUrl: './circ/patron/t_checkout',
111 controller: 'PatronCheckoutCtrl',
115 $routeProvider.when('/circ/patron/:id/items_out', {
116 templateUrl: './circ/patron/t_items_out',
117 controller: 'PatronItemsOutCtrl',
121 $routeProvider.when('/circ/patron/:id/holds', {
122 templateUrl: './circ/patron/t_holds',
123 controller: 'PatronHoldsCtrl',
127 $routeProvider.when('/circ/patron/:id/holds/create', {
128 templateUrl: './circ/patron/t_holds_create',
129 controller: 'PatronHoldsCreateCtrl',
133 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
134 templateUrl: './circ/patron/t_holds',
135 controller: 'PatronHoldsCtrl',
139 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
140 templateUrl: './circ/patron/t_hold_details',
141 controller: 'PatronHoldDetailsCtrl',
145 $routeProvider.when('/circ/patron/:id/bills', {
146 templateUrl: './circ/patron/t_bills',
147 controller: 'PatronBillsCtrl',
151 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
152 templateUrl: './circ/patron/t_xact_details',
153 controller: 'XactDetailsCtrl',
157 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
158 templateUrl: './circ/patron/t_bill_history',
159 controller: 'BillHistoryCtrl',
163 $routeProvider.when('/circ/patron/:id/messages', {
164 templateUrl: './circ/patron/t_messages',
165 controller: 'PatronMessagesCtrl',
169 $routeProvider.when('/circ/patron/:id/edit', {
170 templateUrl: './circ/patron/t_edit',
171 controller: 'PatronRegCtrl',
175 $routeProvider.when('/circ/patron/:id/credentials', {
176 templateUrl: './circ/patron/t_credentials',
177 controller: 'PatronVerifyCredentialsCtrl',
181 $routeProvider.when('/circ/patron/:id/notes', {
182 templateUrl: './circ/patron/t_notes',
183 controller: 'PatronNotesCtrl',
187 $routeProvider.when('/circ/patron/:id/triggered_events', {
188 templateUrl: './circ/patron/t_triggered_events',
189 controller: 'PatronTriggeredEventsCtrl',
193 $routeProvider.when('/circ/patron/:id/message_center', {
194 templateUrl: './circ/patron/t_message_center',
195 controller: 'PatronMessageCenterCtrl',
199 $routeProvider.when('/circ/patron/:id/edit_perms', {
200 templateUrl: './circ/patron/t_edit_perms',
201 controller: 'PatronPermsCtrl',
205 $routeProvider.when('/circ/patron/:id/group', {
206 templateUrl: './circ/patron/t_group',
207 controller: 'PatronGroupCtrl',
211 $routeProvider.when('/circ/patron/:id/stat_cats', {
212 templateUrl: './circ/patron/t_stat_cats',
213 controller: 'PatronStatCatsCtrl',
217 $routeProvider.when('/circ/patron/:id/surveys', {
218 templateUrl: './circ/patron/t_surveys',
219 controller: 'PatronSurveyCtrl',
223 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
229 .factory('patronSvc',
230 ['$q','$timeout','$location','egCore','egUser','$locale',
231 function($q , $timeout , $location , egCore, egUser , $locale) {
234 // cached patron search results
237 // currently selected patron object
240 // patron circ stats (overdues, fines, holds)
243 // event types manually overridden, which should always be
244 // overridden for checkouts to this patron for this instance of
246 checkout_overrides : {},
247 //holds the searched barcode
248 search_barcode : null,
251 // when we change the default patron, we need to clear out any
252 // data collected on that patron
253 service.resetPatronLists = function() {
254 service.checkouts = [];
255 service.items_out = []
256 service.items_out_ids = [];
258 service.hold_ids = [];
259 service.checkout_overrides = {};
260 service.patron_stats = null;
261 service.noncat_ids = [];
262 service.hasAlerts = false;
263 service.patronExpired = false;
264 service.patronExpiresSoon = false;
265 service.invalidAddresses = false;
267 service.resetPatronLists(); // initialize
269 // Returns true if the last alerted patron matches the current
270 // patron. Otherwise, the last alerted patron is set to the
271 // current patron and false is returned.
272 service.alertsShown = function() {
273 var key = 'eg.circ.last_alerted_patron';
274 var last_id = egCore.hatch.getSessionItem(key);
275 if (last_id && last_id == service.current.id()) return true;
276 egCore.hatch.setSessionItem(key, service.current.id());
280 // shortcut to force-reload the current primary
281 service.refreshPrimary = function() {
282 if (!service.current) return $q.when();
283 return service.setPrimary(service.current.id(), null, true);
286 // clear the currently focused user
287 service.clearPrimary = function() {
288 // reset with no patron
289 service.resetPatronLists();
290 service.current = null;
291 service.patron_stats = null;
295 // sets the primary display user, fetching data as necessary.
296 service.setPrimary = function(id, user, force) {
297 var user_id = id ? id : (user ? user.id() : null);
299 console.debug('setting primary user to: ' + user_id);
301 if (!user_id) return $q.reject();
303 // when loading a new patron, update the last patron setting
304 if (!service.current || service.current.id() != user_id)
305 egCore.hatch.setLoginSessionItem('eg.circ.last_patron', user_id);
307 // avoid running multiple retrievals for the same patron, which
308 // can happen during dbl-click by maintaining a single running
309 // data retrieval promise
310 if (service.primaryUserPromise) {
311 if (service.primaryUserId == user_id) {
312 return service.primaryUserPromise.promise;
314 service.primaryUserPromise = null;
318 service.primaryUserPromise = $q.defer();
319 service.primaryUserId = user_id;
321 service.getPrimary(id, user, force)
323 service.checkAlerts();
324 var p = service.primaryUserPromise;
325 service.primaryUserId = null;
326 // clear before resolution just to be safe.
327 service.primaryUserPromise = null;
331 return service.primaryUserPromise.promise;
334 service.getPrimary = function(id, user, force) {
337 if (!force && service.current &&
338 service.current.id() == user.id()) {
339 if (service.patron_stats) {
342 return service.fetchUserStats();
346 service.resetPatronLists();
347 service.current = user;
348 service.localFlesh(user);
349 return service.fetchUserStats();
352 if (!force && service.current && service.current.id() == id) {
353 if (service.patron_stats) {
356 return service.fetchUserStats();
360 service.resetPatronLists();
362 return egUser.get(id).then(
364 service.current = user;
365 service.localFlesh(user);
366 return service.fetchUserStats();
370 "unable to fetch user "+id+': '+js2JSON(err))
375 // fetching a null user clears the primary user.
376 // NOTE: this should probably reject() and log an error,
377 // but calling clear for backwards compat for now.
378 return service.clearPrimary();
382 // flesh some additional user fields locally
383 service.localFlesh = function(user) {
384 if (!angular.isObject(typeof user.home_ou()))
385 user.home_ou(egCore.org.get(user.home_ou()));
388 user.standing_penalties(),
390 if (!angular.isObject(penalty.org_unit()))
391 penalty.org_unit(egCore.org.get(penalty.org_unit()));
395 // stat_cat_entries == stat_cat_entry_user_map
396 angular.forEach(user.stat_cat_entries(), function(map) {
397 if (angular.isObject(map.stat_cat())) return;
398 // At page load, we only retrieve org-visible stat cats.
399 // For the common case, ignore entries for remote stat cats.
400 var cat = egCore.env.actsc.map[map.stat_cat()];
403 cat.owner(egCore.org.get(cat.owner()));
408 // resolves to true if the patron account has expired or will
409 // expire soon, based on YAOUS circ.patron_expires_soon_warning
410 // note: returning a promise is no longer strictly necessary
411 // (no more async activity) if the calling function is changed too.
412 service.testExpire = function() {
414 var expire = Date.parse(service.current.expire_date());
415 if (expire < new Date()) {
416 return $q.when(service.patronExpired = true);
419 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
421 var preExpire = new Date();
422 preExpire.setDate(preExpire.getDate() + Number(soon));
423 if (expire < preExpire)
424 return $q.when(service.patronExpiresSoon = true);
427 return $q.when(false);
430 // resolves to true if the patron account has any invalid addresses.
431 service.testInvalidAddrs = function() {
433 if (service.invalidAddresses)
434 return $q.when(true);
439 service.current.addresses(),
440 function(addr) { if (addr.valid() == 'f') fail = true }
443 return $q.when(fail);
445 //resolves to true if the patron was fetched with an inactive card
446 service.fetchedWithInactiveCard = function() {
447 var bc = service.search_barcode
448 var cards = service.current.cards();
449 var card = cards.filter(function(c) { return c.barcode() == bc })[0];
450 return (card && card.active() == 'f');
452 // resolves to true if there is any aspect of the patron account
453 // which should produce a message in the alerts panel
454 service.checkAlerts = function() {
456 if (service.hasAlerts) // already checked
457 return $q.when(true);
459 var deferred = $q.defer();
460 var p = service.current;
462 if (service.alert_penalties.length ||
466 service.patron_stats.holds.ready) {
468 service.hasAlerts = true;
471 // see if the user was retrieved with an inactive card
472 if(service.fetchedWithInactiveCard()){
473 service.hasAlerts = true;
476 // regardless of whether we know of alerts, we still need
477 // to test/fetch the expire data for display
478 service.testExpire().then(function(bool) {
479 if (bool) service.hasAlerts = true;
480 deferred.resolve(service.hasAlerts);
483 service.testInvalidAddrs().then(function(bool) {
484 if (bool) service.invalidAddresses = true;
485 deferred.resolve(service.invalidAddresses);
488 return deferred.promise;
491 service.fetchGroupFines = function() {
492 return egCore.net.request(
494 'open-ils.actor.usergroup.members.balance_owed',
495 egCore.auth.token(), service.current.usrgroup()
496 ).then(function(list) {
498 angular.forEach(list, function(u) {
499 total += 100 * Number(u.balance_owed)
501 service.patron_stats.fines.group_balance_owed = total / 100;
505 service.getUserStats = function(id) {
506 return egCore.net.request(
508 'open-ils.actor.user.opac.vital_stats.authoritative',
509 egCore.auth.token(), id
512 // force numeric to ensure correct boolean handling in templates
513 stats.fines.balance_owed = Number(stats.fines.balance_owed);
514 stats.checkouts.overdue = Number(stats.checkouts.overdue);
515 stats.checkouts.claims_returned =
516 Number(stats.checkouts.claims_returned);
517 stats.checkouts.lost = Number(stats.checkouts.lost);
518 stats.checkouts.out = Number(stats.checkouts.out);
519 stats.checkouts.total_out =
520 stats.checkouts.out + stats.checkouts.overdue;
522 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
523 stats.checkouts.total_out += stats.checkouts.claims_returned;
525 if (egCore.env.aous['circ.tally_lost'])
526 stats.checkouts.total_out += stats.checkouts.lost
533 // Fetches the IDs of any active non-cat checkouts for the current
534 // user. Also sets the patron_stats non_cat count value to match.
535 service.getUserNonCats = function(id) {
536 return egCore.net.request(
538 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
539 egCore.auth.token(), id
540 ).then(function(noncat_ids) {
541 service.noncat_ids = noncat_ids;
542 service.patron_stats.checkouts.noncat = noncat_ids.length;
546 // grab additional circ info
547 service.fetchUserStats = function() {
548 return service.getUserStats(service.current.id())
549 .then(function(stats) {
550 service.patron_stats = stats
551 service.alert_penalties = service.current.standing_penalties()
552 .filter(function(pen) {
553 return pen.standing_penalty().staff_alert() == 't'
556 service.summary_stat_cats = [];
557 angular.forEach(service.current.stat_cat_entries(),
559 if (angular.isObject(map.stat_cat()) &&
560 map.stat_cat().usr_summary() == 't') {
561 service.summary_stat_cats.push(map);
566 // run these two in parallel
567 var p1 = service.getUserNonCats(service.current.id());
568 var p2 = service.fetchGroupFines();
569 return $q.all([p1, p2]);
573 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
574 // which is the Angular default.
575 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
576 // FIXME: This change needs to be moved into a project-wide collection
577 // of locale overrides.
578 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
579 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
585 * Manages tabbed patron view.
586 * This is the parent scope of all patron tab scopes.
589 .controller('PatronCtrl',
590 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
591 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
593 $scope.is_patron_edit = function() {
594 return Boolean($location.path().match(/patron\/\d+\/edit$/));
597 // To support the fixed position patron edit actions bar,
598 // its markup has to live outside the scope of the patron
599 // edit controller. Insert a scope blob here that can be
600 // modifed from within the patron edit controller.
601 $scope.edit_passthru = {};
603 // returns true if a redirect occurs
604 function redirectToAlertPanel() {
606 $scope.alert_penalties =
607 function() {return patronSvc.alert_penalties}
609 if (patronSvc.alertsShown()) return false;
611 // if the patron has any unshown alerts, show them now
612 if (patronSvc.hasAlerts &&
613 !$location.path().match(/alerts$/)) {
616 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
617 .search('card', null);
621 // no alert required. If the patron has fines and the show-bills
622 // OUS is applied, direct to the bills page.
623 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
624 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
625 && !$location.path().match(/bills$/)) {
627 $scope.tab = 'bills';
629 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
630 .search('card', null);
638 // called after each route-specified controller is instantiated.
639 // this doubles as a way to inform the top-level controller that
640 // egStartup.go() has completed, which means we are clear to
641 // fetch the patron, etc.
642 $scope.initTab = function(tab, patron_id) {
643 console.log('init tab ' + tab);
645 $scope.aous = egCore.env.aous;
648 $scope.patron_id = patron_id;
649 return patronSvc.setPrimary($scope.patron_id)
650 .then(function() {return patronSvc.checkAlerts()})
651 .then(redirectToAlertPanel);
656 $scope._show_dob = {};
657 $scope.show_dob = function (val) {
658 if ($scope.patron()) {
659 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
660 return $scope._show_dob[$scope.patron().id()];
662 return !egCore.env.aous['circ.obscure_dob'];
665 $scope.obscure_dob = function() {
666 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
668 $scope.now_show_dob = function() {
669 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
670 $scope.show_dob() : true;
673 $scope.patron = function() { return patronSvc.current }
674 $scope.patron_stats = function() { return patronSvc.patron_stats }
675 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
676 $scope.hasAlerts = function() { return patronSvc.hasAlerts }
677 $scope.isPatronExpired = function() { return patronSvc.patronExpired }
679 $scope.print_address = function(addr) {
682 template : 'patron_address',
684 patron : egCore.idl.toHash(patronSvc.current),
685 address : egCore.idl.toHash(addr)
690 $scope.toggle_expand_summary = function() {
691 if ($scope.collapsePatronSummary) {
692 $scope.collapsePatronSummary = false;
693 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
695 $scope.collapsePatronSummary = true;
696 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
700 // always expand the patron summary in the search UI, regardless
701 // of stored preference.
702 $scope.collapse_summary = function() {
703 return $scope.tab != 'search' && $scope.collapsePatronSummary;
706 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
707 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
710 .controller('PatronBarcodeSearchCtrl',
711 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
712 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
713 $scope.selectMe = true; // focus text input
714 patronSvc.clearPrimary(); // clear the default user
716 // jump to the patron checkout UI
717 function loadPatron(user_id) {
718 egCore.audio.play('success.patron.by_barcode');
720 .path('/circ/patron/' + user_id + '/checkout')
721 .search('card', $scope.args.barcode);
722 patronSvc.search_barcode = $scope.args.barcode;
725 // create an opt-in=yes response for the loaded user
726 function createOptIn(user_id) {
729 'open-ils.actor.user.org_unit_opt_in.create',
730 egCore.auth.token(), user_id).then(function(resp) {
731 if (evt = egCore.evt.parse(resp)) return alert(evt);
737 $scope.submitBarcode = function(args) {
738 $scope.bcNotFound = null;
739 $scope.optInRestricted = false;
740 if (!args.barcode) return;
742 // blur so next time it's set to true it will re-apply select()
743 $scope.selectMe = false;
750 'open-ils.actor.get_barcodes',
751 egCore.auth.token(), egCore.auth.user().ws_ou(),
752 'actor', args.barcode)
754 .then(function(resp) { // get_barcodes
756 if (evt = egCore.evt.parse(resp)) {
761 if (!resp || !resp[0]) {
762 $scope.bcNotFound = args.barcode;
763 $scope.selectMe = true;
764 egCore.audio.play('warning.patron.not_found');
768 // see if an opt-in request is needed
769 user_id = resp[0].id;
770 return egCore.net.request(
772 'open-ils.actor.user.org_unit_opt_in.check',
773 egCore.auth.token(), user_id);
775 }).then(function(optInResp) { // opt_in_check
777 if (evt = egCore.evt.parse(optInResp)) {
782 if (optInResp == 2) {
783 // opt-in disallowed at this location by patron's home library
784 $scope.optInRestricted = true;
785 $scope.selectMe = true;
786 egCore.audio.play('warning.patron.opt_in_restricted');
790 if (optInResp == 1) {
791 // opt-in handled or not needed
792 return loadPatron(user_id);
795 // opt-in needed, show the opt-in dialog
796 egUser.get(user_id, {useFields : []})
798 .then(function(user) { // retrieve user
799 egConfirmDialog.open(
800 egCore.strings.OPT_IN_DIALOG, '',
801 { org : egCore.org.get(user.home_ou()),
803 ok : function() { createOptIn(user.id()) },
804 cancel : function() {}
814 * Manages patron search
816 .controller('PatronSearchCtrl',
817 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
818 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
819 'egPatronMerge','egProgressDialog',
820 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
821 $filter, egUser, patronSvc , egGridDataProvider , $document,
822 egPatronMerge , egProgressDialog) {
824 $scope.initTab('search');
825 $scope.focusMe = true;
826 $scope.searchArgs = {
827 // default to searching globally
828 home_ou : egCore.org.tree()
831 // last used patron search form element
834 $scope.gridControls = {
835 activateItem : function(item) {
836 $location.path('/circ/patron/' + item.id() + '/checkout');
838 selectedItems : function() {return []}
841 // Handle URL-encoded searches
842 if ($location.search().search) {
843 console.log('URL search = ' + $location.search().search);
844 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
846 // why the double-JSON encoded sort?
847 if (patronSvc.urlSearch.search.search_sort) {
848 patronSvc.urlSearch.sort =
849 JSON2js(patronSvc.urlSearch.search.search_sort);
851 patronSvc.urlSearch.sort = [];
853 delete patronSvc.urlSearch.search.search_sort;
855 // include inactive patrons if "inactive" param
856 if ($location.search().inactive) {
857 patronSvc.urlSearch.inactive = $location.search().inactive;
862 var propagate_inactive;
863 if (patronSvc.lastSearch) {
864 propagate = patronSvc.lastSearch.search;
865 // home_ou needs to be treated specially
866 propagate.home_ou = {
867 value : patronSvc.lastSearch.home_ou,
870 } else if (patronSvc.urlSearch) {
871 propagate = patronSvc.urlSearch.search;
872 if (patronSvc.urlSearch.inactive) {
873 propagate_inactive = patronSvc.urlSearch.inactive;
877 if (egCore.env.pgt) {
878 $scope.profiles = egCore.env.pgt.list;
880 egCore.pcrud.search('pgt', {parent : null},
881 {flesh : -1, flesh_fields : {pgt : ['children']}}
884 egCore.env.absorbTree(tree, 'pgt')
885 $scope.profiles = egCore.env.pgt.list;
891 // populate the search form with our cached / preexisting search info
892 angular.forEach(propagate, function(val, key) {
893 if (key == 'profile')
894 val.value = $scope.profiles.filter(function(p) { return p.id() == val.value })[0];
895 if (key == 'home_ou')
896 val.value = egCore.org.get(val.value);
897 $scope.searchArgs[key] = val.value;
899 if (propagate_inactive) {
900 $scope.searchArgs.inactive = propagate_inactive;
904 var provider = egGridDataProvider.instance({});
907 function() {return $scope.gridControls.selectedItems()},
910 patronSvc.setPrimary(null, list[0]);
915 provider.get = function(offset, count) {
916 var deferred = $q.defer();
919 if (patronSvc.urlSearch) {
920 fullSearch = patronSvc.urlSearch;
921 // enusre the urlSearch only runs once.
922 delete patronSvc.urlSearch;
925 patronSvc.search_barcode = $scope.searchArgs.card;
927 var search = compileSearch($scope.searchArgs);
928 if (Object.keys(search) == 0) return $q.when();
930 var home_ou = search.home_ou;
931 delete search.home_ou;
932 var inactive = search.inactive;
933 delete search.inactive;
937 sort : compileSort(),
943 fullSearch.count = count;
944 fullSearch.offset = offset;
946 if (patronSvc.lastSearch) {
947 // search repeated, return the cached results
948 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
949 console.log('patron search returning ' +
950 patronSvc.patrons.length + ' cached results');
952 // notify has to happen after returning the promise
955 angular.forEach(patronSvc.patrons, function(user) {
956 deferred.notify(user);
961 return deferred.promise;
965 patronSvc.lastSearch = fullSearch;
967 if (fullSearch.search.id) {
968 // search by user id performs a direct ID lookup
969 var userId = fullSearch.search.id.value;
972 egUser.get(userId).then(function(user) {
973 patronSvc.localFlesh(user);
974 patronSvc.patrons = [user];
975 deferred.notify(user);
980 return deferred.promise;
983 if (!Object.keys(fullSearch.search).length) {
984 // Empty searches are rejected by the server. Avoid
985 // running the the empty search that runs on page load.
989 egProgressDialog.open(); // Indeterminate
991 patronSvc.patrons = [];
992 var which_sound = 'success';
995 'open-ils.actor.patron.search.advanced.fleshed',
1000 fullSearch.inactive,
1002 egUser.defaultFleshFields,
1009 function() { // onerror
1010 which_sound = 'error';
1013 // hide progress bar as soon as the first result appears.
1014 egProgressDialog.close();
1015 patronSvc.localFlesh(user); // inline
1016 patronSvc.patrons.push(user);
1017 deferred.notify(user);
1019 )['finally'](function() { // close on 0-hits or error
1020 if (which_sound == 'success' && patronSvc.patrons.length == 0) {
1021 which_sound = 'warning';
1023 egCore.audio.play(which_sound + '.patron.by_search');
1024 egProgressDialog.close();
1027 return deferred.promise;
1030 $scope.patronSearchGridProvider = provider;
1032 // determine the tree depth of the profile group
1033 $scope.pgt_depth = function(grp) {
1035 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
1039 $scope.clearForm = function () {
1040 $scope.searchArgs={};
1041 if (lastFormElement) lastFormElement.focus();
1044 $scope.applyShowExtras = function($event, bool) {
1046 $scope.showExtras = true;
1047 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
1049 $scope.showExtras = false;
1050 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
1052 if (lastFormElement) lastFormElement.focus();
1053 $event.preventDefault();
1056 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
1057 .then(function(val) {$scope.showExtras = val});
1059 // map form arguments into search params
1060 function compileSearch(args) {
1062 angular.forEach(args, function(val, key) {
1064 if (key == 'profile' && args.profile) {
1065 search.profile = {value : args.profile.id(), group : 0};
1066 } else if (key == 'home_ou' && args.home_ou) {
1067 search.home_ou = args.home_ou.id(); // passed separately
1068 } else if (key == 'inactive') {
1069 search.inactive = val;
1071 search[key] = {value : val, group : 0};
1073 if (key.match(/phone|ident/)) {
1074 search[key].group = 2;
1076 if (key.match(/street|city|state|post_code/)) {
1077 search[key].group = 1;
1078 } else if (key == 'card') {
1079 search[key].group = 3
1087 function compileSort() {
1089 if (!provider.sort.length) {
1092 "first_given_name ASC",
1093 "second_given_name ASC",
1102 if (angular.isObject(sortdef)) {
1103 var name = Object.keys(sortdef)[0];
1104 var dir = sortdef[name];
1105 sort.push(name + ' ' + dir);
1115 $scope.setLastFormElement = function() {
1116 lastFormElement = $document[0].activeElement;
1119 // search form submit action; tells the results grid to
1121 $scope.search = function(args) { // args === $scope.searchArgs
1122 if (args && Object.keys(args).length)
1123 $scope.gridControls.refresh();
1124 if (lastFormElement) lastFormElement.focus();
1127 // TODO: move this into the (forthcoming) grid row activate action
1128 $scope.onPatronDblClick = function($event, user) {
1129 $location.path('/circ/patron/' + user.id() + '/checkout');
1132 if (patronSvc.urlSearch) {
1133 // force the grid to load the url-based search on page load
1137 $scope.need_two_selected = function() {
1138 var items = $scope.gridControls.selectedItems();
1139 return (items.length == 2) ? false : true;
1141 $scope.merge_patrons = function() {
1142 var items = $scope.gridControls.selectedItems();
1143 if (items.length != 2) return false;
1145 var patron_ids = [];
1146 angular.forEach(items, function(i) {
1147 patron_ids.push(i.id());
1149 egPatronMerge.do_merge(patron_ids).then(function() {
1150 // ensure that we're not drawing from cached
1151 // resuts, as a successful merge just deleted a
1153 delete patronSvc.lastSearch;
1154 $scope.gridControls.refresh();
1163 .controller('PatronMessagesCtrl',
1164 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
1165 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
1166 $scope.initTab('messages', $routeParams.id);
1167 var usr_id = $routeParams.id;
1169 // setup date filters
1170 var start = new Date(); // now - 1 year
1171 start.setFullYear(start.getFullYear() - 1),
1174 end_date : new Date()
1177 function date_range() {
1178 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1179 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1180 var today = new Date().toISOString().replace(/T.*/,'');
1181 if (end == today) end = 'now';
1182 return [start, end];
1187 var activeGrid = $scope.activeGridControls = {
1188 setSort : function() {
1189 return ['set_date'];
1191 setQuery : function() {
1196 {stop_date : {'>' : 'now'}}
1202 var archiveGrid = $scope.archiveGridControls = {
1203 setSort : function() {
1204 return ['set_date'];
1206 setQuery : function() {
1209 stop_date : {'<=' : 'now'},
1210 set_date : {between : date_range()}
1215 $scope.removePenalty = function(selected) {
1216 // the grid stores flattened penalties. Fetch penalty objects first
1218 var ids = selected.map(function(s){ return s.id });
1219 egCore.pcrud.search('ausp',
1221 {atomic : true, authoritative : true}
1224 ).then(function(penalties) {
1225 return egCore.pcrud.remove(penalties);
1227 // then refresh the grid
1228 }).then(function() {
1229 activeGrid.refresh();
1233 $scope.archivePenalty = function(selected) {
1234 // the grid stores flattened penalties. Fetch penalty objects first
1236 var ids = selected.map(function(s){ return s.id });
1237 egCore.pcrud.search('ausp',
1239 {atomic : true, authoritative : true}
1242 ).then(function(penalties) {
1243 angular.forEach(penalties, function(p){ p.stop_date('now') });
1244 return egCore.pcrud.update(penalties);
1246 // then refresh the grid
1247 }).then(function() {
1248 activeGrid.refresh();
1249 archiveGrid.refresh();
1253 // leverage egEnv for caching
1254 function fetchPenaltyTypes() {
1256 return $q.when(egCore.env.csp.list);
1257 return egCore.pcrud.search(
1258 // id <= 100 are reserved for system use
1259 'csp', {id : {'>': 100}}, {}, {atomic : true})
1260 .then(function(penalties) {
1261 egCore.env.absorbList(penalties, 'csp');
1266 $scope.createPenalty = function() {
1267 egCirc.create_penalty(usr_id).then(function() {
1268 activeGrid.refresh();
1269 // force a refresh of the user, since they may now
1270 // have blocking penalties, etc.
1271 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1275 $scope.editPenalty = function(selected) {
1276 if (selected.length == 0) return;
1278 // grab the penalty from the user object
1279 var penalty = patronSvc.current.standing_penalties().filter(
1280 function(p) {return p.id() == selected[0].id})[0];
1282 egCirc.edit_penalty(penalty).then(function() {
1283 activeGrid.refresh();
1284 // force a refresh of the user, since they may now
1285 // have blocking penalties, etc.
1286 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1293 * Credentials tester
1295 .controller('PatronVerifyCredentialsCtrl',
1296 ['$scope','$routeParams','$location','egCore',
1297 function($scope, $routeParams , $location , egCore) {
1298 $scope.verified = null;
1299 $scope.focusMe = true;
1301 // called with a patron, pre-populate the form args
1302 $scope.initTab('other', $routeParams.id).then(
1304 if ($routeParams.id && $scope.patron()) {
1305 $scope.prepop = true;
1306 $scope.username = $scope.patron().usrname();
1307 $scope.barcode = $scope.patron().card().barcode();
1309 $scope.username = '';
1310 $scope.barcode = '';
1311 $scope.password = '';
1316 // verify login credentials
1317 $scope.verify = function() {
1318 $scope.verified = null;
1319 $scope.notFound = false;
1323 'open-ils.actor.verify_user_password',
1324 egCore.auth.token(), $scope.barcode,
1325 $scope.username, hex_md5($scope.password || '')
1327 ).then(function(resp) {
1328 $scope.focusMe = true;
1329 if (evt = egCore.evt.parse(resp)) {
1331 } else if (resp == 1) {
1332 $scope.verified = true;
1334 $scope.verified = false;
1339 // load the main patron UI for the provided username or barcode
1340 $scope.load = function($event) {
1341 $scope.notFound = false;
1342 $scope.verified = null;
1346 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1347 egCore.auth.token(), $scope.barcode, $scope.username
1349 ).then(function(resp) {
1352 $location.path('/circ/patron/' + resp + '/checkout');
1356 // something went wrong...
1357 $scope.focusMe = true;
1358 if (evt = egCore.evt.parse(resp)) {
1359 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1360 $scope.notFound = true;
1369 // load() button sits within the verify form.
1370 // avoid submitting the verify() form action on load()
1371 $event.preventDefault();
1375 .controller('PatronAlertsCtrl',
1376 ['$scope','$routeParams','$location','egCore','patronSvc',
1377 function($scope, $routeParams , $location , egCore , patronSvc) {
1379 $scope.initTab('other', $routeParams.id)
1381 $scope.patronExpired = patronSvc.patronExpired;
1382 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1383 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1384 $scope.invalidAddresses = patronSvc.invalidAddresses;
1389 .controller('PatronNotesCtrl',
1390 ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
1392 function($scope, $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
1394 $scope.initTab('other', $routeParams.id);
1395 var usr_id = $routeParams.id;
1398 function refreshPage() {
1400 egCore.pcrud.search('aun',
1402 {flesh : 1, flesh_fields : {aun : ['creator']}},
1403 {authoritative : true})
1404 .then(null, null, function(note) {
1405 $scope.notes.push(note);
1409 // open the new-note dialog and create the note
1410 $scope.newNote = function() {
1412 templateUrl: './circ/patron/t_new_note_dialog',
1414 ['$scope', '$uibModalInstance',
1415 function($scope, $uibModalInstance) {
1416 $scope.focusNote = true;
1418 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1419 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1420 $scope.cancel = function () { $uibModalInstance.dismiss() }
1424 if (!args.value) return;
1425 var note = new egCore.idl.aun();
1427 note.title(args.title);
1428 note.value(args.value);
1429 note.pub(args.pub ? 't' : 'f');
1430 note.creator(egCore.auth.user().id());
1432 note.value(note.value() + ' [' + args.initials + ']');
1433 egCore.pcrud.create(note).then(function() {refreshPage()});
1438 // delete the selected note
1439 $scope.deleteNote = function(note) {
1440 egConfirmDialog.open(
1441 egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
1443 egCore.pcrud.remove(note).then(function() {refreshPage()});
1445 note_title : note.title(),
1446 create_date : note.create_date()
1450 // print the selected note
1451 $scope.printNote = function(note) {
1452 var hash = egCore.idl.toHash(note);
1453 hash.usr = egCore.idl.toHash($scope.patron());
1454 egCore.print.print({
1455 context : 'default',
1456 template : 'patron_note',
1457 scope : {note : hash}
1461 // perform the initial note fetch
1465 .controller('PatronGroupCtrl',
1466 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1467 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1468 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1469 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1471 var usr_id = $routeParams.id;
1473 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1475 var grid = $scope.gridControls = {
1476 activateItem : function(item) {
1477 $location.path('/circ/patron/' + item.id + '/checkout');
1479 itemRetrieved : function(item) {
1481 if (item.id == patronSvc.current.id()) {
1482 item.stats = patronSvc.patron_stats;
1485 // flesh stats for other group members
1486 patronSvc.getUserStats(item.id).then(function(stats) {
1488 $scope.totals.total_out += stats.checkouts.total_out;
1489 $scope.totals.overdue += stats.checkouts.overdue;
1493 setSort : function() {
1494 return ['create_date'];
1498 $scope.initTab('other', $routeParams.id)
1499 .then(function(redirect) {
1500 // if we are redirecting to the alerts page, avoid updating the
1502 if (redirect) return;
1503 // let initTab() fetch the user first so we can know the usrgroup
1506 usrgroup : patronSvc.current.usrgroup(),
1509 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1512 $scope.removeFromGroup = function(selected) {
1514 angular.forEach(selected, function(user) {
1515 console.debug('removing user ' + user.id + ' from group');
1520 'open-ils.actor.usergroup.new',
1521 egCore.auth.token(), user.id, true
1526 $q.all(promises).then(function() {grid.refresh()});
1529 function addUserToGroup(user) {
1530 user.usrgroup(patronSvc.current.usrgroup());
1531 user.ischanged(true);
1534 'open-ils.actor.patron.update',
1535 egCore.auth.token(), user
1537 ).then(function() {grid.refresh()});
1540 // fetch each user ("selected" has flattened users)
1541 // update the usrgroup, then update the user object
1542 // After all updates are complete, refresh the grid.
1543 function moveUsersToGroup(target_user, selected) {
1546 angular.forEach(selected, function(user) {
1548 egCore.pcrud.retrieve('au', user.id)
1550 u.usrgroup(target_user.usrgroup());
1552 return egCore.net.request(
1554 'open-ils.actor.patron.update',
1555 egCore.auth.token(), u
1561 $q.all(promises).then(function() {grid.refresh()});
1564 function showMoveToGroupConfirm(barcode, selected, outbound) {
1567 egCore.pcrud.search('ac', {barcode : barcode})
1569 // fetch the fleshed user
1570 .then(function(card) {
1572 if (!card) return; // TODO: warn user
1574 egCore.pcrud.retrieve('au', card.usr())
1575 .then(function(user) {
1578 templateUrl: './circ/patron/t_move_to_group_dialog',
1580 '$scope','$uibModalInstance',
1581 function($scope , $uibModalInstance) {
1583 $scope.selected = selected;
1584 $scope.outbound = outbound;
1586 function(count) { $uibModalInstance.close() }
1588 function () { $uibModalInstance.dismiss() }
1591 }).result.then(function() {
1593 moveUsersToGroup(user, selected);
1595 addUserToGroup(user);
1602 // selected == move selected patrons to another patron's group
1603 // !selected == patron from a different group moves into our group
1604 function moveToGroup(selected, outbound) {
1605 egPromptDialog.open(
1606 egCore.strings.GROUP_ADD_USER, '',
1607 {ok : function(value) {
1609 showMoveToGroupConfirm(value, selected, outbound);
1614 $scope.moveToGroup = function() { moveToGroup([], false) };
1615 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1617 $scope.cloneUser = function(selected) {
1618 if (!selected.length) return;
1619 var url = $location.absUrl().replace(
1621 '/patron/register/clone/' + selected[0].id);
1622 $window.open(url, '_blank').focus();
1625 $scope.retrieveSelected = function(selected) {
1626 if (!selected.length) return;
1627 angular.forEach(selected, function(usr) {
1628 $timeout(function() {
1629 var url = $location.absUrl().replace(
1631 '/patron/' + usr.id + '/checkout');
1632 $window.open(url, '_blank')
1639 .controller('PatronStatCatsCtrl',
1640 ['$scope','$routeParams','$q','egCore','patronSvc',
1641 function($scope, $routeParams , $q , egCore , patronSvc) {
1642 $scope.initTab('other', $routeParams.id)
1643 .then(function(redirect) {
1644 // Entries for org-visible stat cats are fleshed. Any others
1645 // have to be fleshed within.
1648 angular.forEach(patronSvc.current.stat_cat_entries(),
1650 if (!angular.isObject(entry.stat_cat())) {
1651 to_flesh[entry.stat_cat()] = entry;
1656 if (!Object.keys(to_flesh).length) return;
1658 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1659 .then(null, null, function(cat) { // stream
1660 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1661 to_flesh[cat.id()].stat_cat(cat);
1666 .controller('PatronSurveyCtrl',
1667 ['$scope','$routeParams','$location','egCore','patronSvc',
1668 function($scope, $routeParams , $location , egCore , patronSvc) {
1669 $scope.initTab('other', $routeParams.id);
1670 var usr_id = $routeParams.id;
1671 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1672 $scope.surveys = [];
1673 // fetch the surveys
1674 egCore.pcrud.search('asvr',
1676 {flesh : 4, flesh_fields : {
1677 asvr : ['question', 'survey', 'answer'],
1678 asv : ['responses', 'questions'],
1679 asvq : ['responses', 'question']
1681 {authoritative : true})
1682 .then(null, null, function(survey) {
1683 var sameSurveyId = false;
1684 if (survey.survey().id() && $scope.surveys.length > 0) {
1685 for (sid = 0; sid < $scope.surveys.length; sid++) {
1686 if (survey.survey().id() == $scope.surveys[sid].id()) sameSurveyId = true;
1689 if (!sameSurveyId) $scope.surveys.push(survey.survey());
1693 .controller('PatronFetchLastCtrl',
1694 ['$scope','$location','egCore',
1695 function($scope , $location , egCore) {
1697 var id = egCore.hatch.getLoginSessionItem('eg.circ.last_patron');
1698 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1700 $scope.no_last = true;
1703 .controller('PatronTriggeredEventsCtrl',
1704 ['$scope','$routeParams','$location','egCore','patronSvc',
1705 function($scope, $routeParams, $location , egCore , patronSvc) {
1706 $scope.initTab('other', $routeParams.id);
1708 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1709 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1711 $scope.triggered_events_url = url;
1715 .controller('PatronMessageCenterCtrl',
1716 ['$scope','$routeParams','$location','egCore','patronSvc',
1717 function($scope, $routeParams, $location , egCore , patronSvc) {
1718 $scope.initTab('other', $routeParams.id);
1720 var url = $location.protocol() + '://' + $location.host()
1721 + egCore.env.basePath.replace(/\/staff.*/, '/actor/user/message');
1722 url += '/' + encodeURIComponent($routeParams.id);
1724 $scope.message_center_url = url;
1728 .controller('PatronPermsCtrl',
1729 ['$scope','$routeParams','$window','$location','egCore',
1730 function($scope , $routeParams , $window , $location , egCore) {
1731 $scope.initTab('other', $routeParams.id);
1733 var url = $location.absUrl().replace(
1734 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1736 url += '?usr=' + encodeURIComponent($routeParams.id);
1738 // user_edit does not load the session via cookie. It uses URL
1739 // params or xulG instead. Pass via xulG.
1741 ses : egCore.auth.token(),
1742 on_patron_save : function() {
1743 $scope.funcs.reload();
1747 $scope.user_perms_url = url;