4 * Search, checkout, items out, holds, bills, edit, etc.
7 angular.module('egPatronApp', ['ngRoute', 'ui.bootstrap',
8 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod'])
10 .config(function($routeProvider, $locationProvider, $compileProvider) {
11 $locationProvider.html5Mode(true);
12 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
14 // data loaded at startup which only requires an authtoken goes
15 // here. this allows the requests to be run in parallel instead of
16 // waiting until startup has completed.
17 var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
19 // fetch the org settings we care about during egStartup
20 // and toss them into egCore.env as egCore.env.aous[name] = value.
21 // note: only load settings here needed by all tabs; load tab-
22 // specific settings from within their respective controllers
23 egCore.env.classLoaders.aous = function() {
24 return egCore.org.settings([
25 'circ.do_not_tally_claims_returned',
28 'ui.circ.show_billing_tab_on_bills',
29 'circ.patron_expires_soon_warning',
30 'ui.circ.items_out.lost',
31 'ui.circ.items_out.longoverdue',
32 'ui.circ.items_out.claimsreturned'
33 ]).then(function(settings) {
34 // local settings are cached within egOrg. Caching them
35 // again in egEnv just simplifies the syntax for access.
36 egCore.env.aous = settings;
40 egCore.env.loadClasses.push('aous');
42 // app-globally modify the default flesh fields for
43 // fleshed user retrieval.
44 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
45 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
55 return egCore.startup.go().then(function() {
57 // This call requires orgs to be loaded, because it
58 // calls egCore.org.ancestors(), so call it after startup
59 return egCore.pcrud.search('actsc',
60 {owner : egCore.org.ancestors(
61 egCore.auth.user().ws_ou(), true)},
63 ).then(function(cats) {
64 egCore.env.absorbList(cats, 'actsc');
69 $routeProvider.when('/circ/patron/search', {
70 templateUrl: './circ/patron/t_search',
71 controller: 'PatronSearchCtrl',
75 $routeProvider.when('/circ/patron/bcsearch', {
76 templateUrl: './circ/patron/t_bcsearch',
77 controller: 'PatronBarcodeSearchCtrl',
81 $routeProvider.when('/circ/patron/credentials', {
82 templateUrl: './circ/patron/t_credentials',
83 controller: 'PatronVerifyCredentialsCtrl',
87 $routeProvider.when('/circ/patron/last', {
88 templateUrl: './circ/patron/t_last_patron',
89 controller: 'PatronFetchLastCtrl',
93 // the following require a patron ID
95 $routeProvider.when('/circ/patron/:id/alerts', {
96 templateUrl: './circ/patron/t_alerts',
97 controller: 'PatronAlertsCtrl',
101 $routeProvider.when('/circ/patron/:id/checkout', {
102 templateUrl: './circ/patron/t_checkout',
103 controller: 'PatronCheckoutCtrl',
107 $routeProvider.when('/circ/patron/:id/items_out', {
108 templateUrl: './circ/patron/t_items_out',
109 controller: 'PatronItemsOutCtrl',
113 $routeProvider.when('/circ/patron/:id/holds', {
114 templateUrl: './circ/patron/t_holds',
115 controller: 'PatronHoldsCtrl',
119 $routeProvider.when('/circ/patron/:id/holds/create', {
120 templateUrl: './circ/patron/t_holds_create',
121 controller: 'PatronHoldsCreateCtrl',
125 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
126 templateUrl: './circ/patron/t_holds',
127 controller: 'PatronHoldsCtrl',
131 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
132 templateUrl: './circ/patron/t_hold_details',
133 controller: 'PatronHoldDetailsCtrl',
137 $routeProvider.when('/circ/patron/:id/bills', {
138 templateUrl: './circ/patron/t_bills',
139 controller: 'PatronBillsCtrl',
143 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
144 templateUrl: './circ/patron/t_xact_details',
145 controller: 'XactDetailsCtrl',
149 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
150 templateUrl: './circ/patron/t_bill_history',
151 controller: 'BillHistoryCtrl',
155 $routeProvider.when('/circ/patron/:id/messages', {
156 templateUrl: './circ/patron/t_messages',
157 controller: 'PatronMessagesCtrl',
161 $routeProvider.when('/circ/patron/:id/edit', {
162 templateUrl: './circ/patron/t_edit',
163 controller: 'PatronRegCtrl',
167 $routeProvider.when('/circ/patron/:id/credentials', {
168 templateUrl: './circ/patron/t_credentials',
169 controller: 'PatronVerifyCredentialsCtrl',
173 $routeProvider.when('/circ/patron/:id/notes', {
174 templateUrl: './circ/patron/t_notes',
175 controller: 'PatronNotesCtrl',
179 $routeProvider.when('/circ/patron/:id/triggered_events', {
180 templateUrl: './circ/patron/t_triggered_events',
181 controller: 'PatronTriggeredEventsCtrl',
185 $routeProvider.when('/circ/patron/:id/edit_perms', {
186 templateUrl: './circ/patron/t_edit_perms',
187 controller: 'PatronPermsCtrl',
191 $routeProvider.when('/circ/patron/:id/group', {
192 templateUrl: './circ/patron/t_group',
193 controller: 'PatronGroupCtrl',
197 $routeProvider.when('/circ/patron/:id/stat_cats', {
198 templateUrl: './circ/patron/t_stat_cats',
199 controller: 'PatronStatCatsCtrl',
203 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
209 .factory('patronSvc',
210 ['$q','$timeout','$location','egCore','egUser','$locale',
211 function($q , $timeout , $location , egCore, egUser , $locale) {
214 // cached patron search results
217 // currently selected patron object
220 // patron circ stats (overdues, fines, holds)
223 // event types manually overridden, which should always be
224 // overridden for checkouts to this patron for this instance of
226 checkout_overrides : {},
229 // when we change the default patron, we need to clear out any
230 // data collected on that patron
231 service.resetPatronLists = function() {
232 service.checkouts = [];
233 service.items_out = []
234 service.items_out_ids = [];
236 service.hold_ids = [];
237 service.checkout_overrides = {};
238 service.patron_stats = null;
239 service.noncat_ids = [];
240 service.hasAlerts = false;
241 service.alertsShown = false;
242 service.patronExpired = false;
243 service.patronExpiresSoon = false;
244 service.retrievedWithInactive = false;
245 service.invalidAddresses = false;
247 service.resetPatronLists(); // initialize
249 // shortcut to force-reload the current primary
250 service.refreshPrimary = function() {
251 if (!service.current) return $q.when();
252 return service.setPrimary(service.current.id(), null, true);
255 // clear the currently focused user
256 service.clearPrimary = function() {
257 // reset with no patron
258 service.resetPatronLists();
259 service.current = null;
260 service.patron_stats = null;
264 // sets the primary display user, fetching data as necessary.
265 service.setPrimary = function(id, user, force) {
266 var user_id = id ? id : (user ? user.id() : null);
268 console.debug('setting primary user to: ' + user_id);
270 if (!user_id) return $q.reject();
272 // when loading a new patron, update the last patron setting
273 if (!service.current || service.current.id() != user_id)
274 egCore.hatch.setLocalItem('eg.circ.last_patron', user_id);
276 // avoid running multiple retrievals for the same patron, which
277 // can happen during dbl-click by maintaining a single running
278 // data retrieval promise
279 if (service.primaryUserPromise) {
280 if (service.primaryUserId == user_id) {
281 return service.primaryUserPromise.promise;
283 service.primaryUserPromise = null;
287 service.primaryUserPromise = $q.defer();
288 service.primaryUserId = user_id;
290 service.getPrimary(id, user, force)
292 var p = service.primaryUserPromise;
293 service.primaryUserId = null;
294 // clear before resolution just to be safe.
295 service.primaryUserPromise = null;
299 return service.primaryUserPromise.promise;
302 service.getPrimary = function(id, user, force) {
305 if (!force && service.current &&
306 service.current.id() == user.id()) {
307 if (service.patron_stats) {
310 return service.fetchUserStats();
314 service.resetPatronLists();
315 service.current = user;
316 service.localFlesh(user);
317 return service.fetchUserStats();
320 if (!force && service.current && service.current.id() == id) {
321 if (service.patron_stats) {
324 return service.fetchUserStats();
328 service.resetPatronLists();
330 return egUser.get(id).then(
332 service.current = user;
333 service.localFlesh(user);
334 return service.fetchUserStats();
338 "unable to fetch user "+id+': '+js2JSON(err))
343 // fetching a null user clears the primary user.
344 // NOTE: this should probably reject() and log an error,
345 // but calling clear for backwards compat for now.
346 return service.clearPrimary();
350 // flesh some additional user fields locally
351 service.localFlesh = function(user) {
352 if (!angular.isObject(typeof user.home_ou()))
353 user.home_ou(egCore.org.get(user.home_ou()));
356 user.standing_penalties(),
358 if (!angular.isObject(penalty.org_unit()))
359 penalty.org_unit(egCore.org.get(penalty.org_unit()));
363 // stat_cat_entries == stat_cat_entry_user_map
364 angular.forEach(user.stat_cat_entries(), function(map) {
365 if (angular.isObject(map.stat_cat())) return;
366 // At page load, we only retrieve org-visible stat cats.
367 // For the common case, ignore entries for remote stat cats.
368 var cat = egCore.env.actsc.map[map.stat_cat()];
371 cat.owner(egCore.org.get(cat.owner()));
376 // resolves to true if the patron account has expired or will
377 // expire soon, based on YAOUS circ.patron_expires_soon_warning
378 // note: returning a promise is no longer strictly necessary
379 // (no more async activity) if the calling function is changed too.
380 service.testExpire = function() {
382 var expire = Date.parse(service.current.expire_date());
383 if (expire < new Date()) {
384 return $q.when(service.patronExpired = true);
387 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
389 var preExpire = new Date();
390 preExpire.setDate(preExpire.getDate() + Number(soon));
391 if (expire < preExpire)
392 return $q.when(service.patronExpiresSoon = true);
395 return $q.when(false);
398 // resolves to true if the patron account has any invalid addresses.
399 service.testInvalidAddrs = function() {
401 if (service.invalidAddresses)
402 return $q.when(true);
407 service.current.addresses(),
408 function(addr) { if (addr.valid() == 'f') fail = true }
411 return $q.when(fail);
414 // resolves to true if there is any aspect of the patron account
415 // which should produce a message in the alerts panel
416 service.checkAlerts = function() {
418 if (service.hasAlerts) // already checked
419 return $q.when(true);
421 var deferred = $q.defer();
422 var p = service.current;
424 if (service.alert_penalties.length ||
428 service.patron_stats.holds.ready) {
430 service.hasAlerts = true;
433 // see if the user was retrieved with an inactive card
434 if (bc = $location.search().card) {
435 var card = p.cards().filter(
436 function(c) { return c.barcode() == bc })[0];
438 if (card && card.active() == 'f') {
439 service.hasAlerts = true;
440 service.retrievedWithInactive = true;
444 // regardless of whether we know of alerts, we still need
445 // to test/fetch the expire data for display
446 service.testExpire().then(function(bool) {
447 if (bool) service.hasAlerts = true;
448 deferred.resolve(service.hasAlerts);
451 service.testInvalidAddrs().then(function(bool) {
452 if (bool) service.invalidAddresses = true;
453 deferred.resolve(service.invalidAddresses);
456 return deferred.promise;
459 service.fetchGroupFines = function() {
460 return egCore.net.request(
462 'open-ils.actor.usergroup.members.balance_owed',
463 egCore.auth.token(), service.current.usrgroup()
464 ).then(function(list) {
466 angular.forEach(list, function(u) {
467 total += 100 * Number(u.balance_owed)
469 service.patron_stats.fines.group_balance_owed = total / 100;
473 service.getUserStats = function(id) {
474 return egCore.net.request(
476 'open-ils.actor.user.opac.vital_stats.authoritative',
477 egCore.auth.token(), id
480 // force numeric to ensure correct boolean handling in templates
481 stats.fines.balance_owed = Number(stats.fines.balance_owed);
482 stats.checkouts.overdue = Number(stats.checkouts.overdue);
483 stats.checkouts.claims_returned =
484 Number(stats.checkouts.claims_returned);
485 stats.checkouts.lost = Number(stats.checkouts.lost);
486 stats.checkouts.out = Number(stats.checkouts.out);
487 stats.checkouts.total_out =
488 stats.checkouts.out + stats.checkouts.overdue;
490 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
491 stats.checkouts.total_out += stats.checkouts.claims_returned;
493 if (egCore.env.aous['circ.tally_lost'])
494 stats.checkouts.total_out += stats.checkouts.lost
501 // Fetches the IDs of any active non-cat checkouts for the current
502 // user. Also sets the patron_stats non_cat count value to match.
503 service.getUserNonCats = function(id) {
504 return egCore.net.request(
506 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
507 egCore.auth.token(), id
508 ).then(function(noncat_ids) {
509 service.noncat_ids = noncat_ids;
510 service.patron_stats.checkouts.noncat = noncat_ids.length;
514 // grab additional circ info
515 service.fetchUserStats = function() {
516 return service.getUserStats(service.current.id())
517 .then(function(stats) {
518 service.patron_stats = stats
519 service.alert_penalties = service.current.standing_penalties()
520 .filter(function(pen) {
521 return pen.standing_penalty().staff_alert() == 't'
524 service.summary_stat_cats = [];
525 angular.forEach(service.current.stat_cat_entries(),
527 if (angular.isObject(map.stat_cat()) &&
528 map.stat_cat().usr_summary() == 't') {
529 service.summary_stat_cats.push(map);
534 // run these two in parallel
535 var p1 = service.getUserNonCats(service.current.id());
536 var p2 = service.fetchGroupFines();
537 return $q.all([p1, p2]);
541 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
542 // which is the Angular default.
543 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
544 // FIXME: This change needs to be moved into a project-wide collection
545 // of locale overrides.
546 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
547 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
553 * Manages tabbed patron view.
554 * This is the parent scope of all patron tab scopes.
557 .controller('PatronCtrl',
558 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
559 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
561 $scope.is_patron_edit = function() {
562 return Boolean($location.path().match(/patron\/\d+\/edit$/));
565 // To support the fixed position patron edit actions bar,
566 // its markup has to live outside the scope of the patron
567 // edit controller. Insert a scope blob here that can be
568 // modifed from within the patron edit controller.
569 $scope.edit_passthru = {};
571 // returns true if a redirect occurs
572 function redirectToAlertPanel() {
574 $scope.alert_penalties =
575 function() {return patronSvc.alert_penalties}
577 if (patronSvc.alertsShown) return false;
578 patronSvc.alertsShown = true;
580 // if the patron has any unshown alerts, show them now
581 if (patronSvc.hasAlerts &&
582 !$location.path().match(/alerts$/)) {
585 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
586 .search('card', null);
590 // no alert required. If the patron has fines and the show-bills
591 // OUS is applied, direct to the bills page.
592 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
593 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
594 && !$location.path().match(/bills$/)) {
596 $scope.tab = 'bills';
598 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
599 .search('card', null);
607 // called after each route-specified controller is instantiated.
608 // this doubles as a way to inform the top-level controller that
609 // egStartup.go() has completed, which means we are clear to
610 // fetch the patron, etc.
611 $scope.initTab = function(tab, patron_id) {
612 console.log('init tab ' + tab);
614 $scope.aous = egCore.env.aous;
617 $scope.patron_id = patron_id;
618 return patronSvc.setPrimary($scope.patron_id)
619 .then(function() {return patronSvc.checkAlerts()})
620 .then(redirectToAlertPanel);
625 $scope._show_dob = {};
626 $scope.show_dob = function (val) {
627 if ($scope.patron()) {
628 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
629 return $scope._show_dob[$scope.patron().id()];
631 return !egCore.env.aous['circ.obscure_dob'];
634 $scope.obscure_dob = function() {
635 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
637 $scope.now_show_dob = function() {
638 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
639 $scope.show_dob() : true;
642 $scope.patron = function() { return patronSvc.current }
643 $scope.patron_stats = function() { return patronSvc.patron_stats }
644 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
646 $scope.print_address = function(addr) {
649 template : 'patron_address',
651 patron : egCore.idl.toHash(patronSvc.current),
652 address : egCore.idl.toHash(addr)
657 $scope.toggle_expand_summary = function() {
658 if ($scope.collapsePatronSummary) {
659 $scope.collapsePatronSummary = false;
660 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
662 $scope.collapsePatronSummary = true;
663 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
667 // always expand the patron summary in the search UI, regardless
668 // of stored preference.
669 $scope.collapse_summary = function() {
670 return $scope.tab != 'search' && $scope.collapsePatronSummary;
673 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
674 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
677 .controller('PatronBarcodeSearchCtrl',
678 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
679 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
680 $scope.selectMe = true; // focus text input
681 patronSvc.clearPrimary(); // clear the default user
683 // jump to the patron checkout UI
684 function loadPatron(user_id) {
686 .path('/circ/patron/' + user_id + '/checkout')
687 .search('card', $scope.args.barcode);
690 // create an opt-in=yes response for the loaded user
691 function createOptIn(user_id) {
694 'open-ils.actor.user.org_unit_opt_in.create',
695 egCore.auth.token(), user_id).then(function(resp) {
696 if (evt = egCore.evt.parse(resp)) return alert(evt);
702 $scope.submitBarcode = function(args) {
703 $scope.bcNotFound = null;
704 $scope.optInRestricted = false;
705 if (!args.barcode) return;
707 // blur so next time it's set to true it will re-apply select()
708 $scope.selectMe = false;
715 'open-ils.actor.get_barcodes',
716 egCore.auth.token(), egCore.auth.user().ws_ou(),
717 'actor', args.barcode)
719 .then(function(resp) { // get_barcodes
721 if (evt = egCore.evt.parse(resp)) {
726 if (!resp || !resp[0]) {
727 $scope.bcNotFound = args.barcode;
728 $scope.selectMe = true;
732 // see if an opt-in request is needed
733 user_id = resp[0].id;
734 return egCore.net.request(
736 'open-ils.actor.user.org_unit_opt_in.check',
737 egCore.auth.token(), user_id);
739 }).then(function(optInResp) { // opt_in_check
741 if (evt = egCore.evt.parse(optInResp)) {
746 if (optInResp == 2) {
747 // opt-in disallowed at this location by patron's home library
748 $scope.optInRestricted = true;
749 $scope.selectMe = true;
753 if (optInResp == 1) {
754 // opt-in handled or not needed
755 return loadPatron(user_id);
758 // opt-in needed, show the opt-in dialog
759 egUser.get(user_id, {useFields : []})
761 .then(function(user) { // retrieve user
762 egConfirmDialog.open(
763 egCore.strings.OPT_IN_DIALOG, '',
764 { org : egCore.org.get(user.home_ou()),
766 ok : function() { createOptIn(user.id()) },
767 cancel : function() {}
777 * Manages patron search
779 .controller('PatronSearchCtrl',
780 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
781 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
782 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
783 $filter, egUser, patronSvc , egGridDataProvider , $document) {
785 $scope.initTab('search');
786 $scope.focusMe = true;
787 $scope.searchArgs = {
788 // default to searching globally
789 home_ou : egCore.org.tree()
792 // last used patron search form element
795 $scope.gridControls = {
796 activateItem : function(item) {
797 $location.path('/circ/patron/' + item.id() + '/checkout');
799 selectedItems : function() {return []}
802 // Handle URL-encoded searches
803 if ($location.search().search) {
804 console.log('URL search = ' + $location.search().search);
805 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
807 // why the double-JSON encoded sort?
808 if (patronSvc.urlSearch.search.search_sort) {
809 patronSvc.urlSearch.sort =
810 JSON2js(patronSvc.urlSearch.search.search_sort);
812 patronSvc.urlSearch.sort = [];
814 delete patronSvc.urlSearch.search.search_sort;
818 if (patronSvc.lastSearch) {
819 propagate = patronSvc.lastSearch.search;
820 } else if (patronSvc.urlSearch) {
821 propagate = patronSvc.urlSearch.search;
824 if (egCore.env.pgt) {
825 $scope.profiles = egCore.env.pgt.list;
827 egCore.pcrud.search('pgt', {parent : null},
828 {flesh : -1, flesh_fields : {pgt : ['children']}}
831 egCore.env.absorbTree(tree, 'pgt')
832 $scope.profiles = egCore.env.pgt.list;
838 // populate the search form with our cached / preexisting search info
839 angular.forEach(propagate, function(val, key) {
840 if (key == 'profile')
841 val.value = $scope.profiles.filter(function(p) { p.id() == val.value })[0];
842 if (key == 'home_ou')
843 val.value = egCore.org.get(val.value);
844 $scope.searchArgs[key] = val.value;
848 var provider = egGridDataProvider.instance({});
851 function() {return $scope.gridControls.selectedItems()},
854 patronSvc.setPrimary(null, list[0]);
859 provider.get = function(offset, count) {
860 var deferred = $q.defer();
863 if (patronSvc.urlSearch) {
864 fullSearch = patronSvc.urlSearch;
865 // enusre the urlSearch only runs once.
866 delete patronSvc.urlSearch;
870 var search = compileSearch($scope.searchArgs);
871 if (Object.keys(search) == 0) return $q.when();
873 var home_ou = search.home_ou;
874 delete search.home_ou;
875 var inactive = search.inactive;
876 delete search.inactive;
880 sort : compileSort(),
886 fullSearch.count = count;
887 fullSearch.offset = offset;
889 if (patronSvc.lastSearch) {
890 // search repeated, return the cached results
891 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
892 console.log('patron search returning ' +
893 patronSvc.patrons.length + ' cached results');
895 // notify has to happen after returning the promise
898 angular.forEach(patronSvc.patrons, function(user) {
899 deferred.notify(user);
904 return deferred.promise;
908 patronSvc.lastSearch = fullSearch;
910 if (fullSearch.search.id) {
911 // search by user id performs a direct ID lookup
912 var userId = fullSearch.search.id.value;
915 egUser.get(userId).then(function(user) {
916 patronSvc.localFlesh(user);
917 patronSvc.patrons = [user];
918 deferred.notify(user);
923 return deferred.promise;
926 patronSvc.patrons = [];
929 'open-ils.actor.patron.search.advanced.fleshed',
936 egUser.defaultFleshFields,
940 function() { deferred.resolve() },
943 patronSvc.localFlesh(user); // inline
944 patronSvc.patrons.push(user);
945 deferred.notify(user);
949 return deferred.promise;
952 $scope.patronSearchGridProvider = provider;
954 // determine the tree depth of the profile group
955 $scope.pgt_depth = function(grp) {
957 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
961 $scope.clearForm = function () {
962 $scope.searchArgs={};
963 if (lastFormElement) lastFormElement.focus();
966 $scope.applyShowExtras = function($event, bool) {
968 $scope.showExtras = true;
969 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
971 $scope.showExtras = false;
972 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
974 if (lastFormElement) lastFormElement.focus();
975 $event.preventDefault();
978 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
979 .then(function(val) {$scope.showExtras = val});
981 // map form arguments into search params
982 function compileSearch(args) {
984 angular.forEach(args, function(val, key) {
986 if (key == 'profile' && args.profile) {
987 search.profile = {value : args.profile.id(), group : 0};
988 } else if (key == 'home_ou' && args.home_ou) {
989 search.home_ou = args.home_ou.id(); // passed separately
990 } else if (key == 'inactive') {
991 search.inactive = val;
993 search[key] = {value : val, group : 0};
995 if (key.match(/phone|ident/)) {
996 search[key].group = 2;
998 if (key.match(/street|city|state|post_code/)) {
999 search[key].group = 1;
1000 } else if (key == 'card') {
1001 search[key].group = 3
1009 function compileSort() {
1011 if (!provider.sort.length) {
1014 "first_given_name ASC",
1015 "second_given_name ASC",
1024 if (angular.isObject(sortdef)) {
1025 var name = Object.keys(sortdef)[0];
1026 var dir = sortdef[name];
1027 sort.push(name + ' ' + dir);
1037 $scope.setLastFormElement = function() {
1038 lastFormElement = $document[0].activeElement;
1041 // search form submit action; tells the results grid to
1043 $scope.search = function(args) { // args === $scope.searchArgs
1044 if (args && Object.keys(args).length)
1045 $scope.gridControls.refresh();
1046 if (lastFormElement) lastFormElement.focus();
1049 // TODO: move this into the (forthcoming) grid row activate action
1050 $scope.onPatronDblClick = function($event, user) {
1051 $location.path('/circ/patron/' + user.id() + '/checkout');
1054 if (patronSvc.urlSearch) {
1055 // force the grid to load the url-based search on page load
1064 .controller('PatronMessagesCtrl',
1065 ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
1066 function($scope , $q , $routeParams, egCore , $modal , patronSvc , egCirc) {
1067 $scope.initTab('messages', $routeParams.id);
1068 var usr_id = $routeParams.id;
1070 // setup date filters
1071 var start = new Date(); // now - 1 year
1072 start.setFullYear(start.getFullYear() - 1),
1075 end_date : new Date()
1078 function date_range() {
1079 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1080 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1081 var today = new Date().toISOString().replace(/T.*/,'');
1082 if (end == today) end = 'now';
1083 return [start, end];
1088 var activeGrid = $scope.activeGridControls = {
1089 setSort : function() {
1090 return ['set_date'];
1092 setQuery : function() {
1097 {stop_date : {'>' : 'now'}}
1103 var archiveGrid = $scope.archiveGridControls = {
1104 setSort : function() {
1105 return ['set_date'];
1107 setQuery : function() {
1110 stop_date : {'<=' : 'now'},
1111 set_date : {between : date_range()}
1116 $scope.removePenalty = function(selected) {
1117 // the grid stores flattened penalties. Fetch penalty objects first
1119 var ids = selected.map(function(s){ return s.id });
1120 egCore.pcrud.search('ausp',
1122 {atomic : true, authoritative : true}
1125 ).then(function(penalties) {
1126 return egCore.pcrud.remove(penalties);
1128 // then refresh the grid
1129 }).then(function() {
1130 activeGrid.refresh();
1134 $scope.archivePenalty = function(selected) {
1135 // the grid stores flattened penalties. Fetch penalty objects first
1137 var ids = selected.map(function(s){ return s.id });
1138 egCore.pcrud.search('ausp',
1140 {atomic : true, authoritative : true}
1143 ).then(function(penalties) {
1144 angular.forEach(penalties, function(p){ p.stop_date('now') });
1145 return egCore.pcrud.update(penalties);
1147 // then refresh the grid
1148 }).then(function() {
1149 activeGrid.refresh();
1150 archiveGrid.refresh();
1154 // leverage egEnv for caching
1155 function fetchPenaltyTypes() {
1157 return $q.when(egCore.env.csp.list);
1158 return egCore.pcrud.search(
1159 // id <= 100 are reserved for system use
1160 'csp', {id : {'>': 100}}, {}, {atomic : true})
1161 .then(function(penalties) {
1162 egCore.env.absorbList(penalties, 'csp');
1167 $scope.createPenalty = function() {
1168 egCirc.create_penalty(usr_id).then(function() {
1169 activeGrid.refresh();
1170 // force a refresh of the user, since they may now
1171 // have blocking penalties, etc.
1172 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1176 $scope.editPenalty = function(selected) {
1177 if (selected.length == 0) return;
1179 // grab the penalty from the user object
1180 var penalty = patronSvc.current.standing_penalties().filter(
1181 function(p) {return p.id() == selected[0].id})[0];
1183 egCirc.edit_penalty(penalty).then(function() {
1184 activeGrid.refresh();
1185 // force a refresh of the user, since they may now
1186 // have blocking penalties, etc.
1187 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1194 * Credentials tester
1196 .controller('PatronVerifyCredentialsCtrl',
1197 ['$scope','$routeParams','$location','egCore',
1198 function($scope, $routeParams , $location , egCore) {
1199 $scope.verified = null;
1200 $scope.focusMe = true;
1202 // called with a patron, pre-populate the form args
1203 $scope.initTab('other', $routeParams.id).then(
1205 if ($routeParams.id && $scope.patron()) {
1206 $scope.prepop = true;
1207 $scope.username = $scope.patron().usrname();
1208 $scope.barcode = $scope.patron().card().barcode();
1210 $scope.username = '';
1211 $scope.barcode = '';
1212 $scope.password = '';
1217 // verify login credentials
1218 $scope.verify = function() {
1219 $scope.verified = null;
1220 $scope.notFound = false;
1224 'open-ils.actor.verify_user_password',
1225 egCore.auth.token(), $scope.barcode,
1226 $scope.username, hex_md5($scope.password || '')
1228 ).then(function(resp) {
1229 $scope.focusMe = true;
1230 if (evt = egCore.evt.parse(resp)) {
1232 } else if (resp == 1) {
1233 $scope.verified = true;
1235 $scope.verified = false;
1240 // load the main patron UI for the provided username or barcode
1241 $scope.load = function($event) {
1242 $scope.notFound = false;
1243 $scope.verified = null;
1247 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1248 egCore.auth.token(), $scope.barcode, $scope.username
1250 ).then(function(resp) {
1253 $location.path('/circ/patron/' + resp + '/checkout');
1257 // something went wrong...
1258 $scope.focusMe = true;
1259 if (evt = egCore.evt.parse(resp)) {
1260 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1261 $scope.notFound = true;
1270 // load() button sits within the verify form.
1271 // avoid submitting the verify() form action on load()
1272 $event.preventDefault();
1276 .controller('PatronAlertsCtrl',
1277 ['$scope','$routeParams','$location','egCore','patronSvc',
1278 function($scope, $routeParams , $location , egCore , patronSvc) {
1280 $scope.initTab('other', $routeParams.id)
1282 $scope.patronExpired = patronSvc.patronExpired;
1283 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1284 $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1285 $scope.invalidAddresses = patronSvc.invalidAddresses;
1290 .controller('PatronNotesCtrl',
1291 ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1292 function($scope, $routeParams , $location , egCore , patronSvc , $modal) {
1293 $scope.initTab('other', $routeParams.id);
1294 var usr_id = $routeParams.id;
1297 function refreshPage() {
1299 egCore.pcrud.search('aun',
1301 {flesh : 1, flesh_fields : {aun : ['creator']}},
1302 {authoritative : true})
1303 .then(null, null, function(note) {
1304 $scope.notes.push(note);
1308 // open the new-note dialog and create the note
1309 $scope.newNote = function() {
1311 templateUrl: './circ/patron/t_new_note_dialog',
1313 ['$scope', '$modalInstance',
1314 function($scope, $modalInstance) {
1315 $scope.focusNote = true;
1317 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1318 $scope.cancel = function () { $modalInstance.dismiss() }
1322 if (!args.value) return;
1323 var note = new egCore.idl.aun();
1325 note.title(args.title);
1326 note.value(args.value);
1327 note.pub(args.pub ? 't' : 'f');
1328 note.creator(egCore.auth.user().id());
1329 egCore.pcrud.create(note).then(function() {refreshPage()});
1334 // delete the selected note
1335 $scope.deleteNote = function(note) {
1336 egCore.pcrud.remove(note).then(function() {refreshPage()});
1339 // print the selected note
1340 $scope.printNote = function(note) {
1341 var hash = egCore.idl.toHash(note);
1342 hash.usr = egCore.idl.toHash($scope.patron());
1343 egCore.print.print({
1344 context : 'default',
1345 template : 'patron_note',
1346 scope : {note : hash}
1350 // perform the initial note fetch
1354 .controller('PatronGroupCtrl',
1355 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1356 'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1357 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1358 patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1360 var usr_id = $routeParams.id;
1362 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1364 var grid = $scope.gridControls = {
1365 activateItem : function(item) {
1366 $location.path('/circ/patron/' + item.id + '/checkout');
1368 itemRetrieved : function(item) {
1370 if (item.id == patronSvc.current.id()) {
1371 item.stats = patronSvc.patron_stats;
1374 // flesh stats for other group members
1375 patronSvc.getUserStats(item.id).then(function(stats) {
1377 $scope.totals.total_out += stats.checkouts.total_out;
1378 $scope.totals.overdue += stats.checkouts.overdue;
1382 setSort : function() {
1383 return ['create_date'];
1387 $scope.initTab('other', $routeParams.id)
1388 .then(function(redirect) {
1389 // if we are redirecting to the alerts page, avoid updating the
1391 if (redirect) return;
1392 // let initTab() fetch the user first so we can know the usrgroup
1395 usrgroup : patronSvc.current.usrgroup(),
1398 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1401 $scope.removeFromGroup = function(selected) {
1403 angular.forEach(selected, function(user) {
1404 console.debug('removing user ' + user.id + ' from group');
1409 'open-ils.actor.usergroup.new',
1410 egCore.auth.token(), user.id, true
1415 $q.all(promises).then(function() {grid.refresh()});
1418 function addUserToGroup(user) {
1419 user.usrgroup(patronSvc.current.usrgroup());
1420 user.ischanged(true);
1423 'open-ils.actor.patron.update',
1424 egCore.auth.token(), user
1426 ).then(function() {grid.refresh()});
1429 // fetch each user ("selected" has flattened users)
1430 // update the usrgroup, then update the user object
1431 // After all updates are complete, refresh the grid.
1432 function moveUsersToGroup(target_user, selected) {
1435 angular.forEach(selected, function(user) {
1437 egCore.pcrud.retrieve('au', user.id)
1439 u.usrgroup(target_user.usrgroup());
1441 return egCore.net.request(
1443 'open-ils.actor.patron.update',
1444 egCore.auth.token(), u
1450 $q.all(promises).then(function() {grid.refresh()});
1453 function showMoveToGroupConfirm(barcode, selected, outbound) {
1456 egCore.pcrud.search('ac', {barcode : barcode})
1458 // fetch the fleshed user
1459 .then(function(card) {
1461 if (!card) return; // TODO: warn user
1463 egCore.pcrud.retrieve('au', card.usr())
1464 .then(function(user) {
1467 templateUrl: './circ/patron/t_move_to_group_dialog',
1469 '$scope','$modalInstance',
1470 function($scope , $modalInstance) {
1472 $scope.selected = selected;
1473 $scope.outbound = outbound;
1475 function(count) { $modalInstance.close() }
1477 function () { $modalInstance.dismiss() }
1480 }).result.then(function() {
1482 moveUsersToGroup(user, selected);
1484 addUserToGroup(user);
1491 // selected == move selected patrons to another patron's group
1492 // !selected == patron from a different group moves into our group
1493 function moveToGroup(selected, outbound) {
1494 egPromptDialog.open(
1495 egCore.strings.GROUP_ADD_USER, '',
1496 {ok : function(value) {
1498 showMoveToGroupConfirm(value, selected, outbound);
1503 $scope.moveToGroup = function() { moveToGroup([], false) };
1504 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1506 $scope.cloneUser = function(selected) {
1507 if (!selected.length) return;
1508 var url = $location.absUrl().replace(
1510 '/patron/register/clone/' + selected[0].id);
1511 $window.open(url, '_blank').focus();
1514 $scope.retrieveSelected = function(selected) {
1515 if (!selected.length) return;
1516 angular.forEach(selected, function(usr) {
1517 $timeout(function() {
1518 var url = $location.absUrl().replace(
1520 '/patron/' + usr.id + '/checkout');
1521 $window.open(url, '_blank')
1528 .controller('PatronStatCatsCtrl',
1529 ['$scope','$routeParams','$q','egCore','patronSvc',
1530 function($scope, $routeParams , $q , egCore , patronSvc) {
1531 $scope.initTab('other', $routeParams.id)
1532 .then(function(redirect) {
1533 // Entries for org-visible stat cats are fleshed. Any others
1534 // have to be fleshed within.
1537 angular.forEach(patronSvc.current.stat_cat_entries(),
1539 if (!angular.isObject(entry.stat_cat())) {
1540 to_flesh[entry.stat_cat()] = entry;
1545 if (!Object.keys(to_flesh).length) return;
1547 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1548 .then(null, null, function(cat) { // stream
1549 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1550 to_flesh[cat.id()].stat_cat(cat);
1555 .controller('PatronFetchLastCtrl',
1556 ['$scope','$location','egCore',
1557 function($scope , $location , egCore) {
1559 var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1560 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1562 $scope.no_last = true;
1565 .controller('PatronTriggeredEventsCtrl',
1566 ['$scope','$routeParams','$location','egCore','patronSvc',
1567 function($scope, $routeParams, $location , egCore , patronSvc) {
1568 $scope.initTab('other', $routeParams.id);
1570 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1571 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1573 $scope.triggered_events_url = url;
1577 .controller('PatronPermsCtrl',
1578 ['$scope','$routeParams','$window','$location','egCore',
1579 function($scope , $routeParams , $window , $location , egCore) {
1580 $scope.initTab('other', $routeParams.id);
1582 var url = $location.absUrl().replace(
1583 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1585 url += '?usr=' + encodeURIComponent($routeParams.id);
1587 // user_edit does not load the session via cookie. It uses URL
1588 // params or xulG instead. Pass via xulG.
1590 ses : egCore.auth.token(),
1591 on_patron_save : function() {
1592 $scope.funcs.reload();
1596 $scope.user_perms_url = url;