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([
26 'ui.circ.show_billing_tab_on_bills',
27 'circ.patron_expires_soon_warning',
28 'ui.circ.items_out.lost',
29 'ui.circ.items_out.longoverdue',
30 'ui.circ.items_out.claimsreturned'
31 ]).then(function(settings) {
32 // local settings are cached within egOrg. Caching them
33 // again in egEnv just simplifies the syntax for access.
34 egCore.env.aous = settings;
38 egCore.env.loadClasses.push('aous');
40 // app-globally modify the default flesh fields for
41 // fleshed user retrieval.
42 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
43 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
52 return egCore.startup.go().then(function() {
54 // This call requires orgs to be loaded, because it
55 // calls egCore.org.ancestors(), so call it after startup
56 return egCore.pcrud.search('actsc',
57 {owner : egCore.org.ancestors(
58 egCore.auth.user().ws_ou(), true)},
60 ).then(function(cats) {
61 egCore.env.absorbList(cats, 'actsc');
66 $routeProvider.when('/circ/patron/search', {
67 templateUrl: './circ/patron/t_search',
68 controller: 'PatronSearchCtrl',
72 $routeProvider.when('/circ/patron/bcsearch', {
73 templateUrl: './circ/patron/t_bcsearch',
74 controller: 'PatronBarcodeSearchCtrl',
78 $routeProvider.when('/circ/patron/credentials', {
79 templateUrl: './circ/patron/t_credentials',
80 controller: 'PatronVerifyCredentialsCtrl',
84 $routeProvider.when('/circ/patron/last', {
85 templateUrl: './circ/patron/t_last_patron',
86 controller: 'PatronFetchLastCtrl',
90 // the following require a patron ID
92 $routeProvider.when('/circ/patron/:id/alerts', {
93 templateUrl: './circ/patron/t_alerts',
94 controller: 'PatronAlertsCtrl',
98 $routeProvider.when('/circ/patron/:id/checkout', {
99 templateUrl: './circ/patron/t_checkout',
100 controller: 'PatronCheckoutCtrl',
104 $routeProvider.when('/circ/patron/:id/items_out', {
105 templateUrl: './circ/patron/t_items_out',
106 controller: 'PatronItemsOutCtrl',
110 $routeProvider.when('/circ/patron/:id/holds', {
111 templateUrl: './circ/patron/t_holds',
112 controller: 'PatronHoldsCtrl',
116 $routeProvider.when('/circ/patron/:id/holds/create', {
117 templateUrl: './circ/patron/t_holds_create',
118 controller: 'PatronHoldsCreateCtrl',
122 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
123 templateUrl: './circ/patron/t_holds',
124 controller: 'PatronHoldsCtrl',
128 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
129 templateUrl: './circ/patron/t_hold_details',
130 controller: 'PatronHoldDetailsCtrl',
134 $routeProvider.when('/circ/patron/:id/bills', {
135 templateUrl: './circ/patron/t_bills',
136 controller: 'PatronBillsCtrl',
140 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
141 templateUrl: './circ/patron/t_xact_details',
142 controller: 'XactDetailsCtrl',
146 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
147 templateUrl: './circ/patron/t_bill_history',
148 controller: 'BillHistoryCtrl',
152 $routeProvider.when('/circ/patron/:id/messages', {
153 templateUrl: './circ/patron/t_messages',
154 controller: 'PatronMessagesCtrl',
158 $routeProvider.when('/circ/patron/:id/edit', {
159 templateUrl: './circ/patron/t_edit',
160 controller: 'PatronEditCtrl',
164 $routeProvider.when('/circ/patron/:id/credentials', {
165 templateUrl: './circ/patron/t_credentials',
166 controller: 'PatronVerifyCredentialsCtrl',
170 $routeProvider.when('/circ/patron/:id/notes', {
171 templateUrl: './circ/patron/t_notes',
172 controller: 'PatronNotesCtrl',
176 $routeProvider.when('/circ/patron/:id/triggered_events', {
177 templateUrl: './circ/patron/t_triggered_events',
178 controller: 'PatronTriggeredEventsCtrl',
182 $routeProvider.when('/circ/patron/:id/edit_perms', {
183 templateUrl: './circ/patron/t_edit_perms',
184 controller: 'PatronPermsCtrl',
188 $routeProvider.when('/circ/patron/:id/group', {
189 templateUrl: './circ/patron/t_group',
190 controller: 'PatronGroupCtrl',
194 $routeProvider.when('/circ/patron/:id/stat_cats', {
195 templateUrl: './circ/patron/t_stat_cats',
196 controller: 'PatronStatCatsCtrl',
200 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
206 .factory('patronSvc',
207 ['$q','$timeout','$location','egCore','egUser','$locale',
208 function($q , $timeout , $location , egCore, egUser , $locale) {
211 // cached patron search results
214 // currently selected patron object
217 // patron circ stats (overdues, fines, holds)
220 // event types manually overridden, which should always be
221 // overridden for checkouts to this patron for this instance of
223 checkout_overrides : {},
226 // when we change the default patron, we need to clear out any
227 // data collected on that patron
228 service.resetPatronLists = function() {
229 service.checkouts = [];
230 service.items_out = []
231 service.items_out_ids = [];
233 service.hold_ids = [];
234 service.checkout_overrides = {};
235 service.patron_stats = null;
236 service.hasAlerts = false;
237 service.alertsShown = false;
238 service.patronExpired = false;
239 service.patronExpiresSoon = false;
240 service.retrievedWithInactive = false;
241 service.invalidAddresses = false;
243 service.resetPatronLists(); // initialize
245 // shortcut to force-reload the current primary
246 service.refreshPrimary = function() {
247 if (!service.current) return $q.when();
248 return service.setPrimary(service.current.id(), null, true);
251 // clear the currently focused user
252 service.clearPrimary = function() {
253 // reset with no patron
254 service.resetPatronLists();
255 service.current = null;
256 service.patron_stats = null;
260 // sets the primary display user, fetching data as necessary.
261 service.setPrimary = function(id, user, force) {
262 var user_id = id ? id : (user ? user.id() : null);
264 console.debug('setting primary user to: ' + user_id);
266 if (!user_id) return $q.reject();
268 // when loading a new patron, update the last patron setting
269 if (!service.current || service.current.id() != user_id)
270 egCore.hatch.setLocalItem('eg.circ.last_patron', user_id);
272 // avoid running multiple retrievals for the same patron, which
273 // can happen during dbl-click by maintaining a single running
274 // data retrieval promise
275 if (service.primaryUserPromise) {
276 if (service.primaryUserId == user_id) {
277 return service.primaryUserPromise.promise;
279 service.primaryUserPromise = null;
283 service.primaryUserPromise = $q.defer();
284 service.primaryUserId = user_id;
286 service.getPrimary(id, user, force)
288 var p = service.primaryUserPromise;
289 service.primaryUserId = null;
290 // clear before resolution just to be safe.
291 service.primaryUserPromise = null;
295 return service.primaryUserPromise.promise;
298 service.getPrimary = function(id, user, force) {
301 if (!force && service.current &&
302 service.current.id() == user.id()) {
303 if (service.patron_stats) {
306 return service.fetchUserStats();
310 service.resetPatronLists();
311 service.current = user;
312 service.localFlesh(user);
313 return service.fetchUserStats();
316 if (!force && service.current && service.current.id() == id) {
317 if (service.patron_stats) {
320 return service.fetchUserStats();
324 service.resetPatronLists();
326 return egUser.get(id).then(
328 service.current = user;
329 service.localFlesh(user);
330 return service.fetchUserStats();
334 "unable to fetch user "+id+': '+js2JSON(err))
339 // fetching a null user clears the primary user.
340 // NOTE: this should probably reject() and log an error,
341 // but calling clear for backwards compat for now.
342 return service.clearPrimary();
346 // flesh some additional user fields locally
347 service.localFlesh = function(user) {
348 if (!angular.isObject(typeof user.home_ou()))
349 user.home_ou(egCore.org.get(user.home_ou()));
352 user.standing_penalties(),
354 if (!angular.isObject(penalty.org_unit()))
355 penalty.org_unit(egCore.org.get(penalty.org_unit()));
359 // stat_cat_entries == stat_cat_entry_user_map
360 angular.forEach(user.stat_cat_entries(), function(map) {
361 if (angular.isObject(map.stat_cat())) return;
362 // At page load, we only retrieve org-visible stat cats.
363 // For the common case, ignore entries for remote stat cats.
364 var cat = egCore.env.actsc.map[map.stat_cat()];
367 cat.owner(egCore.org.get(cat.owner()));
372 // resolves to true if the patron account has expired or will
373 // expire soon, based on YAOUS circ.patron_expires_soon_warning
374 // note: returning a promise is no longer strictly necessary
375 // (no more async activity) if the calling function is changed too.
376 service.testExpire = function() {
378 var expire = Date.parse(service.current.expire_date());
379 if (expire < new Date()) {
380 return $q.when(service.patronExpired = true);
383 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
385 var preExpire = new Date();
386 preExpire.setDate(preExpire.getDate() + Number(soon));
387 if (expire < preExpire)
388 return $q.when(service.patronExpiresSoon = true);
391 return $q.when(false);
394 // resolves to true if the patron account has any invalid addresses.
395 service.testInvalidAddrs = function() {
397 if (service.invalidAddresses)
398 return $q.when(true);
403 service.current.addresses(),
404 function(addr) { if (addr.valid() == 'f') fail = true }
407 return $q.when(fail);
410 // resolves to true if there is any aspect of the patron account
411 // which should produce a message in the alerts panel
412 service.checkAlerts = function() {
414 if (service.hasAlerts) // already checked
415 return $q.when(true);
417 var deferred = $q.defer();
418 var p = service.current;
420 if (service.alert_penalties.length ||
424 service.patron_stats.holds.ready) {
426 service.hasAlerts = true;
429 // see if the user was retrieved with an inactive card
430 if (bc = $location.search().card) {
431 var card = p.cards().filter(
432 function(c) { return c.barcode() == bc })[0];
434 if (card && card.active() == 'f') {
435 service.hasAlerts = true;
436 service.retrievedWithInactive = true;
440 // regardless of whether we know of alerts, we still need
441 // to test/fetch the expire data for display
442 service.testExpire().then(function(bool) {
443 if (bool) service.hasAlerts = true;
444 deferred.resolve(service.hasAlerts);
447 service.testInvalidAddrs().then(function(bool) {
448 if (bool) service.invalidAddresses = true;
449 deferred.resolve(service.invalidAddresses);
452 return deferred.promise;
455 service.fetchGroupFines = function() {
456 return egCore.net.request(
458 'open-ils.actor.usergroup.members.balance_owed',
459 egCore.auth.token(), service.current.usrgroup()
460 ).then(function(list) {
462 angular.forEach(list, function(u) {
463 total += 100 * Number(u.balance_owed)
465 service.patron_stats.fines.group_balance_owed = total / 100;
469 service.getUserStats = function(id) {
470 return egCore.net.request(
472 'open-ils.actor.user.opac.vital_stats.authoritative',
473 egCore.auth.token(), id
476 // force numeric to ensure correct boolean handling in templates
477 stats.fines.balance_owed = Number(stats.fines.balance_owed);
478 stats.checkouts.overdue = Number(stats.checkouts.overdue);
479 stats.checkouts.claims_returned =
480 Number(stats.checkouts.claims_returned);
481 stats.checkouts.lost = Number(stats.checkouts.lost);
482 stats.checkouts.out = Number(stats.checkouts.out);
483 stats.checkouts.total_out =
484 stats.checkouts.out + stats.checkouts.overdue;
491 // grab additional circ info
492 service.fetchUserStats = function() {
493 return service.getUserStats(service.current.id())
494 .then(function(stats) {
495 service.patron_stats = stats
496 service.alert_penalties = service.current.standing_penalties()
497 .filter(function(pen) {
498 return pen.standing_penalty().staff_alert() == 't'
501 service.summary_stat_cats = [];
502 angular.forEach(service.current.stat_cat_entries(),
504 if (angular.isObject(map.stat_cat()) &&
505 map.stat_cat().usr_summary() == 't') {
506 service.summary_stat_cats.push(map);
511 return service.fetchGroupFines();
515 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
516 // which is the Angular default.
517 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
518 // FIXME: This change needs to be moved into a project-wide collection
519 // of locale overrides.
520 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
521 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
527 * Manages tabbed patron view.
528 * This is the parent scope of all patron tab scopes.
531 .controller('PatronCtrl',
532 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
533 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
535 // returns true if a redirect occurs
536 function redirectToAlertPanel() {
538 $scope.alert_penalties =
539 function() {return patronSvc.alert_penalties}
541 if (patronSvc.alertsShown) return false;
542 patronSvc.alertsShown = true;
544 // if the patron has any unshown alerts, show them now
545 if (patronSvc.hasAlerts &&
546 !$location.path().match(/alerts$/)) {
549 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
550 .search('card', null);
554 // no alert required. If the patron has fines and the show-bills
555 // OUS is applied, direct to the bills page.
556 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
557 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
558 && !$location.path().match(/bills$/)) {
561 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
562 .search('card', null);
570 // called after each route-specified controller is instantiated.
571 // this doubles as a way to inform the top-level controller that
572 // egStartup.go() has completed, which means we are clear to
573 // fetch the patron, etc.
574 $scope.initTab = function(tab, patron_id) {
575 console.log('init tab ' + tab);
577 $scope.aous = egCore.env.aous;
580 $scope.patron_id = patron_id;
581 return patronSvc.setPrimary($scope.patron_id)
582 .then(function() {return patronSvc.checkAlerts()})
583 .then(redirectToAlertPanel);
588 $scope.patron = function() { return patronSvc.current }
589 $scope.patron_stats = function() { return patronSvc.patron_stats }
590 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
592 $scope.print_address = function(addr) {
595 template : 'patron_address',
597 patron : egCore.idl.toHash(patronSvc.current),
598 address : egCore.idl.toHash(addr)
603 $scope.toggle_expand_summary = function() {
604 if ($scope.collapsePatronSummary) {
605 $scope.collapsePatronSummary = false;
606 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
608 $scope.collapsePatronSummary = true;
609 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
613 // always expand the patron summary in the search UI, regardless
614 // of stored preference.
615 $scope.collapse_summary = function() {
616 return $scope.tab != 'search' && $scope.collapsePatronSummary;
619 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
620 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
623 .controller('PatronBarcodeSearchCtrl',
624 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
625 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
626 $scope.selectMe = true; // focus text input
627 patronSvc.clearPrimary(); // clear the default user
629 // jump to the patron checkout UI
630 function loadPatron(user_id) {
632 .path('/circ/patron/' + user_id + '/checkout')
633 .search('card', $scope.args.barcode);
636 // create an opt-in=yes response for the loaded user
637 function createOptIn(user_id) {
640 'open-ils.actor.user.org_unit_opt_in.create',
641 egCore.auth.token(), user_id).then(function(resp) {
642 if (evt = egCore.evt.parse(resp)) return alert(evt);
648 $scope.submitBarcode = function(args) {
649 $scope.bcNotFound = null;
650 if (!args.barcode) return;
652 // blur so next time it's set to true it will re-apply select()
653 $scope.selectMe = false;
660 'open-ils.actor.get_barcodes',
661 egCore.auth.token(), egCore.auth.user().ws_ou(),
662 'actor', args.barcode)
664 .then(function(resp) { // get_barcodes
666 if (evt = egCore.evt.parse(resp)) {
671 if (!resp || !resp[0]) {
672 $scope.bcNotFound = args.barcode;
673 $scope.selectMe = true;
677 // see if an opt-in request is needed
678 user_id = resp[0].id;
679 return egCore.net.request(
681 'open-ils.actor.user.org_unit_opt_in.check',
682 egCore.auth.token(), user_id);
684 }).then(function(optInResp) { // opt_in_check
686 if (evt = egCore.evt.parse(optInResp)) {
691 if (optInResp == 1) {
692 // opt-in handled or not needed
693 return loadPatron(user_id);
696 // opt-in needed, show the opt-in dialog
697 egUser.get(user_id, {useFields : []})
699 .then(function(user) { // retrieve user
700 egConfirmDialog.open(
701 egCore.strings.OPT_IN_DIALOG, '',
702 { org : egCore.org.get(user.home_ou()),
704 ok : function() { createOptIn(user.id()) },
705 cancel : function() {}
715 * Manages patron search
717 .controller('PatronSearchCtrl',
718 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
719 '$filter','egUser', 'patronSvc','egGridDataProvider',
720 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
721 $filter, egUser, patronSvc , egGridDataProvider) {
723 $scope.initTab('search');
724 $scope.focusMe = true;
725 $scope.searchArgs = {
726 // default to searching globally
727 home_ou : egCore.org.tree()
730 $scope.gridControls = {
731 activateItem : function(item) {
732 $location.path('/circ/patron/' + item.id() + '/checkout');
734 selectedItems : function() {return []}
737 // Handle URL-encoded searches
738 if ($location.search().search) {
739 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
741 // why the double-JSON encoded sort?
742 patronSvc.urlSearch.sort =
743 JSON2js(patronSvc.urlSearch.search.search_sort);
744 delete patronSvc.urlSearch.search.search_sort;
748 if (patronSvc.lastSearch) {
749 propagate = patronSvc.lastSearch.search;
750 } else if (patronSvc.urlSearch) {
751 propagate = patronSvc.urlSearch.search;
755 // populate the search form with our cached / preexisting search info
756 angular.forEach(propagate, function(val, key) {
757 $scope.searchArgs[key] = val.value;
761 var provider = egGridDataProvider.instance({});
764 function() {return $scope.gridControls.selectedItems()},
767 patronSvc.setPrimary(null, list[0]);
772 provider.get = function(offset, count) {
773 var deferred = $q.defer();
776 if (patronSvc.urlSearch) {
777 fullSearch = patronSvc.urlSearch;
778 // enusre the urlSearch only runs once.
779 delete patronSvc.urlSearch;
783 var search = compileSearch($scope.searchArgs);
784 if (Object.keys(search) == 0) return $q.when();
786 var home_ou = search.home_ou;
787 delete search.home_ou;
788 var inactive = search.inactive;
789 delete search.inactive;
793 sort : compileSort(),
799 fullSearch.count = count;
800 fullSearch.offset = offset;
802 if (patronSvc.lastSearch) {
803 // search repeated, return the cached results
804 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
805 console.log('patron search returning ' +
806 patronSvc.patrons.length + ' cached results');
808 // notify has to happen after returning the promise
811 angular.forEach(patronSvc.patrons, function(user) {
812 deferred.notify(user);
817 return deferred.promise;
821 patronSvc.lastSearch = fullSearch;
823 if (fullSearch.search.id) {
824 // search by user id performs a direct ID lookup
825 var userId = fullSearch.search.id.value;
828 egUser.get(userId).then(function(user) {
829 patronSvc.localFlesh(user);
830 patronSvc.patrons = [user];
831 deferred.notify(user);
836 return deferred.promise;
839 patronSvc.patrons = [];
842 'open-ils.actor.patron.search.advanced.fleshed',
849 egUser.defaultFleshFields,
853 function() { deferred.resolve() },
856 patronSvc.localFlesh(user); // inline
857 patronSvc.patrons.push(user);
858 deferred.notify(user);
862 return deferred.promise;
865 $scope.patronSearchGridProvider = provider;
867 if (egCore.env.pgt) {
868 $scope.profiles = egCore.env.pgt.list;
870 egCore.pcrud.search('pgt', {parent : null},
871 {flesh : -1, flesh_fields : {pgt : ['children']}}
874 egCore.env.absorbTree(tree, 'pgt')
875 $scope.profiles = egCore.env.pgt.list;
880 // determine the tree depth of the profile group
881 $scope.pgt_depth = function(grp) {
883 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
887 $scope.applyShowExtras = function($event, bool) {
889 $scope.showExtras = true;
890 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
892 $scope.showExtras = false;
893 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
895 $event.preventDefault();
898 egCore.hatch.getItem('eg.prefs.circ.patron.search.showExtras')
899 .then(function(val) {$scope.showExtras = val});
901 // map form arguments into search params
902 function compileSearch(args) {
904 angular.forEach(args, function(val, key) {
906 if (key == 'profile' && args.profile) {
907 search.profile = {value : args.profile.id(), group : 0};
908 } else if (key == 'home_ou' && args.home_ou) {
909 search.home_ou = args.home_ou.id(); // passed separately
910 } else if (key == 'inactive') {
911 search.inactive = val;
913 search[key] = {value : val, group : 0};
915 if (key.match(/phone|ident/)) {
916 search[key].group = 2;
918 if (key.match(/street|city|state|post_code/)) {
919 search[key].group = 1;
920 } else if (key == 'card') {
921 search[key].group = 3
929 function compileSort() {
931 if (!provider.sort.length) {
934 "first_given_name ASC",
935 "second_given_name ASC",
944 if (angular.isObject(sortdef)) {
945 var name = Object.keys(sortdef)[0];
946 var dir = sortdef[name];
947 sort.push(name + ' ' + dir);
957 // search form submit action; tells the results grid to
959 $scope.search = function(args) { // args === $scope.searchArgs
960 if (args && Object.keys(args).length)
961 $scope.gridControls.refresh();
964 // TODO: move this into the (forthcoming) grid row activate action
965 $scope.onPatronDblClick = function($event, user) {
966 $location.path('/circ/patron/' + user.id() + '/checkout');
969 if (patronSvc.urlSearch) {
970 // force the grid to load the url-based search on page load
979 .controller('PatronMessagesCtrl',
980 ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
981 function($scope , $q , $routeParams, egCore , $modal , patronSvc , egCirc) {
982 $scope.initTab('messages', $routeParams.id);
983 var usr_id = $routeParams.id;
985 // setup date filters
986 var start = new Date(); // now - 1 year
987 start.setFullYear(start.getFullYear() - 1),
990 end_date : new Date()
993 function date_range() {
994 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
995 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
996 var today = new Date().toISOString().replace(/T.*/,'');
997 if (end == today) end = 'now';
1003 var activeGrid = $scope.activeGridControls = {
1004 setSort : function() {
1005 return ['set_date'];
1007 setQuery : function() {
1012 {stop_date : {'>' : 'now'}}
1018 var archiveGrid = $scope.archiveGridControls = {
1019 setSort : function() {
1020 return ['set_date'];
1022 setQuery : function() {
1025 stop_date : {'<=' : 'now'},
1026 set_date : {between : date_range()}
1031 $scope.removePenalty = function(selected) {
1032 // the grid stores flattened penalties. Fetch penalty objects first
1034 var ids = selected.map(function(s){ return s.id });
1035 egCore.pcrud.search('ausp',
1037 {atomic : true, authoritative : true}
1040 ).then(function(penalties) {
1041 return egCore.pcrud.remove(penalties);
1043 // then refresh the grid
1044 }).then(function() {
1045 activeGrid.refresh();
1049 $scope.archivePenalty = function(selected) {
1050 // the grid stores flattened penalties. Fetch penalty objects first
1052 var ids = selected.map(function(s){ return s.id });
1053 egCore.pcrud.search('ausp',
1055 {atomic : true, authoritative : true}
1058 ).then(function(penalties) {
1059 angular.forEach(penalties, function(p){ p.stop_date('now') });
1060 return egCore.pcrud.update(penalties);
1062 // then refresh the grid
1063 }).then(function() {
1064 activeGrid.refresh();
1065 archiveGrid.refresh();
1069 // leverage egEnv for caching
1070 function fetchPenaltyTypes() {
1072 return $q.when(egCore.env.csp.list);
1073 return egCore.pcrud.search(
1074 // id <= 100 are reserved for system use
1075 'csp', {id : {'>': 100}}, {}, {atomic : true})
1076 .then(function(penalties) {
1077 egCore.env.absorbList(penalties, 'csp');
1082 $scope.createPenalty = function() {
1083 egCirc.create_penalty(usr_id).then(function() {
1084 activeGrid.refresh();
1085 // force a refresh of the user, since they may now
1086 // have blocking penalties, etc.
1087 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1091 $scope.editPenalty = function(selected) {
1092 if (selected.length == 0) return;
1094 // grab the penalty from the user object
1095 var penalty = patronSvc.current.standing_penalties().filter(
1096 function(p) {return p.id() == selected[0].id})[0];
1098 egCirc.edit_penalty(penalty).then(function() {
1099 activeGrid.refresh();
1100 // force a refresh of the user, since they may now
1101 // have blocking penalties, etc.
1102 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1109 * Link to patron edit UI
1111 .controller('PatronEditCtrl',
1112 ['$scope','$routeParams','$location','egCore','patronSvc',
1113 function($scope, $routeParams, $location , egCore , patronSvc) {
1114 $scope.initTab('edit', $routeParams.id);
1116 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/register');
1117 url += '?usr=' + encodeURIComponent($routeParams.id);
1120 on_save : function() {
1121 patronSvc.refreshPrimary();
1125 $scope.patron_edit_url = url;
1129 * Credentials tester
1131 .controller('PatronVerifyCredentialsCtrl',
1132 ['$scope','$routeParams','$location','egCore',
1133 function($scope, $routeParams , $location , egCore) {
1134 $scope.verified = null;
1135 $scope.focusMe = true;
1137 // called with a patron, pre-populate the form args
1138 $scope.initTab('other', $routeParams.id).then(
1140 if ($scope.patron()) {
1141 $scope.prepop = true;
1142 $scope.username = $scope.patron().usrname();
1143 $scope.barcode = $scope.patron().card().barcode();
1148 // verify login credentials
1149 $scope.verify = function() {
1150 $scope.verified = null;
1151 $scope.notFound = false;
1155 'open-ils.actor.verify_user_password',
1156 egCore.auth.token(), $scope.barcode,
1157 $scope.username, hex_md5($scope.password || '')
1159 ).then(function(resp) {
1160 $scope.focusMe = true;
1161 if (evt = egCore.evt.parse(resp)) {
1163 } else if (resp == 1) {
1164 $scope.verified = true;
1166 $scope.verified = false;
1171 // load the main patron UI for the provided username or barcode
1172 $scope.load = function($event) {
1173 $scope.notFound = false;
1174 $scope.verified = null;
1178 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1179 egCore.auth.token(), $scope.barcode, $scope.username
1181 ).then(function(resp) {
1184 $location.path('/circ/patron/' + resp + '/checkout');
1188 // something went wrong...
1189 $scope.focusMe = true;
1190 if (evt = egCore.evt.parse(resp)) {
1191 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1192 $scope.notFound = true;
1201 // load() button sits within the verify form.
1202 // avoid submitting the verify() form action on load()
1203 $event.preventDefault();
1207 .controller('PatronAlertsCtrl',
1208 ['$scope','$routeParams','$location','egCore','patronSvc',
1209 function($scope, $routeParams , $location , egCore , patronSvc) {
1211 $scope.initTab('other', $routeParams.id)
1213 $scope.patronExpired = patronSvc.patronExpired;
1214 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1215 $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1216 $scope.invalidAddresses = patronSvc.invalidAddresses;
1221 .controller('PatronNotesCtrl',
1222 ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1223 function($scope, $routeParams , $location , egCore , patronSvc , $modal) {
1224 $scope.initTab('other', $routeParams.id);
1225 var usr_id = $routeParams.id;
1228 function refreshPage() {
1230 egCore.pcrud.search('aun',
1232 {flesh : 1, flesh_fields : {aun : ['creator']}},
1233 {authoritative : true})
1234 .then(null, null, function(note) {
1235 $scope.notes.push(note);
1239 // open the new-note dialog and create the note
1240 $scope.newNote = function() {
1242 templateUrl: './circ/patron/t_new_note_dialog',
1244 ['$scope', '$modalInstance',
1245 function($scope, $modalInstance) {
1246 $scope.focusNote = true;
1248 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1249 $scope.cancel = function () { $modalInstance.dismiss() }
1253 if (!args.value) return;
1254 var note = new egCore.idl.aun();
1256 note.title(args.title);
1257 note.value(args.value);
1258 note.pub(args.pub ? 't' : 'f');
1259 note.creator(egCore.auth.user().id());
1260 egCore.pcrud.create(note).then(function() {refreshPage()});
1265 // delete the selected note
1266 $scope.deleteNote = function(note) {
1267 egCore.pcrud.remove(note).then(function() {refreshPage()});
1270 // print the selected note
1271 $scope.printNote = function(note) {
1272 var hash = egCore.idl.toHash(note);
1273 hash.usr = egCore.idl.toHash($scope.patron());
1274 egCore.print.print({
1275 context : 'default',
1276 template : 'patron_note',
1277 scope : {note : hash}
1281 // perform the initial note fetch
1285 .controller('PatronGroupCtrl',
1286 ['$scope','$routeParams','$q','$window','$location','egCore',
1287 'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1288 function($scope, $routeParams , $q , $window , $location , egCore ,
1289 patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1291 var usr_id = $routeParams.id;
1293 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1295 var grid = $scope.gridControls = {
1296 activateItem : function(item) {
1297 $location.path('/circ/patron/' + item.id + '/checkout');
1299 itemRetrieved : function(item) {
1301 if (item.id == patronSvc.current.id()) {
1302 item.stats = patronSvc.patron_stats;
1305 // flesh stats for other group members
1306 patronSvc.getUserStats(item.id).then(function(stats) {
1308 $scope.totals.total_out += stats.checkouts.total_out;
1309 $scope.totals.overdue += stats.checkouts.overdue;
1313 setSort : function() {
1314 return ['create_date'];
1318 $scope.initTab('other', $routeParams.id)
1319 .then(function(redirect) {
1320 // if we are redirecting to the alerts page, avoid updating the
1322 if (redirect) return;
1323 // let initTab() fetch the user first so we can know the usrgroup
1326 usrgroup : patronSvc.current.usrgroup(),
1329 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1332 $scope.removeFromGroup = function(selected) {
1334 angular.forEach(selected, function(user) {
1335 console.debug('removing user ' + user.id + ' from group');
1340 'open-ils.actor.usergroup.new',
1341 egCore.auth.token(), user.id, true
1346 $q.all(promises).then(function() {grid.refresh()});
1349 function addUserToGroup(user) {
1350 user.usrgroup(patronSvc.current.usrgroup());
1351 user.ischanged(true);
1354 'open-ils.actor.patron.update',
1355 egCore.auth.token(), user
1357 ).then(function() {grid.refresh()});
1360 // fetch each user ("selected" has flattened users)
1361 // update the usrgroup, then update the user object
1362 // After all updates are complete, refresh the grid.
1363 function moveUsersToGroup(target_user, selected) {
1366 angular.forEach(selected, function(user) {
1368 egCore.pcrud.retrieve('au', user.id)
1370 u.usrgroup(target_user.usrgroup());
1372 return egCore.net.request(
1374 'open-ils.actor.patron.update',
1375 egCore.auth.token(), u
1381 $q.all(promises).then(function() {grid.refresh()});
1384 function showMoveToGroupConfirm(barcode, selected) {
1387 egCore.pcrud.search('ac', {barcode : barcode})
1389 // fetch the fleshed user
1390 .then(function(card) {
1392 if (!card) return; // TODO: warn user
1394 egCore.pcrud.retrieve('au', card.usr())
1395 .then(function(user) {
1398 templateUrl: './circ/patron/t_move_to_group_dialog',
1400 '$scope','$modalInstance',
1401 function($scope , $modalInstance) {
1403 $scope.outbound = Boolean(selected);
1405 function(count) { $modalInstance.close() }
1407 function () { $modalInstance.dismiss() }
1410 }).result.then(function() {
1412 moveUsersToGroup(user, selected);
1414 addUserToGroup(user);
1421 // selected == move selected patrons to another patron's group
1422 // !selected == patron from a different group moves into our group
1423 function moveToGroup(selected) {
1424 egPromptDialog.open(
1425 egCore.strings.GROUP_ADD_USER, '',
1426 {ok : function(value) {
1428 showMoveToGroupConfirm(value, selected);
1433 $scope.moveToGroup = function() { moveToGroup() };
1434 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected) };
1436 $scope.cloneUser = function(selected) {
1437 if (!selected.length) return;
1438 var url = $location.absUrl().replace(
1440 '/patron/register/clone/' + selected[0].id);
1441 $window.open(url, '_blank').focus();
1444 $scope.retrieveSelected = function(selected) {
1445 if (!selected.length) return;
1446 var url = $location.absUrl().replace(
1448 '/patron/' + selected[0].id + '/checkout');
1449 $window.open(url, '_blank').focus();
1454 .controller('PatronStatCatsCtrl',
1455 ['$scope','$routeParams','$q','egCore','patronSvc',
1456 function($scope, $routeParams , $q , egCore , patronSvc) {
1457 $scope.initTab('other', $routeParams.id)
1458 .then(function(redirect) {
1459 // Entries for org-visible stat cats are fleshed. Any others
1460 // have to be fleshed within.
1463 angular.forEach(patronSvc.current.stat_cat_entries(),
1465 if (!angular.isObject(entry.stat_cat())) {
1466 to_flesh[entry.stat_cat()] = entry;
1471 if (!Object.keys(to_flesh).length) return;
1473 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1474 .then(null, null, function(cat) { // stream
1475 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1476 to_flesh[cat.id()].stat_cat(cat);
1481 .controller('PatronFetchLastCtrl',
1482 ['$scope','$location','egCore',
1483 function($scope , $location , egCore) {
1485 var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1486 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1488 $scope.no_last = true;
1491 .controller('PatronTriggeredEventsCtrl',
1492 ['$scope','$routeParams','$location','egCore','patronSvc',
1493 function($scope, $routeParams, $location , egCore , patronSvc) {
1494 $scope.initTab('other', $routeParams.id);
1496 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1497 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1499 $scope.triggered_events_url = url;
1503 .controller('PatronPermsCtrl',
1504 ['$scope','$routeParams','$window','$location','egCore',
1505 function($scope , $routeParams , $window , $location , egCore) {
1506 $scope.initTab('other', $routeParams.id);
1508 var url = $location.absUrl().replace(
1509 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1511 url += '?usr=' + encodeURIComponent($routeParams.id);
1513 // user_edit does not load the session via cookie. It uses URL
1514 // params or xulG instead. Pass via xulG.
1516 ses : egCore.auth.token(),
1517 on_patron_save : function() {
1518 $scope.funcs.reload();
1522 $scope.user_perms_url = url;