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 'circ.do_not_tally_claims_returned',
35 'ui.circ.show_billing_tab_on_bills',
36 'circ.patron_expires_soon_warning',
37 'ui.circ.items_out.lost',
38 'ui.circ.items_out.longoverdue',
39 'ui.circ.items_out.claimsreturned'
40 ]).then(function(settings) {
41 // local settings are cached within egOrg. Caching them
42 // again in egEnv just simplifies the syntax for access.
43 egCore.env.aous = settings;
47 egCore.env.loadClasses.push('aous');
49 // app-globally modify the default flesh fields for
50 // fleshed user retrieval.
51 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
52 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
62 return egCore.startup.go().then(function() {
64 // This call requires orgs to be loaded, because it
65 // calls egCore.org.ancestors(), so call it after startup
66 return egCore.pcrud.search('actsc',
67 {owner : egCore.org.ancestors(
68 egCore.auth.user().ws_ou(), true)},
70 ).then(function(cats) {
71 egCore.env.absorbList(cats, 'actsc');
76 $routeProvider.when('/circ/patron/search', {
77 templateUrl: './circ/patron/t_search',
78 controller: 'PatronSearchCtrl',
82 $routeProvider.when('/circ/patron/bcsearch', {
83 templateUrl: './circ/patron/t_bcsearch',
84 controller: 'PatronBarcodeSearchCtrl',
88 $routeProvider.when('/circ/patron/credentials', {
89 templateUrl: './circ/patron/t_credentials',
90 controller: 'PatronVerifyCredentialsCtrl',
94 $routeProvider.when('/circ/patron/last', {
95 templateUrl: './circ/patron/t_last_patron',
96 controller: 'PatronFetchLastCtrl',
100 // the following require a patron ID
102 $routeProvider.when('/circ/patron/:id/alerts', {
103 templateUrl: './circ/patron/t_alerts',
104 controller: 'PatronAlertsCtrl',
108 $routeProvider.when('/circ/patron/:id/checkout', {
109 templateUrl: './circ/patron/t_checkout',
110 controller: 'PatronCheckoutCtrl',
114 $routeProvider.when('/circ/patron/:id/items_out', {
115 templateUrl: './circ/patron/t_items_out',
116 controller: 'PatronItemsOutCtrl',
120 $routeProvider.when('/circ/patron/:id/holds', {
121 templateUrl: './circ/patron/t_holds',
122 controller: 'PatronHoldsCtrl',
126 $routeProvider.when('/circ/patron/:id/holds/create', {
127 templateUrl: './circ/patron/t_holds_create',
128 controller: 'PatronHoldsCreateCtrl',
132 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
133 templateUrl: './circ/patron/t_holds',
134 controller: 'PatronHoldsCtrl',
138 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
139 templateUrl: './circ/patron/t_hold_details',
140 controller: 'PatronHoldDetailsCtrl',
144 $routeProvider.when('/circ/patron/:id/bills', {
145 templateUrl: './circ/patron/t_bills',
146 controller: 'PatronBillsCtrl',
150 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
151 templateUrl: './circ/patron/t_xact_details',
152 controller: 'XactDetailsCtrl',
156 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
157 templateUrl: './circ/patron/t_bill_history',
158 controller: 'BillHistoryCtrl',
162 $routeProvider.when('/circ/patron/:id/messages', {
163 templateUrl: './circ/patron/t_messages',
164 controller: 'PatronMessagesCtrl',
168 $routeProvider.when('/circ/patron/:id/edit', {
169 templateUrl: './circ/patron/t_edit',
170 controller: 'PatronRegCtrl',
174 $routeProvider.when('/circ/patron/:id/credentials', {
175 templateUrl: './circ/patron/t_credentials',
176 controller: 'PatronVerifyCredentialsCtrl',
180 $routeProvider.when('/circ/patron/:id/notes', {
181 templateUrl: './circ/patron/t_notes',
182 controller: 'PatronNotesCtrl',
186 $routeProvider.when('/circ/patron/:id/triggered_events', {
187 templateUrl: './circ/patron/t_triggered_events',
188 controller: 'PatronTriggeredEventsCtrl',
192 $routeProvider.when('/circ/patron/:id/edit_perms', {
193 templateUrl: './circ/patron/t_edit_perms',
194 controller: 'PatronPermsCtrl',
198 $routeProvider.when('/circ/patron/:id/group', {
199 templateUrl: './circ/patron/t_group',
200 controller: 'PatronGroupCtrl',
204 $routeProvider.when('/circ/patron/:id/stat_cats', {
205 templateUrl: './circ/patron/t_stat_cats',
206 controller: 'PatronStatCatsCtrl',
210 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
216 .factory('patronSvc',
217 ['$q','$timeout','$location','egCore','egUser','$locale',
218 function($q , $timeout , $location , egCore, egUser , $locale) {
221 // cached patron search results
224 // currently selected patron object
227 // patron circ stats (overdues, fines, holds)
230 // event types manually overridden, which should always be
231 // overridden for checkouts to this patron for this instance of
233 checkout_overrides : {},
236 // when we change the default patron, we need to clear out any
237 // data collected on that patron
238 service.resetPatronLists = function() {
239 service.checkouts = [];
240 service.items_out = []
241 service.items_out_ids = [];
243 service.hold_ids = [];
244 service.checkout_overrides = {};
245 service.patron_stats = null;
246 service.noncat_ids = [];
247 service.hasAlerts = false;
248 service.alertsShown = false;
249 service.patronExpired = false;
250 service.patronExpiresSoon = false;
251 service.retrievedWithInactive = false;
252 service.invalidAddresses = false;
254 service.resetPatronLists(); // initialize
256 // shortcut to force-reload the current primary
257 service.refreshPrimary = function() {
258 if (!service.current) return $q.when();
259 return service.setPrimary(service.current.id(), null, true);
262 // clear the currently focused user
263 service.clearPrimary = function() {
264 // reset with no patron
265 service.resetPatronLists();
266 service.current = null;
267 service.patron_stats = null;
271 // sets the primary display user, fetching data as necessary.
272 service.setPrimary = function(id, user, force) {
273 var user_id = id ? id : (user ? user.id() : null);
275 console.debug('setting primary user to: ' + user_id);
277 if (!user_id) return $q.reject();
279 // when loading a new patron, update the last patron setting
280 if (!service.current || service.current.id() != user_id)
281 egCore.hatch.setLoginSessionItem('eg.circ.last_patron', user_id);
283 // avoid running multiple retrievals for the same patron, which
284 // can happen during dbl-click by maintaining a single running
285 // data retrieval promise
286 if (service.primaryUserPromise) {
287 if (service.primaryUserId == user_id) {
288 return service.primaryUserPromise.promise;
290 service.primaryUserPromise = null;
294 service.primaryUserPromise = $q.defer();
295 service.primaryUserId = user_id;
297 service.getPrimary(id, user, force)
299 var p = service.primaryUserPromise;
300 service.primaryUserId = null;
301 // clear before resolution just to be safe.
302 service.primaryUserPromise = null;
306 return service.primaryUserPromise.promise;
309 service.getPrimary = function(id, user, force) {
312 if (!force && service.current &&
313 service.current.id() == user.id()) {
314 if (service.patron_stats) {
317 return service.fetchUserStats();
321 service.resetPatronLists();
322 service.current = user;
323 service.localFlesh(user);
324 return service.fetchUserStats();
327 if (!force && service.current && service.current.id() == id) {
328 if (service.patron_stats) {
331 return service.fetchUserStats();
335 service.resetPatronLists();
337 return egUser.get(id).then(
339 service.current = user;
340 service.localFlesh(user);
341 return service.fetchUserStats();
345 "unable to fetch user "+id+': '+js2JSON(err))
350 // fetching a null user clears the primary user.
351 // NOTE: this should probably reject() and log an error,
352 // but calling clear for backwards compat for now.
353 return service.clearPrimary();
357 // flesh some additional user fields locally
358 service.localFlesh = function(user) {
359 if (!angular.isObject(typeof user.home_ou()))
360 user.home_ou(egCore.org.get(user.home_ou()));
363 user.standing_penalties(),
365 if (!angular.isObject(penalty.org_unit()))
366 penalty.org_unit(egCore.org.get(penalty.org_unit()));
370 // stat_cat_entries == stat_cat_entry_user_map
371 angular.forEach(user.stat_cat_entries(), function(map) {
372 if (angular.isObject(map.stat_cat())) return;
373 // At page load, we only retrieve org-visible stat cats.
374 // For the common case, ignore entries for remote stat cats.
375 var cat = egCore.env.actsc.map[map.stat_cat()];
378 cat.owner(egCore.org.get(cat.owner()));
383 // resolves to true if the patron account has expired or will
384 // expire soon, based on YAOUS circ.patron_expires_soon_warning
385 // note: returning a promise is no longer strictly necessary
386 // (no more async activity) if the calling function is changed too.
387 service.testExpire = function() {
389 var expire = Date.parse(service.current.expire_date());
390 if (expire < new Date()) {
391 return $q.when(service.patronExpired = true);
394 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
396 var preExpire = new Date();
397 preExpire.setDate(preExpire.getDate() + Number(soon));
398 if (expire < preExpire)
399 return $q.when(service.patronExpiresSoon = true);
402 return $q.when(false);
405 // resolves to true if the patron account has any invalid addresses.
406 service.testInvalidAddrs = function() {
408 if (service.invalidAddresses)
409 return $q.when(true);
414 service.current.addresses(),
415 function(addr) { if (addr.valid() == 'f') fail = true }
418 return $q.when(fail);
421 // resolves to true if there is any aspect of the patron account
422 // which should produce a message in the alerts panel
423 service.checkAlerts = function() {
425 if (service.hasAlerts) // already checked
426 return $q.when(true);
428 var deferred = $q.defer();
429 var p = service.current;
431 if (service.alert_penalties.length ||
435 service.patron_stats.holds.ready) {
437 service.hasAlerts = true;
440 // see if the user was retrieved with an inactive card
441 if (bc = $location.search().card) {
442 var card = p.cards().filter(
443 function(c) { return c.barcode() == bc })[0];
445 if (card && card.active() == 'f') {
446 service.hasAlerts = true;
447 service.retrievedWithInactive = true;
451 // regardless of whether we know of alerts, we still need
452 // to test/fetch the expire data for display
453 service.testExpire().then(function(bool) {
454 if (bool) service.hasAlerts = true;
455 deferred.resolve(service.hasAlerts);
458 service.testInvalidAddrs().then(function(bool) {
459 if (bool) service.invalidAddresses = true;
460 deferred.resolve(service.invalidAddresses);
463 return deferred.promise;
466 service.fetchGroupFines = function() {
467 return egCore.net.request(
469 'open-ils.actor.usergroup.members.balance_owed',
470 egCore.auth.token(), service.current.usrgroup()
471 ).then(function(list) {
473 angular.forEach(list, function(u) {
474 total += 100 * Number(u.balance_owed)
476 service.patron_stats.fines.group_balance_owed = total / 100;
480 service.getUserStats = function(id) {
481 return egCore.net.request(
483 'open-ils.actor.user.opac.vital_stats.authoritative',
484 egCore.auth.token(), id
487 // force numeric to ensure correct boolean handling in templates
488 stats.fines.balance_owed = Number(stats.fines.balance_owed);
489 stats.checkouts.overdue = Number(stats.checkouts.overdue);
490 stats.checkouts.claims_returned =
491 Number(stats.checkouts.claims_returned);
492 stats.checkouts.lost = Number(stats.checkouts.lost);
493 stats.checkouts.out = Number(stats.checkouts.out);
494 stats.checkouts.total_out =
495 stats.checkouts.out + stats.checkouts.overdue;
497 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
498 stats.checkouts.total_out += stats.checkouts.claims_returned;
500 if (egCore.env.aous['circ.tally_lost'])
501 stats.checkouts.total_out += stats.checkouts.lost
508 // Fetches the IDs of any active non-cat checkouts for the current
509 // user. Also sets the patron_stats non_cat count value to match.
510 service.getUserNonCats = function(id) {
511 return egCore.net.request(
513 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
514 egCore.auth.token(), id
515 ).then(function(noncat_ids) {
516 service.noncat_ids = noncat_ids;
517 service.patron_stats.checkouts.noncat = noncat_ids.length;
521 // grab additional circ info
522 service.fetchUserStats = function() {
523 return service.getUserStats(service.current.id())
524 .then(function(stats) {
525 service.patron_stats = stats
526 service.alert_penalties = service.current.standing_penalties()
527 .filter(function(pen) {
528 return pen.standing_penalty().staff_alert() == 't'
531 service.summary_stat_cats = [];
532 angular.forEach(service.current.stat_cat_entries(),
534 if (angular.isObject(map.stat_cat()) &&
535 map.stat_cat().usr_summary() == 't') {
536 service.summary_stat_cats.push(map);
541 // run these two in parallel
542 var p1 = service.getUserNonCats(service.current.id());
543 var p2 = service.fetchGroupFines();
544 return $q.all([p1, p2]);
548 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
549 // which is the Angular default.
550 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
551 // FIXME: This change needs to be moved into a project-wide collection
552 // of locale overrides.
553 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
554 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
560 * Manages tabbed patron view.
561 * This is the parent scope of all patron tab scopes.
564 .controller('PatronCtrl',
565 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
566 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
568 $scope.is_patron_edit = function() {
569 return Boolean($location.path().match(/patron\/\d+\/edit$/));
572 // To support the fixed position patron edit actions bar,
573 // its markup has to live outside the scope of the patron
574 // edit controller. Insert a scope blob here that can be
575 // modifed from within the patron edit controller.
576 $scope.edit_passthru = {};
578 // returns true if a redirect occurs
579 function redirectToAlertPanel() {
581 $scope.alert_penalties =
582 function() {return patronSvc.alert_penalties}
584 if (patronSvc.alertsShown) return false;
585 patronSvc.alertsShown = true;
587 // if the patron has any unshown alerts, show them now
588 if (patronSvc.hasAlerts &&
589 !$location.path().match(/alerts$/)) {
592 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
593 .search('card', null);
597 // no alert required. If the patron has fines and the show-bills
598 // OUS is applied, direct to the bills page.
599 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
600 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
601 && !$location.path().match(/bills$/)) {
603 $scope.tab = 'bills';
605 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
606 .search('card', null);
614 // called after each route-specified controller is instantiated.
615 // this doubles as a way to inform the top-level controller that
616 // egStartup.go() has completed, which means we are clear to
617 // fetch the patron, etc.
618 $scope.initTab = function(tab, patron_id) {
619 console.log('init tab ' + tab);
621 $scope.aous = egCore.env.aous;
624 $scope.patron_id = patron_id;
625 return patronSvc.setPrimary($scope.patron_id)
626 .then(function() {return patronSvc.checkAlerts()})
627 .then(redirectToAlertPanel);
632 $scope._show_dob = {};
633 $scope.show_dob = function (val) {
634 if ($scope.patron()) {
635 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
636 return $scope._show_dob[$scope.patron().id()];
638 return !egCore.env.aous['circ.obscure_dob'];
641 $scope.obscure_dob = function() {
642 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
644 $scope.now_show_dob = function() {
645 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
646 $scope.show_dob() : true;
649 $scope.patron = function() { return patronSvc.current }
650 $scope.patron_stats = function() { return patronSvc.patron_stats }
651 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
653 $scope.print_address = function(addr) {
656 template : 'patron_address',
658 patron : egCore.idl.toHash(patronSvc.current),
659 address : egCore.idl.toHash(addr)
664 $scope.toggle_expand_summary = function() {
665 if ($scope.collapsePatronSummary) {
666 $scope.collapsePatronSummary = false;
667 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
669 $scope.collapsePatronSummary = true;
670 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
674 // always expand the patron summary in the search UI, regardless
675 // of stored preference.
676 $scope.collapse_summary = function() {
677 return $scope.tab != 'search' && $scope.collapsePatronSummary;
680 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
681 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
684 .controller('PatronBarcodeSearchCtrl',
685 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
686 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
687 $scope.selectMe = true; // focus text input
688 patronSvc.clearPrimary(); // clear the default user
690 // jump to the patron checkout UI
691 function loadPatron(user_id) {
693 .path('/circ/patron/' + user_id + '/checkout')
694 .search('card', $scope.args.barcode);
697 // create an opt-in=yes response for the loaded user
698 function createOptIn(user_id) {
701 'open-ils.actor.user.org_unit_opt_in.create',
702 egCore.auth.token(), user_id).then(function(resp) {
703 if (evt = egCore.evt.parse(resp)) return alert(evt);
709 $scope.submitBarcode = function(args) {
710 $scope.bcNotFound = null;
711 $scope.optInRestricted = false;
712 if (!args.barcode) return;
714 // blur so next time it's set to true it will re-apply select()
715 $scope.selectMe = false;
722 'open-ils.actor.get_barcodes',
723 egCore.auth.token(), egCore.auth.user().ws_ou(),
724 'actor', args.barcode)
726 .then(function(resp) { // get_barcodes
728 if (evt = egCore.evt.parse(resp)) {
733 if (!resp || !resp[0]) {
734 $scope.bcNotFound = args.barcode;
735 $scope.selectMe = true;
739 // see if an opt-in request is needed
740 user_id = resp[0].id;
741 return egCore.net.request(
743 'open-ils.actor.user.org_unit_opt_in.check',
744 egCore.auth.token(), user_id);
746 }).then(function(optInResp) { // opt_in_check
748 if (evt = egCore.evt.parse(optInResp)) {
753 if (optInResp == 2) {
754 // opt-in disallowed at this location by patron's home library
755 $scope.optInRestricted = true;
756 $scope.selectMe = true;
760 if (optInResp == 1) {
761 // opt-in handled or not needed
762 return loadPatron(user_id);
765 // opt-in needed, show the opt-in dialog
766 egUser.get(user_id, {useFields : []})
768 .then(function(user) { // retrieve user
769 egConfirmDialog.open(
770 egCore.strings.OPT_IN_DIALOG, '',
771 { org : egCore.org.get(user.home_ou()),
773 ok : function() { createOptIn(user.id()) },
774 cancel : function() {}
784 * Manages patron search
786 .controller('PatronSearchCtrl',
787 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
788 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
789 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
790 $filter, egUser, patronSvc , egGridDataProvider , $document) {
792 $scope.initTab('search');
793 $scope.focusMe = true;
794 $scope.searchArgs = {
795 // default to searching globally
796 home_ou : egCore.org.tree()
799 // last used patron search form element
802 $scope.gridControls = {
803 activateItem : function(item) {
804 $location.path('/circ/patron/' + item.id() + '/checkout');
806 selectedItems : function() {return []}
809 // Handle URL-encoded searches
810 if ($location.search().search) {
811 console.log('URL search = ' + $location.search().search);
812 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
814 // why the double-JSON encoded sort?
815 if (patronSvc.urlSearch.search.search_sort) {
816 patronSvc.urlSearch.sort =
817 JSON2js(patronSvc.urlSearch.search.search_sort);
819 patronSvc.urlSearch.sort = [];
821 delete patronSvc.urlSearch.search.search_sort;
825 if (patronSvc.lastSearch) {
826 propagate = patronSvc.lastSearch.search;
827 } else if (patronSvc.urlSearch) {
828 propagate = patronSvc.urlSearch.search;
831 if (egCore.env.pgt) {
832 $scope.profiles = egCore.env.pgt.list;
834 egCore.pcrud.search('pgt', {parent : null},
835 {flesh : -1, flesh_fields : {pgt : ['children']}}
838 egCore.env.absorbTree(tree, 'pgt')
839 $scope.profiles = egCore.env.pgt.list;
845 // populate the search form with our cached / preexisting search info
846 angular.forEach(propagate, function(val, key) {
847 if (key == 'profile')
848 val.value = $scope.profiles.filter(function(p) { p.id() == val.value })[0];
849 if (key == 'home_ou')
850 val.value = egCore.org.get(val.value);
851 $scope.searchArgs[key] = val.value;
855 var provider = egGridDataProvider.instance({});
858 function() {return $scope.gridControls.selectedItems()},
861 patronSvc.setPrimary(null, list[0]);
866 provider.get = function(offset, count) {
867 var deferred = $q.defer();
870 if (patronSvc.urlSearch) {
871 fullSearch = patronSvc.urlSearch;
872 // enusre the urlSearch only runs once.
873 delete patronSvc.urlSearch;
877 var search = compileSearch($scope.searchArgs);
878 if (Object.keys(search) == 0) return $q.when();
880 var home_ou = search.home_ou;
881 delete search.home_ou;
882 var inactive = search.inactive;
883 delete search.inactive;
887 sort : compileSort(),
893 fullSearch.count = count;
894 fullSearch.offset = offset;
896 if (patronSvc.lastSearch) {
897 // search repeated, return the cached results
898 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
899 console.log('patron search returning ' +
900 patronSvc.patrons.length + ' cached results');
902 // notify has to happen after returning the promise
905 angular.forEach(patronSvc.patrons, function(user) {
906 deferred.notify(user);
911 return deferred.promise;
915 patronSvc.lastSearch = fullSearch;
917 if (fullSearch.search.id) {
918 // search by user id performs a direct ID lookup
919 var userId = fullSearch.search.id.value;
922 egUser.get(userId).then(function(user) {
923 patronSvc.localFlesh(user);
924 patronSvc.patrons = [user];
925 deferred.notify(user);
930 return deferred.promise;
933 patronSvc.patrons = [];
936 'open-ils.actor.patron.search.advanced.fleshed',
943 egUser.defaultFleshFields,
947 function() { deferred.resolve() },
950 patronSvc.localFlesh(user); // inline
951 patronSvc.patrons.push(user);
952 deferred.notify(user);
956 return deferred.promise;
959 $scope.patronSearchGridProvider = provider;
961 // determine the tree depth of the profile group
962 $scope.pgt_depth = function(grp) {
964 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
968 $scope.clearForm = function () {
969 $scope.searchArgs={};
970 if (lastFormElement) lastFormElement.focus();
973 $scope.applyShowExtras = function($event, bool) {
975 $scope.showExtras = true;
976 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
978 $scope.showExtras = false;
979 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
981 if (lastFormElement) lastFormElement.focus();
982 $event.preventDefault();
985 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
986 .then(function(val) {$scope.showExtras = val});
988 // map form arguments into search params
989 function compileSearch(args) {
991 angular.forEach(args, function(val, key) {
993 if (key == 'profile' && args.profile) {
994 search.profile = {value : args.profile.id(), group : 0};
995 } else if (key == 'home_ou' && args.home_ou) {
996 search.home_ou = args.home_ou.id(); // passed separately
997 } else if (key == 'inactive') {
998 search.inactive = val;
1000 search[key] = {value : val, group : 0};
1002 if (key.match(/phone|ident/)) {
1003 search[key].group = 2;
1005 if (key.match(/street|city|state|post_code/)) {
1006 search[key].group = 1;
1007 } else if (key == 'card') {
1008 search[key].group = 3
1016 function compileSort() {
1018 if (!provider.sort.length) {
1021 "first_given_name ASC",
1022 "second_given_name ASC",
1031 if (angular.isObject(sortdef)) {
1032 var name = Object.keys(sortdef)[0];
1033 var dir = sortdef[name];
1034 sort.push(name + ' ' + dir);
1044 $scope.setLastFormElement = function() {
1045 lastFormElement = $document[0].activeElement;
1048 // search form submit action; tells the results grid to
1050 $scope.search = function(args) { // args === $scope.searchArgs
1051 if (args && Object.keys(args).length)
1052 $scope.gridControls.refresh();
1053 if (lastFormElement) lastFormElement.focus();
1056 // TODO: move this into the (forthcoming) grid row activate action
1057 $scope.onPatronDblClick = function($event, user) {
1058 $location.path('/circ/patron/' + user.id() + '/checkout');
1061 if (patronSvc.urlSearch) {
1062 // force the grid to load the url-based search on page load
1071 .controller('PatronMessagesCtrl',
1072 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
1073 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
1074 $scope.initTab('messages', $routeParams.id);
1075 var usr_id = $routeParams.id;
1077 // setup date filters
1078 var start = new Date(); // now - 1 year
1079 start.setFullYear(start.getFullYear() - 1),
1082 end_date : new Date()
1085 function date_range() {
1086 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1087 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1088 var today = new Date().toISOString().replace(/T.*/,'');
1089 if (end == today) end = 'now';
1090 return [start, end];
1095 var activeGrid = $scope.activeGridControls = {
1096 setSort : function() {
1097 return ['set_date'];
1099 setQuery : function() {
1104 {stop_date : {'>' : 'now'}}
1110 var archiveGrid = $scope.archiveGridControls = {
1111 setSort : function() {
1112 return ['set_date'];
1114 setQuery : function() {
1117 stop_date : {'<=' : 'now'},
1118 set_date : {between : date_range()}
1123 $scope.removePenalty = function(selected) {
1124 // the grid stores flattened penalties. Fetch penalty objects first
1126 var ids = selected.map(function(s){ return s.id });
1127 egCore.pcrud.search('ausp',
1129 {atomic : true, authoritative : true}
1132 ).then(function(penalties) {
1133 return egCore.pcrud.remove(penalties);
1135 // then refresh the grid
1136 }).then(function() {
1137 activeGrid.refresh();
1141 $scope.archivePenalty = 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 angular.forEach(penalties, function(p){ p.stop_date('now') });
1152 return egCore.pcrud.update(penalties);
1154 // then refresh the grid
1155 }).then(function() {
1156 activeGrid.refresh();
1157 archiveGrid.refresh();
1161 // leverage egEnv for caching
1162 function fetchPenaltyTypes() {
1164 return $q.when(egCore.env.csp.list);
1165 return egCore.pcrud.search(
1166 // id <= 100 are reserved for system use
1167 'csp', {id : {'>': 100}}, {}, {atomic : true})
1168 .then(function(penalties) {
1169 egCore.env.absorbList(penalties, 'csp');
1174 $scope.createPenalty = function() {
1175 egCirc.create_penalty(usr_id).then(function() {
1176 activeGrid.refresh();
1177 // force a refresh of the user, since they may now
1178 // have blocking penalties, etc.
1179 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1183 $scope.editPenalty = function(selected) {
1184 if (selected.length == 0) return;
1186 // grab the penalty from the user object
1187 var penalty = patronSvc.current.standing_penalties().filter(
1188 function(p) {return p.id() == selected[0].id})[0];
1190 egCirc.edit_penalty(penalty).then(function() {
1191 activeGrid.refresh();
1192 // force a refresh of the user, since they may now
1193 // have blocking penalties, etc.
1194 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1201 * Credentials tester
1203 .controller('PatronVerifyCredentialsCtrl',
1204 ['$scope','$routeParams','$location','egCore',
1205 function($scope, $routeParams , $location , egCore) {
1206 $scope.verified = null;
1207 $scope.focusMe = true;
1209 // called with a patron, pre-populate the form args
1210 $scope.initTab('other', $routeParams.id).then(
1212 if ($routeParams.id && $scope.patron()) {
1213 $scope.prepop = true;
1214 $scope.username = $scope.patron().usrname();
1215 $scope.barcode = $scope.patron().card().barcode();
1217 $scope.username = '';
1218 $scope.barcode = '';
1219 $scope.password = '';
1224 // verify login credentials
1225 $scope.verify = function() {
1226 $scope.verified = null;
1227 $scope.notFound = false;
1231 'open-ils.actor.verify_user_password',
1232 egCore.auth.token(), $scope.barcode,
1233 $scope.username, hex_md5($scope.password || '')
1235 ).then(function(resp) {
1236 $scope.focusMe = true;
1237 if (evt = egCore.evt.parse(resp)) {
1239 } else if (resp == 1) {
1240 $scope.verified = true;
1242 $scope.verified = false;
1247 // load the main patron UI for the provided username or barcode
1248 $scope.load = function($event) {
1249 $scope.notFound = false;
1250 $scope.verified = null;
1254 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1255 egCore.auth.token(), $scope.barcode, $scope.username
1257 ).then(function(resp) {
1260 $location.path('/circ/patron/' + resp + '/checkout');
1264 // something went wrong...
1265 $scope.focusMe = true;
1266 if (evt = egCore.evt.parse(resp)) {
1267 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1268 $scope.notFound = true;
1277 // load() button sits within the verify form.
1278 // avoid submitting the verify() form action on load()
1279 $event.preventDefault();
1283 .controller('PatronAlertsCtrl',
1284 ['$scope','$routeParams','$location','egCore','patronSvc',
1285 function($scope, $routeParams , $location , egCore , patronSvc) {
1287 $scope.initTab('other', $routeParams.id)
1289 $scope.patronExpired = patronSvc.patronExpired;
1290 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1291 $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1292 $scope.invalidAddresses = patronSvc.invalidAddresses;
1297 .controller('PatronNotesCtrl',
1298 ['$scope','$routeParams','$location','egCore','patronSvc','$uibModal',
1299 function($scope, $routeParams , $location , egCore , patronSvc , $uibModal) {
1300 $scope.initTab('other', $routeParams.id);
1301 var usr_id = $routeParams.id;
1304 function refreshPage() {
1306 egCore.pcrud.search('aun',
1308 {flesh : 1, flesh_fields : {aun : ['creator']}},
1309 {authoritative : true})
1310 .then(null, null, function(note) {
1311 $scope.notes.push(note);
1315 // open the new-note dialog and create the note
1316 $scope.newNote = function() {
1318 templateUrl: './circ/patron/t_new_note_dialog',
1320 ['$scope', '$uibModalInstance',
1321 function($scope, $uibModalInstance) {
1322 $scope.focusNote = true;
1324 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1325 $scope.cancel = function () { $uibModalInstance.dismiss() }
1329 if (!args.value) return;
1330 var note = new egCore.idl.aun();
1332 note.title(args.title);
1333 note.value(args.value);
1334 note.pub(args.pub ? 't' : 'f');
1335 note.creator(egCore.auth.user().id());
1336 egCore.pcrud.create(note).then(function() {refreshPage()});
1341 // delete the selected note
1342 $scope.deleteNote = function(note) {
1343 egCore.pcrud.remove(note).then(function() {refreshPage()});
1346 // print the selected note
1347 $scope.printNote = function(note) {
1348 var hash = egCore.idl.toHash(note);
1349 hash.usr = egCore.idl.toHash($scope.patron());
1350 egCore.print.print({
1351 context : 'default',
1352 template : 'patron_note',
1353 scope : {note : hash}
1357 // perform the initial note fetch
1361 .controller('PatronGroupCtrl',
1362 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1363 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1364 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1365 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1367 var usr_id = $routeParams.id;
1369 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1371 var grid = $scope.gridControls = {
1372 activateItem : function(item) {
1373 $location.path('/circ/patron/' + item.id + '/checkout');
1375 itemRetrieved : function(item) {
1377 if (item.id == patronSvc.current.id()) {
1378 item.stats = patronSvc.patron_stats;
1381 // flesh stats for other group members
1382 patronSvc.getUserStats(item.id).then(function(stats) {
1384 $scope.totals.total_out += stats.checkouts.total_out;
1385 $scope.totals.overdue += stats.checkouts.overdue;
1389 setSort : function() {
1390 return ['create_date'];
1394 $scope.initTab('other', $routeParams.id)
1395 .then(function(redirect) {
1396 // if we are redirecting to the alerts page, avoid updating the
1398 if (redirect) return;
1399 // let initTab() fetch the user first so we can know the usrgroup
1402 usrgroup : patronSvc.current.usrgroup(),
1405 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1408 $scope.removeFromGroup = function(selected) {
1410 angular.forEach(selected, function(user) {
1411 console.debug('removing user ' + user.id + ' from group');
1416 'open-ils.actor.usergroup.new',
1417 egCore.auth.token(), user.id, true
1422 $q.all(promises).then(function() {grid.refresh()});
1425 function addUserToGroup(user) {
1426 user.usrgroup(patronSvc.current.usrgroup());
1427 user.ischanged(true);
1430 'open-ils.actor.patron.update',
1431 egCore.auth.token(), user
1433 ).then(function() {grid.refresh()});
1436 // fetch each user ("selected" has flattened users)
1437 // update the usrgroup, then update the user object
1438 // After all updates are complete, refresh the grid.
1439 function moveUsersToGroup(target_user, selected) {
1442 angular.forEach(selected, function(user) {
1444 egCore.pcrud.retrieve('au', user.id)
1446 u.usrgroup(target_user.usrgroup());
1448 return egCore.net.request(
1450 'open-ils.actor.patron.update',
1451 egCore.auth.token(), u
1457 $q.all(promises).then(function() {grid.refresh()});
1460 function showMoveToGroupConfirm(barcode, selected, outbound) {
1463 egCore.pcrud.search('ac', {barcode : barcode})
1465 // fetch the fleshed user
1466 .then(function(card) {
1468 if (!card) return; // TODO: warn user
1470 egCore.pcrud.retrieve('au', card.usr())
1471 .then(function(user) {
1474 templateUrl: './circ/patron/t_move_to_group_dialog',
1476 '$scope','$uibModalInstance',
1477 function($scope , $uibModalInstance) {
1479 $scope.selected = selected;
1480 $scope.outbound = outbound;
1482 function(count) { $uibModalInstance.close() }
1484 function () { $uibModalInstance.dismiss() }
1487 }).result.then(function() {
1489 moveUsersToGroup(user, selected);
1491 addUserToGroup(user);
1498 // selected == move selected patrons to another patron's group
1499 // !selected == patron from a different group moves into our group
1500 function moveToGroup(selected, outbound) {
1501 egPromptDialog.open(
1502 egCore.strings.GROUP_ADD_USER, '',
1503 {ok : function(value) {
1505 showMoveToGroupConfirm(value, selected, outbound);
1510 $scope.moveToGroup = function() { moveToGroup([], false) };
1511 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1513 $scope.cloneUser = function(selected) {
1514 if (!selected.length) return;
1515 var url = $location.absUrl().replace(
1517 '/patron/register/clone/' + selected[0].id);
1518 $window.open(url, '_blank').focus();
1521 $scope.retrieveSelected = function(selected) {
1522 if (!selected.length) return;
1523 angular.forEach(selected, function(usr) {
1524 $timeout(function() {
1525 var url = $location.absUrl().replace(
1527 '/patron/' + usr.id + '/checkout');
1528 $window.open(url, '_blank')
1535 .controller('PatronStatCatsCtrl',
1536 ['$scope','$routeParams','$q','egCore','patronSvc',
1537 function($scope, $routeParams , $q , egCore , patronSvc) {
1538 $scope.initTab('other', $routeParams.id)
1539 .then(function(redirect) {
1540 // Entries for org-visible stat cats are fleshed. Any others
1541 // have to be fleshed within.
1544 angular.forEach(patronSvc.current.stat_cat_entries(),
1546 if (!angular.isObject(entry.stat_cat())) {
1547 to_flesh[entry.stat_cat()] = entry;
1552 if (!Object.keys(to_flesh).length) return;
1554 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1555 .then(null, null, function(cat) { // stream
1556 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1557 to_flesh[cat.id()].stat_cat(cat);
1562 .controller('PatronFetchLastCtrl',
1563 ['$scope','$location','egCore',
1564 function($scope , $location , egCore) {
1566 var id = egCore.hatch.getLoginSessionItem('eg.circ.last_patron');
1567 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1569 $scope.no_last = true;
1572 .controller('PatronTriggeredEventsCtrl',
1573 ['$scope','$routeParams','$location','egCore','patronSvc',
1574 function($scope, $routeParams, $location , egCore , patronSvc) {
1575 $scope.initTab('other', $routeParams.id);
1577 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1578 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1580 $scope.triggered_events_url = url;
1584 .controller('PatronPermsCtrl',
1585 ['$scope','$routeParams','$window','$location','egCore',
1586 function($scope , $routeParams , $window , $location , egCore) {
1587 $scope.initTab('other', $routeParams.id);
1589 var url = $location.absUrl().replace(
1590 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1592 url += '?usr=' + encodeURIComponent($routeParams.id);
1594 // user_edit does not load the session via cookie. It uses URL
1595 // params or xulG instead. Pass via xulG.
1597 ses : egCore.auth.token(),
1598 on_patron_save : function() {
1599 $scope.funcs.reload();
1603 $scope.user_perms_url = url;