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/edit_perms', {
194 templateUrl: './circ/patron/t_edit_perms',
195 controller: 'PatronPermsCtrl',
199 $routeProvider.when('/circ/patron/:id/group', {
200 templateUrl: './circ/patron/t_group',
201 controller: 'PatronGroupCtrl',
205 $routeProvider.when('/circ/patron/:id/stat_cats', {
206 templateUrl: './circ/patron/t_stat_cats',
207 controller: 'PatronStatCatsCtrl',
211 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
217 .factory('patronSvc',
218 ['$q','$timeout','$location','egCore','egUser','$locale',
219 function($q , $timeout , $location , egCore, egUser , $locale) {
222 // cached patron search results
225 // currently selected patron object
228 // patron circ stats (overdues, fines, holds)
231 // event types manually overridden, which should always be
232 // overridden for checkouts to this patron for this instance of
234 checkout_overrides : {},
235 //holds the searched barcode
236 search_barcode : null,
239 // when we change the default patron, we need to clear out any
240 // data collected on that patron
241 service.resetPatronLists = function() {
242 service.checkouts = [];
243 service.items_out = []
244 service.items_out_ids = [];
246 service.hold_ids = [];
247 service.checkout_overrides = {};
248 service.patron_stats = null;
249 service.noncat_ids = [];
250 service.hasAlerts = false;
251 service.alertsShown = false;
252 service.patronExpired = false;
253 service.patronExpiresSoon = false;
254 service.invalidAddresses = false;
256 service.resetPatronLists(); // initialize
258 // shortcut to force-reload the current primary
259 service.refreshPrimary = function() {
260 if (!service.current) return $q.when();
261 return service.setPrimary(service.current.id(), null, true);
264 // clear the currently focused user
265 service.clearPrimary = function() {
266 // reset with no patron
267 service.resetPatronLists();
268 service.current = null;
269 service.patron_stats = null;
273 // sets the primary display user, fetching data as necessary.
274 service.setPrimary = function(id, user, force) {
275 var user_id = id ? id : (user ? user.id() : null);
277 console.debug('setting primary user to: ' + user_id);
279 if (!user_id) return $q.reject();
281 // when loading a new patron, update the last patron setting
282 if (!service.current || service.current.id() != user_id)
283 egCore.hatch.setLoginSessionItem('eg.circ.last_patron', user_id);
285 // avoid running multiple retrievals for the same patron, which
286 // can happen during dbl-click by maintaining a single running
287 // data retrieval promise
288 if (service.primaryUserPromise) {
289 if (service.primaryUserId == user_id) {
290 return service.primaryUserPromise.promise;
292 service.primaryUserPromise = null;
296 service.primaryUserPromise = $q.defer();
297 service.primaryUserId = user_id;
299 service.getPrimary(id, user, force)
301 var p = service.primaryUserPromise;
302 service.primaryUserId = null;
303 // clear before resolution just to be safe.
304 service.primaryUserPromise = null;
308 return service.primaryUserPromise.promise;
311 service.getPrimary = function(id, user, force) {
314 if (!force && service.current &&
315 service.current.id() == user.id()) {
316 if (service.patron_stats) {
319 return service.fetchUserStats();
323 service.resetPatronLists();
324 service.current = user;
325 service.localFlesh(user);
326 return service.fetchUserStats();
329 if (!force && service.current && service.current.id() == id) {
330 if (service.patron_stats) {
333 return service.fetchUserStats();
337 service.resetPatronLists();
339 return egUser.get(id).then(
341 service.current = user;
342 service.localFlesh(user);
343 return service.fetchUserStats();
347 "unable to fetch user "+id+': '+js2JSON(err))
352 // fetching a null user clears the primary user.
353 // NOTE: this should probably reject() and log an error,
354 // but calling clear for backwards compat for now.
355 return service.clearPrimary();
359 // flesh some additional user fields locally
360 service.localFlesh = function(user) {
361 if (!angular.isObject(typeof user.home_ou()))
362 user.home_ou(egCore.org.get(user.home_ou()));
365 user.standing_penalties(),
367 if (!angular.isObject(penalty.org_unit()))
368 penalty.org_unit(egCore.org.get(penalty.org_unit()));
372 // stat_cat_entries == stat_cat_entry_user_map
373 angular.forEach(user.stat_cat_entries(), function(map) {
374 if (angular.isObject(map.stat_cat())) return;
375 // At page load, we only retrieve org-visible stat cats.
376 // For the common case, ignore entries for remote stat cats.
377 var cat = egCore.env.actsc.map[map.stat_cat()];
380 cat.owner(egCore.org.get(cat.owner()));
385 // resolves to true if the patron account has expired or will
386 // expire soon, based on YAOUS circ.patron_expires_soon_warning
387 // note: returning a promise is no longer strictly necessary
388 // (no more async activity) if the calling function is changed too.
389 service.testExpire = function() {
391 var expire = Date.parse(service.current.expire_date());
392 if (expire < new Date()) {
393 return $q.when(service.patronExpired = true);
396 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
398 var preExpire = new Date();
399 preExpire.setDate(preExpire.getDate() + Number(soon));
400 if (expire < preExpire)
401 return $q.when(service.patronExpiresSoon = true);
404 return $q.when(false);
407 // resolves to true if the patron account has any invalid addresses.
408 service.testInvalidAddrs = function() {
410 if (service.invalidAddresses)
411 return $q.when(true);
416 service.current.addresses(),
417 function(addr) { if (addr.valid() == 'f') fail = true }
420 return $q.when(fail);
422 //resolves to true if the patron was fetched with an inactive card
423 service.fetchedWithInactiveCard = function() {
424 var bc = service.search_barcode
425 var cards = service.current.cards();
426 var card = cards.filter(function(c) { return c.barcode() == bc })[0];
427 return (card && card.active() == 'f');
429 // resolves to true if there is any aspect of the patron account
430 // which should produce a message in the alerts panel
431 service.checkAlerts = function() {
433 if (service.hasAlerts) // already checked
434 return $q.when(true);
436 var deferred = $q.defer();
437 var p = service.current;
439 if (service.alert_penalties.length ||
443 service.patron_stats.holds.ready) {
445 service.hasAlerts = true;
448 // see if the user was retrieved with an inactive card
449 if(service.fetchedWithInactiveCard()){
450 service.hasAlerts = true;
453 // regardless of whether we know of alerts, we still need
454 // to test/fetch the expire data for display
455 service.testExpire().then(function(bool) {
456 if (bool) service.hasAlerts = true;
457 deferred.resolve(service.hasAlerts);
460 service.testInvalidAddrs().then(function(bool) {
461 if (bool) service.invalidAddresses = true;
462 deferred.resolve(service.invalidAddresses);
465 return deferred.promise;
468 service.fetchGroupFines = function() {
469 return egCore.net.request(
471 'open-ils.actor.usergroup.members.balance_owed',
472 egCore.auth.token(), service.current.usrgroup()
473 ).then(function(list) {
475 angular.forEach(list, function(u) {
476 total += 100 * Number(u.balance_owed)
478 service.patron_stats.fines.group_balance_owed = total / 100;
482 service.getUserStats = function(id) {
483 return egCore.net.request(
485 'open-ils.actor.user.opac.vital_stats.authoritative',
486 egCore.auth.token(), id
489 // force numeric to ensure correct boolean handling in templates
490 stats.fines.balance_owed = Number(stats.fines.balance_owed);
491 stats.checkouts.overdue = Number(stats.checkouts.overdue);
492 stats.checkouts.claims_returned =
493 Number(stats.checkouts.claims_returned);
494 stats.checkouts.lost = Number(stats.checkouts.lost);
495 stats.checkouts.out = Number(stats.checkouts.out);
496 stats.checkouts.total_out =
497 stats.checkouts.out + stats.checkouts.overdue;
499 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
500 stats.checkouts.total_out += stats.checkouts.claims_returned;
502 if (egCore.env.aous['circ.tally_lost'])
503 stats.checkouts.total_out += stats.checkouts.lost
510 // Fetches the IDs of any active non-cat checkouts for the current
511 // user. Also sets the patron_stats non_cat count value to match.
512 service.getUserNonCats = function(id) {
513 return egCore.net.request(
515 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
516 egCore.auth.token(), id
517 ).then(function(noncat_ids) {
518 service.noncat_ids = noncat_ids;
519 service.patron_stats.checkouts.noncat = noncat_ids.length;
523 // grab additional circ info
524 service.fetchUserStats = function() {
525 return service.getUserStats(service.current.id())
526 .then(function(stats) {
527 service.patron_stats = stats
528 service.alert_penalties = service.current.standing_penalties()
529 .filter(function(pen) {
530 return pen.standing_penalty().staff_alert() == 't'
533 service.summary_stat_cats = [];
534 angular.forEach(service.current.stat_cat_entries(),
536 if (angular.isObject(map.stat_cat()) &&
537 map.stat_cat().usr_summary() == 't') {
538 service.summary_stat_cats.push(map);
543 // run these two in parallel
544 var p1 = service.getUserNonCats(service.current.id());
545 var p2 = service.fetchGroupFines();
546 return $q.all([p1, p2]);
550 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
551 // which is the Angular default.
552 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
553 // FIXME: This change needs to be moved into a project-wide collection
554 // of locale overrides.
555 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
556 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
562 * Manages tabbed patron view.
563 * This is the parent scope of all patron tab scopes.
566 .controller('PatronCtrl',
567 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
568 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
570 $scope.is_patron_edit = function() {
571 return Boolean($location.path().match(/patron\/\d+\/edit$/));
574 // To support the fixed position patron edit actions bar,
575 // its markup has to live outside the scope of the patron
576 // edit controller. Insert a scope blob here that can be
577 // modifed from within the patron edit controller.
578 $scope.edit_passthru = {};
580 // returns true if a redirect occurs
581 function redirectToAlertPanel() {
583 $scope.alert_penalties =
584 function() {return patronSvc.alert_penalties}
586 if (patronSvc.alertsShown) return false;
587 patronSvc.alertsShown = true;
589 // if the patron has any unshown alerts, show them now
590 if (patronSvc.hasAlerts &&
591 !$location.path().match(/alerts$/)) {
594 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
595 .search('card', null);
599 // no alert required. If the patron has fines and the show-bills
600 // OUS is applied, direct to the bills page.
601 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
602 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
603 && !$location.path().match(/bills$/)) {
605 $scope.tab = 'bills';
607 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
608 .search('card', null);
616 // called after each route-specified controller is instantiated.
617 // this doubles as a way to inform the top-level controller that
618 // egStartup.go() has completed, which means we are clear to
619 // fetch the patron, etc.
620 $scope.initTab = function(tab, patron_id) {
621 console.log('init tab ' + tab);
623 $scope.aous = egCore.env.aous;
626 $scope.patron_id = patron_id;
627 return patronSvc.setPrimary($scope.patron_id)
628 .then(function() {return patronSvc.checkAlerts()})
629 .then(redirectToAlertPanel);
634 $scope._show_dob = {};
635 $scope.show_dob = function (val) {
636 if ($scope.patron()) {
637 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
638 return $scope._show_dob[$scope.patron().id()];
640 return !egCore.env.aous['circ.obscure_dob'];
643 $scope.obscure_dob = function() {
644 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
646 $scope.now_show_dob = function() {
647 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
648 $scope.show_dob() : true;
651 $scope.patron = function() { return patronSvc.current }
652 $scope.patron_stats = function() { return patronSvc.patron_stats }
653 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
655 $scope.print_address = function(addr) {
658 template : 'patron_address',
660 patron : egCore.idl.toHash(patronSvc.current),
661 address : egCore.idl.toHash(addr)
666 $scope.toggle_expand_summary = function() {
667 if ($scope.collapsePatronSummary) {
668 $scope.collapsePatronSummary = false;
669 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
671 $scope.collapsePatronSummary = true;
672 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
676 // always expand the patron summary in the search UI, regardless
677 // of stored preference.
678 $scope.collapse_summary = function() {
679 return $scope.tab != 'search' && $scope.collapsePatronSummary;
682 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
683 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
686 .controller('PatronBarcodeSearchCtrl',
687 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
688 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
689 $scope.selectMe = true; // focus text input
690 patronSvc.clearPrimary(); // clear the default user
692 // jump to the patron checkout UI
693 function loadPatron(user_id) {
695 .path('/circ/patron/' + user_id + '/checkout')
696 .search('card', $scope.args.barcode);
697 patronSvc.search_barcode = $scope.args.barcode;
700 // create an opt-in=yes response for the loaded user
701 function createOptIn(user_id) {
704 'open-ils.actor.user.org_unit_opt_in.create',
705 egCore.auth.token(), user_id).then(function(resp) {
706 if (evt = egCore.evt.parse(resp)) return alert(evt);
712 $scope.submitBarcode = function(args) {
713 $scope.bcNotFound = null;
714 $scope.optInRestricted = false;
715 if (!args.barcode) return;
717 // blur so next time it's set to true it will re-apply select()
718 $scope.selectMe = false;
725 'open-ils.actor.get_barcodes',
726 egCore.auth.token(), egCore.auth.user().ws_ou(),
727 'actor', args.barcode)
729 .then(function(resp) { // get_barcodes
731 if (evt = egCore.evt.parse(resp)) {
736 if (!resp || !resp[0]) {
737 $scope.bcNotFound = args.barcode;
738 $scope.selectMe = true;
742 // see if an opt-in request is needed
743 user_id = resp[0].id;
744 return egCore.net.request(
746 'open-ils.actor.user.org_unit_opt_in.check',
747 egCore.auth.token(), user_id);
749 }).then(function(optInResp) { // opt_in_check
751 if (evt = egCore.evt.parse(optInResp)) {
756 if (optInResp == 2) {
757 // opt-in disallowed at this location by patron's home library
758 $scope.optInRestricted = true;
759 $scope.selectMe = true;
763 if (optInResp == 1) {
764 // opt-in handled or not needed
765 return loadPatron(user_id);
768 // opt-in needed, show the opt-in dialog
769 egUser.get(user_id, {useFields : []})
771 .then(function(user) { // retrieve user
772 egConfirmDialog.open(
773 egCore.strings.OPT_IN_DIALOG, '',
774 { org : egCore.org.get(user.home_ou()),
776 ok : function() { createOptIn(user.id()) },
777 cancel : function() {}
787 * Manages patron search
789 .controller('PatronSearchCtrl',
790 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
791 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
792 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
793 $filter, egUser, patronSvc , egGridDataProvider , $document) {
795 $scope.initTab('search');
796 $scope.focusMe = true;
797 $scope.searchArgs = {
798 // default to searching globally
799 home_ou : egCore.org.tree()
802 // last used patron search form element
805 $scope.gridControls = {
806 activateItem : function(item) {
807 $location.path('/circ/patron/' + item.id() + '/checkout');
809 selectedItems : function() {return []}
812 // Handle URL-encoded searches
813 if ($location.search().search) {
814 console.log('URL search = ' + $location.search().search);
815 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
817 // why the double-JSON encoded sort?
818 if (patronSvc.urlSearch.search.search_sort) {
819 patronSvc.urlSearch.sort =
820 JSON2js(patronSvc.urlSearch.search.search_sort);
822 patronSvc.urlSearch.sort = [];
824 delete patronSvc.urlSearch.search.search_sort;
828 if (patronSvc.lastSearch) {
829 propagate = patronSvc.lastSearch.search;
830 // home_ou needs to be treated specially
831 propagate.home_ou = {
832 value : patronSvc.lastSearch.home_ou,
835 } else if (patronSvc.urlSearch) {
836 propagate = patronSvc.urlSearch.search;
839 if (egCore.env.pgt) {
840 $scope.profiles = egCore.env.pgt.list;
842 egCore.pcrud.search('pgt', {parent : null},
843 {flesh : -1, flesh_fields : {pgt : ['children']}}
846 egCore.env.absorbTree(tree, 'pgt')
847 $scope.profiles = egCore.env.pgt.list;
853 // populate the search form with our cached / preexisting search info
854 angular.forEach(propagate, function(val, key) {
855 if (key == 'profile')
856 val.value = $scope.profiles.filter(function(p) { return p.id() == val.value })[0];
857 if (key == 'home_ou')
858 val.value = egCore.org.get(val.value);
859 $scope.searchArgs[key] = val.value;
863 var provider = egGridDataProvider.instance({});
866 function() {return $scope.gridControls.selectedItems()},
869 patronSvc.setPrimary(null, list[0]);
874 provider.get = function(offset, count) {
875 var deferred = $q.defer();
878 if (patronSvc.urlSearch) {
879 fullSearch = patronSvc.urlSearch;
880 // enusre the urlSearch only runs once.
881 delete patronSvc.urlSearch;
884 patronSvc.search_barcode = $scope.searchArgs.card;
886 var search = compileSearch($scope.searchArgs);
887 if (Object.keys(search) == 0) return $q.when();
889 var home_ou = search.home_ou;
890 delete search.home_ou;
891 var inactive = search.inactive;
892 delete search.inactive;
896 sort : compileSort(),
902 fullSearch.count = count;
903 fullSearch.offset = offset;
905 if (patronSvc.lastSearch) {
906 // search repeated, return the cached results
907 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
908 console.log('patron search returning ' +
909 patronSvc.patrons.length + ' cached results');
911 // notify has to happen after returning the promise
914 angular.forEach(patronSvc.patrons, function(user) {
915 deferred.notify(user);
920 return deferred.promise;
924 patronSvc.lastSearch = fullSearch;
926 if (fullSearch.search.id) {
927 // search by user id performs a direct ID lookup
928 var userId = fullSearch.search.id.value;
931 egUser.get(userId).then(function(user) {
932 patronSvc.localFlesh(user);
933 patronSvc.patrons = [user];
934 deferred.notify(user);
939 return deferred.promise;
942 // Dispay the search progress bar to indicate a search is in progress
943 $scope.show_search_progress = true;
945 patronSvc.patrons = [];
948 'open-ils.actor.patron.search.advanced.fleshed',
955 egUser.defaultFleshFields,
960 // hide progress bar on 0-hits searches
961 $scope.show_search_progress = false;
966 // hide progress bar as soon as the first result appears.
967 $scope.show_search_progress = false;
968 patronSvc.localFlesh(user); // inline
969 patronSvc.patrons.push(user);
970 deferred.notify(user);
974 return deferred.promise;
977 $scope.patronSearchGridProvider = provider;
979 // determine the tree depth of the profile group
980 $scope.pgt_depth = function(grp) {
982 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
986 $scope.clearForm = function () {
987 $scope.searchArgs={};
988 if (lastFormElement) lastFormElement.focus();
991 $scope.applyShowExtras = function($event, bool) {
993 $scope.showExtras = true;
994 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
996 $scope.showExtras = false;
997 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
999 if (lastFormElement) lastFormElement.focus();
1000 $event.preventDefault();
1003 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
1004 .then(function(val) {$scope.showExtras = val});
1006 // map form arguments into search params
1007 function compileSearch(args) {
1009 angular.forEach(args, function(val, key) {
1011 if (key == 'profile' && args.profile) {
1012 search.profile = {value : args.profile.id(), group : 0};
1013 } else if (key == 'home_ou' && args.home_ou) {
1014 search.home_ou = args.home_ou.id(); // passed separately
1015 } else if (key == 'inactive') {
1016 search.inactive = val;
1018 search[key] = {value : val, group : 0};
1020 if (key.match(/phone|ident/)) {
1021 search[key].group = 2;
1023 if (key.match(/street|city|state|post_code/)) {
1024 search[key].group = 1;
1025 } else if (key == 'card') {
1026 search[key].group = 3
1034 function compileSort() {
1036 if (!provider.sort.length) {
1039 "first_given_name ASC",
1040 "second_given_name ASC",
1049 if (angular.isObject(sortdef)) {
1050 var name = Object.keys(sortdef)[0];
1051 var dir = sortdef[name];
1052 sort.push(name + ' ' + dir);
1062 $scope.setLastFormElement = function() {
1063 lastFormElement = $document[0].activeElement;
1066 // search form submit action; tells the results grid to
1068 $scope.search = function(args) { // args === $scope.searchArgs
1069 if (args && Object.keys(args).length)
1070 $scope.gridControls.refresh();
1071 if (lastFormElement) lastFormElement.focus();
1074 // TODO: move this into the (forthcoming) grid row activate action
1075 $scope.onPatronDblClick = function($event, user) {
1076 $location.path('/circ/patron/' + user.id() + '/checkout');
1079 if (patronSvc.urlSearch) {
1080 // force the grid to load the url-based search on page load
1089 .controller('PatronMessagesCtrl',
1090 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
1091 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
1092 $scope.initTab('messages', $routeParams.id);
1093 var usr_id = $routeParams.id;
1095 // setup date filters
1096 var start = new Date(); // now - 1 year
1097 start.setFullYear(start.getFullYear() - 1),
1100 end_date : new Date()
1103 function date_range() {
1104 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1105 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1106 var today = new Date().toISOString().replace(/T.*/,'');
1107 if (end == today) end = 'now';
1108 return [start, end];
1113 var activeGrid = $scope.activeGridControls = {
1114 setSort : function() {
1115 return ['set_date'];
1117 setQuery : function() {
1122 {stop_date : {'>' : 'now'}}
1128 var archiveGrid = $scope.archiveGridControls = {
1129 setSort : function() {
1130 return ['set_date'];
1132 setQuery : function() {
1135 stop_date : {'<=' : 'now'},
1136 set_date : {between : date_range()}
1141 $scope.removePenalty = function(selected) {
1142 // the grid stores flattened penalties. Fetch penalty objects first
1144 var ids = selected.map(function(s){ return s.id });
1145 egCore.pcrud.search('ausp',
1147 {atomic : true, authoritative : true}
1150 ).then(function(penalties) {
1151 return egCore.pcrud.remove(penalties);
1153 // then refresh the grid
1154 }).then(function() {
1155 activeGrid.refresh();
1159 $scope.archivePenalty = function(selected) {
1160 // the grid stores flattened penalties. Fetch penalty objects first
1162 var ids = selected.map(function(s){ return s.id });
1163 egCore.pcrud.search('ausp',
1165 {atomic : true, authoritative : true}
1168 ).then(function(penalties) {
1169 angular.forEach(penalties, function(p){ p.stop_date('now') });
1170 return egCore.pcrud.update(penalties);
1172 // then refresh the grid
1173 }).then(function() {
1174 activeGrid.refresh();
1175 archiveGrid.refresh();
1179 // leverage egEnv for caching
1180 function fetchPenaltyTypes() {
1182 return $q.when(egCore.env.csp.list);
1183 return egCore.pcrud.search(
1184 // id <= 100 are reserved for system use
1185 'csp', {id : {'>': 100}}, {}, {atomic : true})
1186 .then(function(penalties) {
1187 egCore.env.absorbList(penalties, 'csp');
1192 $scope.createPenalty = function() {
1193 egCirc.create_penalty(usr_id).then(function() {
1194 activeGrid.refresh();
1195 // force a refresh of the user, since they may now
1196 // have blocking penalties, etc.
1197 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1201 $scope.editPenalty = function(selected) {
1202 if (selected.length == 0) return;
1204 // grab the penalty from the user object
1205 var penalty = patronSvc.current.standing_penalties().filter(
1206 function(p) {return p.id() == selected[0].id})[0];
1208 egCirc.edit_penalty(penalty).then(function() {
1209 activeGrid.refresh();
1210 // force a refresh of the user, since they may now
1211 // have blocking penalties, etc.
1212 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1219 * Credentials tester
1221 .controller('PatronVerifyCredentialsCtrl',
1222 ['$scope','$routeParams','$location','egCore',
1223 function($scope, $routeParams , $location , egCore) {
1224 $scope.verified = null;
1225 $scope.focusMe = true;
1227 // called with a patron, pre-populate the form args
1228 $scope.initTab('other', $routeParams.id).then(
1230 if ($routeParams.id && $scope.patron()) {
1231 $scope.prepop = true;
1232 $scope.username = $scope.patron().usrname();
1233 $scope.barcode = $scope.patron().card().barcode();
1235 $scope.username = '';
1236 $scope.barcode = '';
1237 $scope.password = '';
1242 // verify login credentials
1243 $scope.verify = function() {
1244 $scope.verified = null;
1245 $scope.notFound = false;
1249 'open-ils.actor.verify_user_password',
1250 egCore.auth.token(), $scope.barcode,
1251 $scope.username, hex_md5($scope.password || '')
1253 ).then(function(resp) {
1254 $scope.focusMe = true;
1255 if (evt = egCore.evt.parse(resp)) {
1257 } else if (resp == 1) {
1258 $scope.verified = true;
1260 $scope.verified = false;
1265 // load the main patron UI for the provided username or barcode
1266 $scope.load = function($event) {
1267 $scope.notFound = false;
1268 $scope.verified = null;
1272 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1273 egCore.auth.token(), $scope.barcode, $scope.username
1275 ).then(function(resp) {
1278 $location.path('/circ/patron/' + resp + '/checkout');
1282 // something went wrong...
1283 $scope.focusMe = true;
1284 if (evt = egCore.evt.parse(resp)) {
1285 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1286 $scope.notFound = true;
1295 // load() button sits within the verify form.
1296 // avoid submitting the verify() form action on load()
1297 $event.preventDefault();
1301 .controller('PatronAlertsCtrl',
1302 ['$scope','$routeParams','$location','egCore','patronSvc',
1303 function($scope, $routeParams , $location , egCore , patronSvc) {
1305 $scope.initTab('other', $routeParams.id)
1307 $scope.patronExpired = patronSvc.patronExpired;
1308 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1309 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1310 $scope.invalidAddresses = patronSvc.invalidAddresses;
1315 .controller('PatronNotesCtrl',
1316 ['$scope', '$filter', '$routeParams','$location','egCore','patronSvc','$uibModal',
1317 function($scope, $filter, $routeParams , $location , egCore , patronSvc , $uibModal) {
1318 $scope.initTab('other', $routeParams.id);
1319 var usr_id = $routeParams.id;
1322 function refreshPage() {
1324 egCore.pcrud.search('aun',
1326 {flesh : 1, flesh_fields : {aun : ['creator']}},
1327 {authoritative : true})
1328 .then(null, null, function(note) {
1329 $scope.notes.push(note);
1333 // open the new-note dialog and create the note
1334 $scope.newNote = function() {
1336 templateUrl: './circ/patron/t_new_note_dialog',
1338 ['$scope', '$uibModalInstance',
1339 function($scope, $uibModalInstance) {
1340 $scope.focusNote = true;
1342 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1343 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1344 $scope.cancel = function () { $uibModalInstance.dismiss() }
1348 if (!args.value) return;
1349 var note = new egCore.idl.aun();
1351 note.title(args.title);
1352 note.value(args.value);
1353 note.pub(args.pub ? 't' : 'f');
1354 note.creator(egCore.auth.user().id());
1356 note.value(note.value() + ' [' + args.initials + ']');
1357 egCore.pcrud.create(note).then(function() {refreshPage()});
1362 // delete the selected note
1363 $scope.deleteNote = function(note) {
1364 egCore.pcrud.remove(note).then(function() {refreshPage()});
1367 // print the selected note
1368 $scope.printNote = function(note) {
1369 var hash = egCore.idl.toHash(note);
1370 hash.usr = egCore.idl.toHash($scope.patron());
1371 egCore.print.print({
1372 context : 'default',
1373 template : 'patron_note',
1374 scope : {note : hash}
1378 // perform the initial note fetch
1382 .controller('PatronGroupCtrl',
1383 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1384 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1385 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1386 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1388 var usr_id = $routeParams.id;
1390 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1392 var grid = $scope.gridControls = {
1393 activateItem : function(item) {
1394 $location.path('/circ/patron/' + item.id + '/checkout');
1396 itemRetrieved : function(item) {
1398 if (item.id == patronSvc.current.id()) {
1399 item.stats = patronSvc.patron_stats;
1402 // flesh stats for other group members
1403 patronSvc.getUserStats(item.id).then(function(stats) {
1405 $scope.totals.total_out += stats.checkouts.total_out;
1406 $scope.totals.overdue += stats.checkouts.overdue;
1410 setSort : function() {
1411 return ['create_date'];
1415 $scope.initTab('other', $routeParams.id)
1416 .then(function(redirect) {
1417 // if we are redirecting to the alerts page, avoid updating the
1419 if (redirect) return;
1420 // let initTab() fetch the user first so we can know the usrgroup
1423 usrgroup : patronSvc.current.usrgroup(),
1426 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1429 $scope.removeFromGroup = function(selected) {
1431 angular.forEach(selected, function(user) {
1432 console.debug('removing user ' + user.id + ' from group');
1437 'open-ils.actor.usergroup.new',
1438 egCore.auth.token(), user.id, true
1443 $q.all(promises).then(function() {grid.refresh()});
1446 function addUserToGroup(user) {
1447 user.usrgroup(patronSvc.current.usrgroup());
1448 user.ischanged(true);
1451 'open-ils.actor.patron.update',
1452 egCore.auth.token(), user
1454 ).then(function() {grid.refresh()});
1457 // fetch each user ("selected" has flattened users)
1458 // update the usrgroup, then update the user object
1459 // After all updates are complete, refresh the grid.
1460 function moveUsersToGroup(target_user, selected) {
1463 angular.forEach(selected, function(user) {
1465 egCore.pcrud.retrieve('au', user.id)
1467 u.usrgroup(target_user.usrgroup());
1469 return egCore.net.request(
1471 'open-ils.actor.patron.update',
1472 egCore.auth.token(), u
1478 $q.all(promises).then(function() {grid.refresh()});
1481 function showMoveToGroupConfirm(barcode, selected, outbound) {
1484 egCore.pcrud.search('ac', {barcode : barcode})
1486 // fetch the fleshed user
1487 .then(function(card) {
1489 if (!card) return; // TODO: warn user
1491 egCore.pcrud.retrieve('au', card.usr())
1492 .then(function(user) {
1495 templateUrl: './circ/patron/t_move_to_group_dialog',
1497 '$scope','$uibModalInstance',
1498 function($scope , $uibModalInstance) {
1500 $scope.selected = selected;
1501 $scope.outbound = outbound;
1503 function(count) { $uibModalInstance.close() }
1505 function () { $uibModalInstance.dismiss() }
1508 }).result.then(function() {
1510 moveUsersToGroup(user, selected);
1512 addUserToGroup(user);
1519 // selected == move selected patrons to another patron's group
1520 // !selected == patron from a different group moves into our group
1521 function moveToGroup(selected, outbound) {
1522 egPromptDialog.open(
1523 egCore.strings.GROUP_ADD_USER, '',
1524 {ok : function(value) {
1526 showMoveToGroupConfirm(value, selected, outbound);
1531 $scope.moveToGroup = function() { moveToGroup([], false) };
1532 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1534 $scope.cloneUser = function(selected) {
1535 if (!selected.length) return;
1536 var url = $location.absUrl().replace(
1538 '/patron/register/clone/' + selected[0].id);
1539 $window.open(url, '_blank').focus();
1542 $scope.retrieveSelected = function(selected) {
1543 if (!selected.length) return;
1544 angular.forEach(selected, function(usr) {
1545 $timeout(function() {
1546 var url = $location.absUrl().replace(
1548 '/patron/' + usr.id + '/checkout');
1549 $window.open(url, '_blank')
1556 .controller('PatronStatCatsCtrl',
1557 ['$scope','$routeParams','$q','egCore','patronSvc',
1558 function($scope, $routeParams , $q , egCore , patronSvc) {
1559 $scope.initTab('other', $routeParams.id)
1560 .then(function(redirect) {
1561 // Entries for org-visible stat cats are fleshed. Any others
1562 // have to be fleshed within.
1565 angular.forEach(patronSvc.current.stat_cat_entries(),
1567 if (!angular.isObject(entry.stat_cat())) {
1568 to_flesh[entry.stat_cat()] = entry;
1573 if (!Object.keys(to_flesh).length) return;
1575 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1576 .then(null, null, function(cat) { // stream
1577 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1578 to_flesh[cat.id()].stat_cat(cat);
1583 .controller('PatronFetchLastCtrl',
1584 ['$scope','$location','egCore',
1585 function($scope , $location , egCore) {
1587 var id = egCore.hatch.getLoginSessionItem('eg.circ.last_patron');
1588 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1590 $scope.no_last = true;
1593 .controller('PatronTriggeredEventsCtrl',
1594 ['$scope','$routeParams','$location','egCore','patronSvc',
1595 function($scope, $routeParams, $location , egCore , patronSvc) {
1596 $scope.initTab('other', $routeParams.id);
1598 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1599 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1601 $scope.triggered_events_url = url;
1605 .controller('PatronPermsCtrl',
1606 ['$scope','$routeParams','$window','$location','egCore',
1607 function($scope , $routeParams , $window , $location , egCore) {
1608 $scope.initTab('other', $routeParams.id);
1610 var url = $location.absUrl().replace(
1611 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1613 url += '?usr=' + encodeURIComponent($routeParams.id);
1615 // user_edit does not load the session via cookie. It uses URL
1616 // params or xulG instead. Pass via xulG.
1618 ses : egCore.auth.token(),
1619 on_patron_save : function() {
1620 $scope.funcs.reload();
1624 $scope.user_perms_url = url;