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',
793 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
794 $filter, egUser, patronSvc , egGridDataProvider , $document,
797 $scope.initTab('search');
798 $scope.focusMe = true;
799 $scope.searchArgs = {
800 // default to searching globally
801 home_ou : egCore.org.tree()
804 // last used patron search form element
807 $scope.gridControls = {
808 activateItem : function(item) {
809 $location.path('/circ/patron/' + item.id() + '/checkout');
811 selectedItems : function() {return []}
814 // Handle URL-encoded searches
815 if ($location.search().search) {
816 console.log('URL search = ' + $location.search().search);
817 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
819 // why the double-JSON encoded sort?
820 if (patronSvc.urlSearch.search.search_sort) {
821 patronSvc.urlSearch.sort =
822 JSON2js(patronSvc.urlSearch.search.search_sort);
824 patronSvc.urlSearch.sort = [];
826 delete patronSvc.urlSearch.search.search_sort;
830 if (patronSvc.lastSearch) {
831 propagate = patronSvc.lastSearch.search;
832 // home_ou needs to be treated specially
833 propagate.home_ou = {
834 value : patronSvc.lastSearch.home_ou,
837 } else if (patronSvc.urlSearch) {
838 propagate = patronSvc.urlSearch.search;
841 if (egCore.env.pgt) {
842 $scope.profiles = egCore.env.pgt.list;
844 egCore.pcrud.search('pgt', {parent : null},
845 {flesh : -1, flesh_fields : {pgt : ['children']}}
848 egCore.env.absorbTree(tree, 'pgt')
849 $scope.profiles = egCore.env.pgt.list;
855 // populate the search form with our cached / preexisting search info
856 angular.forEach(propagate, function(val, key) {
857 if (key == 'profile')
858 val.value = $scope.profiles.filter(function(p) { return p.id() == val.value })[0];
859 if (key == 'home_ou')
860 val.value = egCore.org.get(val.value);
861 $scope.searchArgs[key] = val.value;
865 var provider = egGridDataProvider.instance({});
868 function() {return $scope.gridControls.selectedItems()},
871 patronSvc.setPrimary(null, list[0]);
876 provider.get = function(offset, count) {
877 var deferred = $q.defer();
880 if (patronSvc.urlSearch) {
881 fullSearch = patronSvc.urlSearch;
882 // enusre the urlSearch only runs once.
883 delete patronSvc.urlSearch;
886 patronSvc.search_barcode = $scope.searchArgs.card;
888 var search = compileSearch($scope.searchArgs);
889 if (Object.keys(search) == 0) return $q.when();
891 var home_ou = search.home_ou;
892 delete search.home_ou;
893 var inactive = search.inactive;
894 delete search.inactive;
898 sort : compileSort(),
904 fullSearch.count = count;
905 fullSearch.offset = offset;
907 if (patronSvc.lastSearch) {
908 // search repeated, return the cached results
909 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
910 console.log('patron search returning ' +
911 patronSvc.patrons.length + ' cached results');
913 // notify has to happen after returning the promise
916 angular.forEach(patronSvc.patrons, function(user) {
917 deferred.notify(user);
922 return deferred.promise;
926 patronSvc.lastSearch = fullSearch;
928 if (fullSearch.search.id) {
929 // search by user id performs a direct ID lookup
930 var userId = fullSearch.search.id.value;
933 egUser.get(userId).then(function(user) {
934 patronSvc.localFlesh(user);
935 patronSvc.patrons = [user];
936 deferred.notify(user);
941 return deferred.promise;
944 // Dispay the search progress bar to indicate a search is in progress
945 $scope.show_search_progress = true;
947 patronSvc.patrons = [];
950 'open-ils.actor.patron.search.advanced.fleshed',
957 egUser.defaultFleshFields,
962 // hide progress bar on 0-hits searches
963 $scope.show_search_progress = false;
968 // hide progress bar as soon as the first result appears.
969 $scope.show_search_progress = false;
970 patronSvc.localFlesh(user); // inline
971 patronSvc.patrons.push(user);
972 deferred.notify(user);
976 return deferred.promise;
979 $scope.patronSearchGridProvider = provider;
981 // determine the tree depth of the profile group
982 $scope.pgt_depth = function(grp) {
984 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
988 $scope.clearForm = function () {
989 $scope.searchArgs={};
990 if (lastFormElement) lastFormElement.focus();
993 $scope.applyShowExtras = function($event, bool) {
995 $scope.showExtras = true;
996 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
998 $scope.showExtras = false;
999 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
1001 if (lastFormElement) lastFormElement.focus();
1002 $event.preventDefault();
1005 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
1006 .then(function(val) {$scope.showExtras = val});
1008 // map form arguments into search params
1009 function compileSearch(args) {
1011 angular.forEach(args, function(val, key) {
1013 if (key == 'profile' && args.profile) {
1014 search.profile = {value : args.profile.id(), group : 0};
1015 } else if (key == 'home_ou' && args.home_ou) {
1016 search.home_ou = args.home_ou.id(); // passed separately
1017 } else if (key == 'inactive') {
1018 search.inactive = val;
1020 search[key] = {value : val, group : 0};
1022 if (key.match(/phone|ident/)) {
1023 search[key].group = 2;
1025 if (key.match(/street|city|state|post_code/)) {
1026 search[key].group = 1;
1027 } else if (key == 'card') {
1028 search[key].group = 3
1036 function compileSort() {
1038 if (!provider.sort.length) {
1041 "first_given_name ASC",
1042 "second_given_name ASC",
1051 if (angular.isObject(sortdef)) {
1052 var name = Object.keys(sortdef)[0];
1053 var dir = sortdef[name];
1054 sort.push(name + ' ' + dir);
1064 $scope.setLastFormElement = function() {
1065 lastFormElement = $document[0].activeElement;
1068 // search form submit action; tells the results grid to
1070 $scope.search = function(args) { // args === $scope.searchArgs
1071 if (args && Object.keys(args).length)
1072 $scope.gridControls.refresh();
1073 if (lastFormElement) lastFormElement.focus();
1076 // TODO: move this into the (forthcoming) grid row activate action
1077 $scope.onPatronDblClick = function($event, user) {
1078 $location.path('/circ/patron/' + user.id() + '/checkout');
1081 if (patronSvc.urlSearch) {
1082 // force the grid to load the url-based search on page load
1086 $scope.need_two_selected = function() {
1087 var items = $scope.gridControls.selectedItems();
1088 return (items.length == 2) ? false : true;
1090 $scope.merge_patrons = function() {
1091 var items = $scope.gridControls.selectedItems();
1092 if (items.length != 2) return false;
1094 var patron_ids = [];
1095 angular.forEach(items, function(i) {
1096 patron_ids.push(i.id());
1098 egPatronMerge.do_merge(patron_ids).then(function() {
1099 // ensure that we're not drawing from cached
1100 // resuts, as a successful merge just deleted a
1102 delete patronSvc.lastSearch;
1103 $scope.gridControls.refresh();
1112 .controller('PatronMessagesCtrl',
1113 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
1114 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
1115 $scope.initTab('messages', $routeParams.id);
1116 var usr_id = $routeParams.id;
1118 // setup date filters
1119 var start = new Date(); // now - 1 year
1120 start.setFullYear(start.getFullYear() - 1),
1123 end_date : new Date()
1126 function date_range() {
1127 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1128 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1129 var today = new Date().toISOString().replace(/T.*/,'');
1130 if (end == today) end = 'now';
1131 return [start, end];
1136 var activeGrid = $scope.activeGridControls = {
1137 setSort : function() {
1138 return ['set_date'];
1140 setQuery : function() {
1145 {stop_date : {'>' : 'now'}}
1151 var archiveGrid = $scope.archiveGridControls = {
1152 setSort : function() {
1153 return ['set_date'];
1155 setQuery : function() {
1158 stop_date : {'<=' : 'now'},
1159 set_date : {between : date_range()}
1164 $scope.removePenalty = function(selected) {
1165 // the grid stores flattened penalties. Fetch penalty objects first
1167 var ids = selected.map(function(s){ return s.id });
1168 egCore.pcrud.search('ausp',
1170 {atomic : true, authoritative : true}
1173 ).then(function(penalties) {
1174 return egCore.pcrud.remove(penalties);
1176 // then refresh the grid
1177 }).then(function() {
1178 activeGrid.refresh();
1182 $scope.archivePenalty = function(selected) {
1183 // the grid stores flattened penalties. Fetch penalty objects first
1185 var ids = selected.map(function(s){ return s.id });
1186 egCore.pcrud.search('ausp',
1188 {atomic : true, authoritative : true}
1191 ).then(function(penalties) {
1192 angular.forEach(penalties, function(p){ p.stop_date('now') });
1193 return egCore.pcrud.update(penalties);
1195 // then refresh the grid
1196 }).then(function() {
1197 activeGrid.refresh();
1198 archiveGrid.refresh();
1202 // leverage egEnv for caching
1203 function fetchPenaltyTypes() {
1205 return $q.when(egCore.env.csp.list);
1206 return egCore.pcrud.search(
1207 // id <= 100 are reserved for system use
1208 'csp', {id : {'>': 100}}, {}, {atomic : true})
1209 .then(function(penalties) {
1210 egCore.env.absorbList(penalties, 'csp');
1215 $scope.createPenalty = function() {
1216 egCirc.create_penalty(usr_id).then(function() {
1217 activeGrid.refresh();
1218 // force a refresh of the user, since they may now
1219 // have blocking penalties, etc.
1220 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1224 $scope.editPenalty = function(selected) {
1225 if (selected.length == 0) return;
1227 // grab the penalty from the user object
1228 var penalty = patronSvc.current.standing_penalties().filter(
1229 function(p) {return p.id() == selected[0].id})[0];
1231 egCirc.edit_penalty(penalty).then(function() {
1232 activeGrid.refresh();
1233 // force a refresh of the user, since they may now
1234 // have blocking penalties, etc.
1235 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1242 * Credentials tester
1244 .controller('PatronVerifyCredentialsCtrl',
1245 ['$scope','$routeParams','$location','egCore',
1246 function($scope, $routeParams , $location , egCore) {
1247 $scope.verified = null;
1248 $scope.focusMe = true;
1250 // called with a patron, pre-populate the form args
1251 $scope.initTab('other', $routeParams.id).then(
1253 if ($routeParams.id && $scope.patron()) {
1254 $scope.prepop = true;
1255 $scope.username = $scope.patron().usrname();
1256 $scope.barcode = $scope.patron().card().barcode();
1258 $scope.username = '';
1259 $scope.barcode = '';
1260 $scope.password = '';
1265 // verify login credentials
1266 $scope.verify = function() {
1267 $scope.verified = null;
1268 $scope.notFound = false;
1272 'open-ils.actor.verify_user_password',
1273 egCore.auth.token(), $scope.barcode,
1274 $scope.username, hex_md5($scope.password || '')
1276 ).then(function(resp) {
1277 $scope.focusMe = true;
1278 if (evt = egCore.evt.parse(resp)) {
1280 } else if (resp == 1) {
1281 $scope.verified = true;
1283 $scope.verified = false;
1288 // load the main patron UI for the provided username or barcode
1289 $scope.load = function($event) {
1290 $scope.notFound = false;
1291 $scope.verified = null;
1295 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1296 egCore.auth.token(), $scope.barcode, $scope.username
1298 ).then(function(resp) {
1301 $location.path('/circ/patron/' + resp + '/checkout');
1305 // something went wrong...
1306 $scope.focusMe = true;
1307 if (evt = egCore.evt.parse(resp)) {
1308 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1309 $scope.notFound = true;
1318 // load() button sits within the verify form.
1319 // avoid submitting the verify() form action on load()
1320 $event.preventDefault();
1324 .controller('PatronAlertsCtrl',
1325 ['$scope','$routeParams','$location','egCore','patronSvc',
1326 function($scope, $routeParams , $location , egCore , patronSvc) {
1328 $scope.initTab('other', $routeParams.id)
1330 $scope.patronExpired = patronSvc.patronExpired;
1331 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1332 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1333 $scope.invalidAddresses = patronSvc.invalidAddresses;
1338 .controller('PatronNotesCtrl',
1339 ['$scope', '$filter', '$routeParams','$location','egCore','patronSvc','$uibModal',
1340 function($scope, $filter, $routeParams , $location , egCore , patronSvc , $uibModal) {
1341 $scope.initTab('other', $routeParams.id);
1342 var usr_id = $routeParams.id;
1345 function refreshPage() {
1347 egCore.pcrud.search('aun',
1349 {flesh : 1, flesh_fields : {aun : ['creator']}},
1350 {authoritative : true})
1351 .then(null, null, function(note) {
1352 $scope.notes.push(note);
1356 // open the new-note dialog and create the note
1357 $scope.newNote = function() {
1359 templateUrl: './circ/patron/t_new_note_dialog',
1361 ['$scope', '$uibModalInstance',
1362 function($scope, $uibModalInstance) {
1363 $scope.focusNote = true;
1365 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1366 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1367 $scope.cancel = function () { $uibModalInstance.dismiss() }
1371 if (!args.value) return;
1372 var note = new egCore.idl.aun();
1374 note.title(args.title);
1375 note.value(args.value);
1376 note.pub(args.pub ? 't' : 'f');
1377 note.creator(egCore.auth.user().id());
1379 note.value(note.value() + ' [' + args.initials + ']');
1380 egCore.pcrud.create(note).then(function() {refreshPage()});
1385 // delete the selected note
1386 $scope.deleteNote = function(note) {
1387 egCore.pcrud.remove(note).then(function() {refreshPage()});
1390 // print the selected note
1391 $scope.printNote = function(note) {
1392 var hash = egCore.idl.toHash(note);
1393 hash.usr = egCore.idl.toHash($scope.patron());
1394 egCore.print.print({
1395 context : 'default',
1396 template : 'patron_note',
1397 scope : {note : hash}
1401 // perform the initial note fetch
1405 .controller('PatronGroupCtrl',
1406 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1407 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1408 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1409 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1411 var usr_id = $routeParams.id;
1413 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1415 var grid = $scope.gridControls = {
1416 activateItem : function(item) {
1417 $location.path('/circ/patron/' + item.id + '/checkout');
1419 itemRetrieved : function(item) {
1421 if (item.id == patronSvc.current.id()) {
1422 item.stats = patronSvc.patron_stats;
1425 // flesh stats for other group members
1426 patronSvc.getUserStats(item.id).then(function(stats) {
1428 $scope.totals.total_out += stats.checkouts.total_out;
1429 $scope.totals.overdue += stats.checkouts.overdue;
1433 setSort : function() {
1434 return ['create_date'];
1438 $scope.initTab('other', $routeParams.id)
1439 .then(function(redirect) {
1440 // if we are redirecting to the alerts page, avoid updating the
1442 if (redirect) return;
1443 // let initTab() fetch the user first so we can know the usrgroup
1446 usrgroup : patronSvc.current.usrgroup(),
1449 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1452 $scope.removeFromGroup = function(selected) {
1454 angular.forEach(selected, function(user) {
1455 console.debug('removing user ' + user.id + ' from group');
1460 'open-ils.actor.usergroup.new',
1461 egCore.auth.token(), user.id, true
1466 $q.all(promises).then(function() {grid.refresh()});
1469 function addUserToGroup(user) {
1470 user.usrgroup(patronSvc.current.usrgroup());
1471 user.ischanged(true);
1474 'open-ils.actor.patron.update',
1475 egCore.auth.token(), user
1477 ).then(function() {grid.refresh()});
1480 // fetch each user ("selected" has flattened users)
1481 // update the usrgroup, then update the user object
1482 // After all updates are complete, refresh the grid.
1483 function moveUsersToGroup(target_user, selected) {
1486 angular.forEach(selected, function(user) {
1488 egCore.pcrud.retrieve('au', user.id)
1490 u.usrgroup(target_user.usrgroup());
1492 return egCore.net.request(
1494 'open-ils.actor.patron.update',
1495 egCore.auth.token(), u
1501 $q.all(promises).then(function() {grid.refresh()});
1504 function showMoveToGroupConfirm(barcode, selected, outbound) {
1507 egCore.pcrud.search('ac', {barcode : barcode})
1509 // fetch the fleshed user
1510 .then(function(card) {
1512 if (!card) return; // TODO: warn user
1514 egCore.pcrud.retrieve('au', card.usr())
1515 .then(function(user) {
1518 templateUrl: './circ/patron/t_move_to_group_dialog',
1520 '$scope','$uibModalInstance',
1521 function($scope , $uibModalInstance) {
1523 $scope.selected = selected;
1524 $scope.outbound = outbound;
1526 function(count) { $uibModalInstance.close() }
1528 function () { $uibModalInstance.dismiss() }
1531 }).result.then(function() {
1533 moveUsersToGroup(user, selected);
1535 addUserToGroup(user);
1542 // selected == move selected patrons to another patron's group
1543 // !selected == patron from a different group moves into our group
1544 function moveToGroup(selected, outbound) {
1545 egPromptDialog.open(
1546 egCore.strings.GROUP_ADD_USER, '',
1547 {ok : function(value) {
1549 showMoveToGroupConfirm(value, selected, outbound);
1554 $scope.moveToGroup = function() { moveToGroup([], false) };
1555 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1557 $scope.cloneUser = function(selected) {
1558 if (!selected.length) return;
1559 var url = $location.absUrl().replace(
1561 '/patron/register/clone/' + selected[0].id);
1562 $window.open(url, '_blank').focus();
1565 $scope.retrieveSelected = function(selected) {
1566 if (!selected.length) return;
1567 angular.forEach(selected, function(usr) {
1568 $timeout(function() {
1569 var url = $location.absUrl().replace(
1571 '/patron/' + usr.id + '/checkout');
1572 $window.open(url, '_blank')
1579 .controller('PatronStatCatsCtrl',
1580 ['$scope','$routeParams','$q','egCore','patronSvc',
1581 function($scope, $routeParams , $q , egCore , patronSvc) {
1582 $scope.initTab('other', $routeParams.id)
1583 .then(function(redirect) {
1584 // Entries for org-visible stat cats are fleshed. Any others
1585 // have to be fleshed within.
1588 angular.forEach(patronSvc.current.stat_cat_entries(),
1590 if (!angular.isObject(entry.stat_cat())) {
1591 to_flesh[entry.stat_cat()] = entry;
1596 if (!Object.keys(to_flesh).length) return;
1598 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1599 .then(null, null, function(cat) { // stream
1600 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1601 to_flesh[cat.id()].stat_cat(cat);
1606 .controller('PatronFetchLastCtrl',
1607 ['$scope','$location','egCore',
1608 function($scope , $location , egCore) {
1610 var id = egCore.hatch.getLoginSessionItem('eg.circ.last_patron');
1611 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1613 $scope.no_last = true;
1616 .controller('PatronTriggeredEventsCtrl',
1617 ['$scope','$routeParams','$location','egCore','patronSvc',
1618 function($scope, $routeParams, $location , egCore , patronSvc) {
1619 $scope.initTab('other', $routeParams.id);
1621 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1622 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1624 $scope.triggered_events_url = url;
1628 .controller('PatronPermsCtrl',
1629 ['$scope','$routeParams','$window','$location','egCore',
1630 function($scope , $routeParams , $window , $location , egCore) {
1631 $scope.initTab('other', $routeParams.id);
1633 var url = $location.absUrl().replace(
1634 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1636 url += '?usr=' + encodeURIComponent($routeParams.id);
1638 // user_edit does not load the session via cookie. It uses URL
1639 // params or xulG instead. Pass via xulG.
1641 ses : egCore.auth.token(),
1642 on_patron_save : function() {
1643 $scope.funcs.reload();
1647 $scope.user_perms_url = url;