4 * Search, checkout, items out, holds, bills, edit, etc.
7 angular.module('egPatronApp', ['ngRoute', 'ui.bootstrap',
8 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod', 'ngToast'])
10 .config(['ngToastProvider', function(ngToastProvider) {
11 ngToastProvider.configure({
12 verticalPosition: 'bottom',
17 .config(function($routeProvider, $locationProvider, $compileProvider) {
18 $locationProvider.html5Mode(true);
19 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
21 // data loaded at startup which only requires an authtoken goes
22 // here. this allows the requests to be run in parallel instead of
23 // waiting until startup has completed.
24 var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
26 // fetch the org settings we care about during egStartup
27 // and toss them into egCore.env as egCore.env.aous[name] = value.
28 // note: only load settings here needed by all tabs; load tab-
29 // specific settings from within their respective controllers
30 egCore.env.classLoaders.aous = function() {
31 return egCore.org.settings([
32 'ui.staff.require_initials.patron_info_notes',
33 'circ.do_not_tally_claims_returned',
36 'ui.circ.show_billing_tab_on_bills',
37 'circ.patron_expires_soon_warning',
38 'ui.circ.items_out.lost',
39 'ui.circ.items_out.longoverdue',
40 'ui.circ.items_out.claimsreturned'
41 ]).then(function(settings) {
42 // local settings are cached within egOrg. Caching them
43 // again in egEnv just simplifies the syntax for access.
44 egCore.env.aous = settings;
48 egCore.env.loadClasses.push('aous');
50 // app-globally modify the default flesh fields for
51 // fleshed user retrieval.
52 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
53 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
63 return egCore.startup.go().then(function() {
65 // This call requires orgs to be loaded, because it
66 // calls egCore.org.ancestors(), so call it after startup
67 return egCore.pcrud.search('actsc',
68 {owner : egCore.org.ancestors(
69 egCore.auth.user().ws_ou(), true)},
71 ).then(function(cats) {
72 egCore.env.absorbList(cats, 'actsc');
77 $routeProvider.when('/circ/patron/search', {
78 templateUrl: './circ/patron/t_search',
79 controller: 'PatronSearchCtrl',
83 $routeProvider.when('/circ/patron/bcsearch', {
84 templateUrl: './circ/patron/t_bcsearch',
85 controller: 'PatronBarcodeSearchCtrl',
89 $routeProvider.when('/circ/patron/credentials', {
90 templateUrl: './circ/patron/t_credentials',
91 controller: 'PatronVerifyCredentialsCtrl',
95 $routeProvider.when('/circ/patron/last', {
96 templateUrl: './circ/patron/t_last_patron',
97 controller: 'PatronFetchLastCtrl',
101 // the following require a patron ID
103 $routeProvider.when('/circ/patron/:id/alerts', {
104 templateUrl: './circ/patron/t_alerts',
105 controller: 'PatronAlertsCtrl',
109 $routeProvider.when('/circ/patron/:id/checkout', {
110 templateUrl: './circ/patron/t_checkout',
111 controller: 'PatronCheckoutCtrl',
115 $routeProvider.when('/circ/patron/:id/items_out', {
116 templateUrl: './circ/patron/t_items_out',
117 controller: 'PatronItemsOutCtrl',
121 $routeProvider.when('/circ/patron/:id/holds', {
122 templateUrl: './circ/patron/t_holds',
123 controller: 'PatronHoldsCtrl',
127 $routeProvider.when('/circ/patron/:id/holds/create', {
128 templateUrl: './circ/patron/t_holds_create',
129 controller: 'PatronHoldsCreateCtrl',
133 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
134 templateUrl: './circ/patron/t_holds',
135 controller: 'PatronHoldsCtrl',
139 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
140 templateUrl: './circ/patron/t_hold_details',
141 controller: 'PatronHoldDetailsCtrl',
145 $routeProvider.when('/circ/patron/:id/bills', {
146 templateUrl: './circ/patron/t_bills',
147 controller: 'PatronBillsCtrl',
151 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
152 templateUrl: './circ/patron/t_xact_details',
153 controller: 'XactDetailsCtrl',
157 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
158 templateUrl: './circ/patron/t_bill_history',
159 controller: 'BillHistoryCtrl',
163 $routeProvider.when('/circ/patron/:id/messages', {
164 templateUrl: './circ/patron/t_messages',
165 controller: 'PatronMessagesCtrl',
169 $routeProvider.when('/circ/patron/:id/edit', {
170 templateUrl: './circ/patron/t_edit',
171 controller: 'PatronRegCtrl',
175 $routeProvider.when('/circ/patron/:id/credentials', {
176 templateUrl: './circ/patron/t_credentials',
177 controller: 'PatronVerifyCredentialsCtrl',
181 $routeProvider.when('/circ/patron/:id/notes', {
182 templateUrl: './circ/patron/t_notes',
183 controller: 'PatronNotesCtrl',
187 $routeProvider.when('/circ/patron/:id/triggered_events', {
188 templateUrl: './circ/patron/t_triggered_events',
189 controller: 'PatronTriggeredEventsCtrl',
193 $routeProvider.when('/circ/patron/:id/edit_perms', {
194 templateUrl: './circ/patron/t_edit_perms',
195 controller: 'PatronPermsCtrl',
199 $routeProvider.when('/circ/patron/:id/group', {
200 templateUrl: './circ/patron/t_group',
201 controller: 'PatronGroupCtrl',
205 $routeProvider.when('/circ/patron/:id/stat_cats', {
206 templateUrl: './circ/patron/t_stat_cats',
207 controller: 'PatronStatCatsCtrl',
211 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
217 .factory('patronSvc',
218 ['$q','$timeout','$location','egCore','egUser','$locale',
219 function($q , $timeout , $location , egCore, egUser , $locale) {
222 // cached patron search results
225 // currently selected patron object
228 // patron circ stats (overdues, fines, holds)
231 // event types manually overridden, which should always be
232 // overridden for checkouts to this patron for this instance of
234 checkout_overrides : {},
235 //holds the searched barcode
236 search_barcode : null,
239 // when we change the default patron, we need to clear out any
240 // data collected on that patron
241 service.resetPatronLists = function() {
242 service.checkouts = [];
243 service.items_out = []
244 service.items_out_ids = [];
246 service.hold_ids = [];
247 service.checkout_overrides = {};
248 service.patron_stats = null;
249 service.noncat_ids = [];
250 service.hasAlerts = false;
251 service.alertsShown = false;
252 service.patronExpired = false;
253 service.patronExpiresSoon = false;
254 service.invalidAddresses = false;
256 service.resetPatronLists(); // initialize
258 // shortcut to force-reload the current primary
259 service.refreshPrimary = function() {
260 if (!service.current) return $q.when();
261 return service.setPrimary(service.current.id(), null, true);
264 // clear the currently focused user
265 service.clearPrimary = function() {
266 // reset with no patron
267 service.resetPatronLists();
268 service.current = null;
269 service.patron_stats = null;
273 // sets the primary display user, fetching data as necessary.
274 service.setPrimary = function(id, user, force) {
275 var user_id = id ? id : (user ? user.id() : null);
277 console.debug('setting primary user to: ' + user_id);
279 if (!user_id) return $q.reject();
281 // when loading a new patron, update the last patron setting
282 if (!service.current || service.current.id() != user_id)
283 egCore.hatch.setLoginSessionItem('eg.circ.last_patron', user_id);
285 // avoid running multiple retrievals for the same patron, which
286 // can happen during dbl-click by maintaining a single running
287 // data retrieval promise
288 if (service.primaryUserPromise) {
289 if (service.primaryUserId == user_id) {
290 return service.primaryUserPromise.promise;
292 service.primaryUserPromise = null;
296 service.primaryUserPromise = $q.defer();
297 service.primaryUserId = user_id;
299 service.getPrimary(id, user, force)
301 service.checkAlerts();
302 var p = service.primaryUserPromise;
303 service.primaryUserId = null;
304 // clear before resolution just to be safe.
305 service.primaryUserPromise = null;
309 return service.primaryUserPromise.promise;
312 service.getPrimary = function(id, user, force) {
315 if (!force && service.current &&
316 service.current.id() == user.id()) {
317 if (service.patron_stats) {
320 return service.fetchUserStats();
324 service.resetPatronLists();
325 service.current = user;
326 service.localFlesh(user);
327 return service.fetchUserStats();
330 if (!force && service.current && service.current.id() == id) {
331 if (service.patron_stats) {
334 return service.fetchUserStats();
338 service.resetPatronLists();
340 return egUser.get(id).then(
342 service.current = user;
343 service.localFlesh(user);
344 return service.fetchUserStats();
348 "unable to fetch user "+id+': '+js2JSON(err))
353 // fetching a null user clears the primary user.
354 // NOTE: this should probably reject() and log an error,
355 // but calling clear for backwards compat for now.
356 return service.clearPrimary();
360 // flesh some additional user fields locally
361 service.localFlesh = function(user) {
362 if (!angular.isObject(typeof user.home_ou()))
363 user.home_ou(egCore.org.get(user.home_ou()));
366 user.standing_penalties(),
368 if (!angular.isObject(penalty.org_unit()))
369 penalty.org_unit(egCore.org.get(penalty.org_unit()));
373 // stat_cat_entries == stat_cat_entry_user_map
374 angular.forEach(user.stat_cat_entries(), function(map) {
375 if (angular.isObject(map.stat_cat())) return;
376 // At page load, we only retrieve org-visible stat cats.
377 // For the common case, ignore entries for remote stat cats.
378 var cat = egCore.env.actsc.map[map.stat_cat()];
381 cat.owner(egCore.org.get(cat.owner()));
386 // resolves to true if the patron account has expired or will
387 // expire soon, based on YAOUS circ.patron_expires_soon_warning
388 // note: returning a promise is no longer strictly necessary
389 // (no more async activity) if the calling function is changed too.
390 service.testExpire = function() {
392 var expire = Date.parse(service.current.expire_date());
393 if (expire < new Date()) {
394 return $q.when(service.patronExpired = true);
397 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
399 var preExpire = new Date();
400 preExpire.setDate(preExpire.getDate() + Number(soon));
401 if (expire < preExpire)
402 return $q.when(service.patronExpiresSoon = true);
405 return $q.when(false);
408 // resolves to true if the patron account has any invalid addresses.
409 service.testInvalidAddrs = function() {
411 if (service.invalidAddresses)
412 return $q.when(true);
417 service.current.addresses(),
418 function(addr) { if (addr.valid() == 'f') fail = true }
421 return $q.when(fail);
423 //resolves to true if the patron was fetched with an inactive card
424 service.fetchedWithInactiveCard = function() {
425 var bc = service.search_barcode
426 var cards = service.current.cards();
427 var card = cards.filter(function(c) { return c.barcode() == bc })[0];
428 return (card && card.active() == 'f');
430 // resolves to true if there is any aspect of the patron account
431 // which should produce a message in the alerts panel
432 service.checkAlerts = function() {
434 if (service.hasAlerts) // already checked
435 return $q.when(true);
437 var deferred = $q.defer();
438 var p = service.current;
440 if (service.alert_penalties.length ||
444 service.patron_stats.holds.ready) {
446 service.hasAlerts = true;
449 // see if the user was retrieved with an inactive card
450 if(service.fetchedWithInactiveCard()){
451 service.hasAlerts = true;
454 // regardless of whether we know of alerts, we still need
455 // to test/fetch the expire data for display
456 service.testExpire().then(function(bool) {
457 if (bool) service.hasAlerts = true;
458 deferred.resolve(service.hasAlerts);
461 service.testInvalidAddrs().then(function(bool) {
462 if (bool) service.invalidAddresses = true;
463 deferred.resolve(service.invalidAddresses);
466 return deferred.promise;
469 service.fetchGroupFines = function() {
470 return egCore.net.request(
472 'open-ils.actor.usergroup.members.balance_owed',
473 egCore.auth.token(), service.current.usrgroup()
474 ).then(function(list) {
476 angular.forEach(list, function(u) {
477 total += 100 * Number(u.balance_owed)
479 service.patron_stats.fines.group_balance_owed = total / 100;
483 service.getUserStats = function(id) {
484 return egCore.net.request(
486 'open-ils.actor.user.opac.vital_stats.authoritative',
487 egCore.auth.token(), id
490 // force numeric to ensure correct boolean handling in templates
491 stats.fines.balance_owed = Number(stats.fines.balance_owed);
492 stats.checkouts.overdue = Number(stats.checkouts.overdue);
493 stats.checkouts.claims_returned =
494 Number(stats.checkouts.claims_returned);
495 stats.checkouts.lost = Number(stats.checkouts.lost);
496 stats.checkouts.out = Number(stats.checkouts.out);
497 stats.checkouts.total_out =
498 stats.checkouts.out + stats.checkouts.overdue;
500 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
501 stats.checkouts.total_out += stats.checkouts.claims_returned;
503 if (egCore.env.aous['circ.tally_lost'])
504 stats.checkouts.total_out += stats.checkouts.lost
511 // Fetches the IDs of any active non-cat checkouts for the current
512 // user. Also sets the patron_stats non_cat count value to match.
513 service.getUserNonCats = function(id) {
514 return egCore.net.request(
516 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
517 egCore.auth.token(), id
518 ).then(function(noncat_ids) {
519 service.noncat_ids = noncat_ids;
520 service.patron_stats.checkouts.noncat = noncat_ids.length;
524 // grab additional circ info
525 service.fetchUserStats = function() {
526 return service.getUserStats(service.current.id())
527 .then(function(stats) {
528 service.patron_stats = stats
529 service.alert_penalties = service.current.standing_penalties()
530 .filter(function(pen) {
531 return pen.standing_penalty().staff_alert() == 't'
534 service.summary_stat_cats = [];
535 angular.forEach(service.current.stat_cat_entries(),
537 if (angular.isObject(map.stat_cat()) &&
538 map.stat_cat().usr_summary() == 't') {
539 service.summary_stat_cats.push(map);
544 // run these two in parallel
545 var p1 = service.getUserNonCats(service.current.id());
546 var p2 = service.fetchGroupFines();
547 return $q.all([p1, p2]);
551 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
552 // which is the Angular default.
553 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
554 // FIXME: This change needs to be moved into a project-wide collection
555 // of locale overrides.
556 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
557 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
563 * Manages tabbed patron view.
564 * This is the parent scope of all patron tab scopes.
567 .controller('PatronCtrl',
568 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
569 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
571 $scope.is_patron_edit = function() {
572 return Boolean($location.path().match(/patron\/\d+\/edit$/));
575 // To support the fixed position patron edit actions bar,
576 // its markup has to live outside the scope of the patron
577 // edit controller. Insert a scope blob here that can be
578 // modifed from within the patron edit controller.
579 $scope.edit_passthru = {};
581 // returns true if a redirect occurs
582 function redirectToAlertPanel() {
584 $scope.alert_penalties =
585 function() {return patronSvc.alert_penalties}
587 if (patronSvc.alertsShown) return false;
588 patronSvc.alertsShown = true;
590 // if the patron has any unshown alerts, show them now
591 if (patronSvc.hasAlerts &&
592 !$location.path().match(/alerts$/)) {
595 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
596 .search('card', null);
600 // no alert required. If the patron has fines and the show-bills
601 // OUS is applied, direct to the bills page.
602 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
603 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
604 && !$location.path().match(/bills$/)) {
606 $scope.tab = 'bills';
608 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
609 .search('card', null);
617 // called after each route-specified controller is instantiated.
618 // this doubles as a way to inform the top-level controller that
619 // egStartup.go() has completed, which means we are clear to
620 // fetch the patron, etc.
621 $scope.initTab = function(tab, patron_id) {
622 console.log('init tab ' + tab);
624 $scope.aous = egCore.env.aous;
627 $scope.patron_id = patron_id;
628 return patronSvc.setPrimary($scope.patron_id)
629 .then(function() {return patronSvc.checkAlerts()})
630 .then(redirectToAlertPanel);
635 $scope._show_dob = {};
636 $scope.show_dob = function (val) {
637 if ($scope.patron()) {
638 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
639 return $scope._show_dob[$scope.patron().id()];
641 return !egCore.env.aous['circ.obscure_dob'];
644 $scope.obscure_dob = function() {
645 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
647 $scope.now_show_dob = function() {
648 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
649 $scope.show_dob() : true;
652 $scope.patron = function() { return patronSvc.current }
653 $scope.patron_stats = function() { return patronSvc.patron_stats }
654 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
655 $scope.hasAlerts = function() { return patronSvc.hasAlerts }
656 $scope.isPatronExpired = function() { return patronSvc.patronExpired }
658 $scope.print_address = function(addr) {
661 template : 'patron_address',
663 patron : egCore.idl.toHash(patronSvc.current),
664 address : egCore.idl.toHash(addr)
669 $scope.toggle_expand_summary = function() {
670 if ($scope.collapsePatronSummary) {
671 $scope.collapsePatronSummary = false;
672 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
674 $scope.collapsePatronSummary = true;
675 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
679 // always expand the patron summary in the search UI, regardless
680 // of stored preference.
681 $scope.collapse_summary = function() {
682 return $scope.tab != 'search' && $scope.collapsePatronSummary;
685 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
686 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
689 .controller('PatronBarcodeSearchCtrl',
690 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
691 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
692 $scope.selectMe = true; // focus text input
693 patronSvc.clearPrimary(); // clear the default user
695 // jump to the patron checkout UI
696 function loadPatron(user_id) {
698 .path('/circ/patron/' + user_id + '/checkout')
699 .search('card', $scope.args.barcode);
700 patronSvc.search_barcode = $scope.args.barcode;
703 // create an opt-in=yes response for the loaded user
704 function createOptIn(user_id) {
707 'open-ils.actor.user.org_unit_opt_in.create',
708 egCore.auth.token(), user_id).then(function(resp) {
709 if (evt = egCore.evt.parse(resp)) return alert(evt);
715 $scope.submitBarcode = function(args) {
716 $scope.bcNotFound = null;
717 $scope.optInRestricted = false;
718 if (!args.barcode) return;
720 // blur so next time it's set to true it will re-apply select()
721 $scope.selectMe = false;
728 'open-ils.actor.get_barcodes',
729 egCore.auth.token(), egCore.auth.user().ws_ou(),
730 'actor', args.barcode)
732 .then(function(resp) { // get_barcodes
734 if (evt = egCore.evt.parse(resp)) {
739 if (!resp || !resp[0]) {
740 $scope.bcNotFound = args.barcode;
741 $scope.selectMe = true;
745 // see if an opt-in request is needed
746 user_id = resp[0].id;
747 return egCore.net.request(
749 'open-ils.actor.user.org_unit_opt_in.check',
750 egCore.auth.token(), user_id);
752 }).then(function(optInResp) { // opt_in_check
754 if (evt = egCore.evt.parse(optInResp)) {
759 if (optInResp == 2) {
760 // opt-in disallowed at this location by patron's home library
761 $scope.optInRestricted = true;
762 $scope.selectMe = true;
766 if (optInResp == 1) {
767 // opt-in handled or not needed
768 return loadPatron(user_id);
771 // opt-in needed, show the opt-in dialog
772 egUser.get(user_id, {useFields : []})
774 .then(function(user) { // retrieve user
775 egConfirmDialog.open(
776 egCore.strings.OPT_IN_DIALOG, '',
777 { org : egCore.org.get(user.home_ou()),
779 ok : function() { createOptIn(user.id()) },
780 cancel : function() {}
790 * Manages patron search
792 .controller('PatronSearchCtrl',
793 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
794 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
796 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
797 $filter, egUser, patronSvc , egGridDataProvider , $document,
800 $scope.initTab('search');
801 $scope.focusMe = true;
802 $scope.searchArgs = {
803 // default to searching globally
804 home_ou : egCore.org.tree()
807 // last used patron search form element
810 $scope.gridControls = {
811 activateItem : function(item) {
812 $location.path('/circ/patron/' + item.id() + '/checkout');
814 selectedItems : function() {return []}
817 // Handle URL-encoded searches
818 if ($location.search().search) {
819 console.log('URL search = ' + $location.search().search);
820 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
822 // why the double-JSON encoded sort?
823 if (patronSvc.urlSearch.search.search_sort) {
824 patronSvc.urlSearch.sort =
825 JSON2js(patronSvc.urlSearch.search.search_sort);
827 patronSvc.urlSearch.sort = [];
829 delete patronSvc.urlSearch.search.search_sort;
833 if (patronSvc.lastSearch) {
834 propagate = patronSvc.lastSearch.search;
835 // home_ou needs to be treated specially
836 propagate.home_ou = {
837 value : patronSvc.lastSearch.home_ou,
840 } else if (patronSvc.urlSearch) {
841 propagate = patronSvc.urlSearch.search;
844 if (egCore.env.pgt) {
845 $scope.profiles = egCore.env.pgt.list;
847 egCore.pcrud.search('pgt', {parent : null},
848 {flesh : -1, flesh_fields : {pgt : ['children']}}
851 egCore.env.absorbTree(tree, 'pgt')
852 $scope.profiles = egCore.env.pgt.list;
858 // populate the search form with our cached / preexisting search info
859 angular.forEach(propagate, function(val, key) {
860 if (key == 'profile')
861 val.value = $scope.profiles.filter(function(p) { return p.id() == val.value })[0];
862 if (key == 'home_ou')
863 val.value = egCore.org.get(val.value);
864 $scope.searchArgs[key] = val.value;
868 var provider = egGridDataProvider.instance({});
871 function() {return $scope.gridControls.selectedItems()},
874 patronSvc.setPrimary(null, list[0]);
879 provider.get = function(offset, count) {
880 var deferred = $q.defer();
883 if (patronSvc.urlSearch) {
884 fullSearch = patronSvc.urlSearch;
885 // enusre the urlSearch only runs once.
886 delete patronSvc.urlSearch;
889 patronSvc.search_barcode = $scope.searchArgs.card;
891 var search = compileSearch($scope.searchArgs);
892 if (Object.keys(search) == 0) return $q.when();
894 var home_ou = search.home_ou;
895 delete search.home_ou;
896 var inactive = search.inactive;
897 delete search.inactive;
901 sort : compileSort(),
907 fullSearch.count = count;
908 fullSearch.offset = offset;
910 if (patronSvc.lastSearch) {
911 // search repeated, return the cached results
912 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
913 console.log('patron search returning ' +
914 patronSvc.patrons.length + ' cached results');
916 // notify has to happen after returning the promise
919 angular.forEach(patronSvc.patrons, function(user) {
920 deferred.notify(user);
925 return deferred.promise;
929 patronSvc.lastSearch = fullSearch;
931 if (fullSearch.search.id) {
932 // search by user id performs a direct ID lookup
933 var userId = fullSearch.search.id.value;
936 egUser.get(userId).then(function(user) {
937 patronSvc.localFlesh(user);
938 patronSvc.patrons = [user];
939 deferred.notify(user);
944 return deferred.promise;
947 // Dispay the search progress bar to indicate a search is in progress
948 $scope.show_search_progress = true;
950 patronSvc.patrons = [];
953 'open-ils.actor.patron.search.advanced.fleshed',
960 egUser.defaultFleshFields,
965 // hide progress bar on 0-hits searches
966 $scope.show_search_progress = false;
971 // hide progress bar as soon as the first result appears.
972 $scope.show_search_progress = false;
973 patronSvc.localFlesh(user); // inline
974 patronSvc.patrons.push(user);
975 deferred.notify(user);
979 return deferred.promise;
982 $scope.patronSearchGridProvider = provider;
984 // determine the tree depth of the profile group
985 $scope.pgt_depth = function(grp) {
987 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
991 $scope.clearForm = function () {
992 $scope.searchArgs={};
993 if (lastFormElement) lastFormElement.focus();
996 $scope.applyShowExtras = function($event, bool) {
998 $scope.showExtras = true;
999 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
1001 $scope.showExtras = false;
1002 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
1004 if (lastFormElement) lastFormElement.focus();
1005 $event.preventDefault();
1008 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
1009 .then(function(val) {$scope.showExtras = val});
1011 // map form arguments into search params
1012 function compileSearch(args) {
1014 angular.forEach(args, function(val, key) {
1016 if (key == 'profile' && args.profile) {
1017 search.profile = {value : args.profile.id(), group : 0};
1018 } else if (key == 'home_ou' && args.home_ou) {
1019 search.home_ou = args.home_ou.id(); // passed separately
1020 } else if (key == 'inactive') {
1021 search.inactive = val;
1023 search[key] = {value : val, group : 0};
1025 if (key.match(/phone|ident/)) {
1026 search[key].group = 2;
1028 if (key.match(/street|city|state|post_code/)) {
1029 search[key].group = 1;
1030 } else if (key == 'card') {
1031 search[key].group = 3
1039 function compileSort() {
1041 if (!provider.sort.length) {
1044 "first_given_name ASC",
1045 "second_given_name ASC",
1054 if (angular.isObject(sortdef)) {
1055 var name = Object.keys(sortdef)[0];
1056 var dir = sortdef[name];
1057 sort.push(name + ' ' + dir);
1067 $scope.setLastFormElement = function() {
1068 lastFormElement = $document[0].activeElement;
1071 // search form submit action; tells the results grid to
1073 $scope.search = function(args) { // args === $scope.searchArgs
1074 if (args && Object.keys(args).length)
1075 $scope.gridControls.refresh();
1076 if (lastFormElement) lastFormElement.focus();
1079 // TODO: move this into the (forthcoming) grid row activate action
1080 $scope.onPatronDblClick = function($event, user) {
1081 $location.path('/circ/patron/' + user.id() + '/checkout');
1084 if (patronSvc.urlSearch) {
1085 // force the grid to load the url-based search on page load
1089 $scope.need_two_selected = function() {
1090 var items = $scope.gridControls.selectedItems();
1091 return (items.length == 2) ? false : true;
1093 $scope.merge_patrons = function() {
1094 var items = $scope.gridControls.selectedItems();
1095 if (items.length != 2) return false;
1097 var patron_ids = [];
1098 angular.forEach(items, function(i) {
1099 patron_ids.push(i.id());
1101 egPatronMerge.do_merge(patron_ids).then(function() {
1102 // ensure that we're not drawing from cached
1103 // resuts, as a successful merge just deleted a
1105 delete patronSvc.lastSearch;
1106 $scope.gridControls.refresh();
1115 .controller('PatronMessagesCtrl',
1116 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
1117 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
1118 $scope.initTab('messages', $routeParams.id);
1119 var usr_id = $routeParams.id;
1121 // setup date filters
1122 var start = new Date(); // now - 1 year
1123 start.setFullYear(start.getFullYear() - 1),
1126 end_date : new Date()
1129 function date_range() {
1130 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1131 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1132 var today = new Date().toISOString().replace(/T.*/,'');
1133 if (end == today) end = 'now';
1134 return [start, end];
1139 var activeGrid = $scope.activeGridControls = {
1140 setSort : function() {
1141 return ['set_date'];
1143 setQuery : function() {
1148 {stop_date : {'>' : 'now'}}
1154 var archiveGrid = $scope.archiveGridControls = {
1155 setSort : function() {
1156 return ['set_date'];
1158 setQuery : function() {
1161 stop_date : {'<=' : 'now'},
1162 set_date : {between : date_range()}
1167 $scope.removePenalty = function(selected) {
1168 // the grid stores flattened penalties. Fetch penalty objects first
1170 var ids = selected.map(function(s){ return s.id });
1171 egCore.pcrud.search('ausp',
1173 {atomic : true, authoritative : true}
1176 ).then(function(penalties) {
1177 return egCore.pcrud.remove(penalties);
1179 // then refresh the grid
1180 }).then(function() {
1181 activeGrid.refresh();
1185 $scope.archivePenalty = function(selected) {
1186 // the grid stores flattened penalties. Fetch penalty objects first
1188 var ids = selected.map(function(s){ return s.id });
1189 egCore.pcrud.search('ausp',
1191 {atomic : true, authoritative : true}
1194 ).then(function(penalties) {
1195 angular.forEach(penalties, function(p){ p.stop_date('now') });
1196 return egCore.pcrud.update(penalties);
1198 // then refresh the grid
1199 }).then(function() {
1200 activeGrid.refresh();
1201 archiveGrid.refresh();
1205 // leverage egEnv for caching
1206 function fetchPenaltyTypes() {
1208 return $q.when(egCore.env.csp.list);
1209 return egCore.pcrud.search(
1210 // id <= 100 are reserved for system use
1211 'csp', {id : {'>': 100}}, {}, {atomic : true})
1212 .then(function(penalties) {
1213 egCore.env.absorbList(penalties, 'csp');
1218 $scope.createPenalty = function() {
1219 egCirc.create_penalty(usr_id).then(function() {
1220 activeGrid.refresh();
1221 // force a refresh of the user, since they may now
1222 // have blocking penalties, etc.
1223 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1227 $scope.editPenalty = function(selected) {
1228 if (selected.length == 0) return;
1230 // grab the penalty from the user object
1231 var penalty = patronSvc.current.standing_penalties().filter(
1232 function(p) {return p.id() == selected[0].id})[0];
1234 egCirc.edit_penalty(penalty).then(function() {
1235 activeGrid.refresh();
1236 // force a refresh of the user, since they may now
1237 // have blocking penalties, etc.
1238 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1245 * Credentials tester
1247 .controller('PatronVerifyCredentialsCtrl',
1248 ['$scope','$routeParams','$location','egCore',
1249 function($scope, $routeParams , $location , egCore) {
1250 $scope.verified = null;
1251 $scope.focusMe = true;
1253 // called with a patron, pre-populate the form args
1254 $scope.initTab('other', $routeParams.id).then(
1256 if ($routeParams.id && $scope.patron()) {
1257 $scope.prepop = true;
1258 $scope.username = $scope.patron().usrname();
1259 $scope.barcode = $scope.patron().card().barcode();
1261 $scope.username = '';
1262 $scope.barcode = '';
1263 $scope.password = '';
1268 // verify login credentials
1269 $scope.verify = function() {
1270 $scope.verified = null;
1271 $scope.notFound = false;
1275 'open-ils.actor.verify_user_password',
1276 egCore.auth.token(), $scope.barcode,
1277 $scope.username, hex_md5($scope.password || '')
1279 ).then(function(resp) {
1280 $scope.focusMe = true;
1281 if (evt = egCore.evt.parse(resp)) {
1283 } else if (resp == 1) {
1284 $scope.verified = true;
1286 $scope.verified = false;
1291 // load the main patron UI for the provided username or barcode
1292 $scope.load = function($event) {
1293 $scope.notFound = false;
1294 $scope.verified = null;
1298 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1299 egCore.auth.token(), $scope.barcode, $scope.username
1301 ).then(function(resp) {
1304 $location.path('/circ/patron/' + resp + '/checkout');
1308 // something went wrong...
1309 $scope.focusMe = true;
1310 if (evt = egCore.evt.parse(resp)) {
1311 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1312 $scope.notFound = true;
1321 // load() button sits within the verify form.
1322 // avoid submitting the verify() form action on load()
1323 $event.preventDefault();
1327 .controller('PatronAlertsCtrl',
1328 ['$scope','$routeParams','$location','egCore','patronSvc',
1329 function($scope, $routeParams , $location , egCore , patronSvc) {
1331 $scope.initTab('other', $routeParams.id)
1333 $scope.patronExpired = patronSvc.patronExpired;
1334 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1335 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1336 $scope.invalidAddresses = patronSvc.invalidAddresses;
1341 .controller('PatronNotesCtrl',
1342 ['$scope', '$filter', '$routeParams','$location','egCore','patronSvc','$uibModal',
1343 function($scope, $filter, $routeParams , $location , egCore , patronSvc , $uibModal) {
1344 $scope.initTab('other', $routeParams.id);
1345 var usr_id = $routeParams.id;
1348 function refreshPage() {
1350 egCore.pcrud.search('aun',
1352 {flesh : 1, flesh_fields : {aun : ['creator']}},
1353 {authoritative : true})
1354 .then(null, null, function(note) {
1355 $scope.notes.push(note);
1359 // open the new-note dialog and create the note
1360 $scope.newNote = function() {
1362 templateUrl: './circ/patron/t_new_note_dialog',
1364 ['$scope', '$uibModalInstance',
1365 function($scope, $uibModalInstance) {
1366 $scope.focusNote = true;
1368 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1369 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1370 $scope.cancel = function () { $uibModalInstance.dismiss() }
1374 if (!args.value) return;
1375 var note = new egCore.idl.aun();
1377 note.title(args.title);
1378 note.value(args.value);
1379 note.pub(args.pub ? 't' : 'f');
1380 note.creator(egCore.auth.user().id());
1382 note.value(note.value() + ' [' + args.initials + ']');
1383 egCore.pcrud.create(note).then(function() {refreshPage()});
1388 // delete the selected note
1389 $scope.deleteNote = function(note) {
1390 egCore.pcrud.remove(note).then(function() {refreshPage()});
1393 // print the selected note
1394 $scope.printNote = function(note) {
1395 var hash = egCore.idl.toHash(note);
1396 hash.usr = egCore.idl.toHash($scope.patron());
1397 egCore.print.print({
1398 context : 'default',
1399 template : 'patron_note',
1400 scope : {note : hash}
1404 // perform the initial note fetch
1408 .controller('PatronGroupCtrl',
1409 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1410 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1411 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1412 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1414 var usr_id = $routeParams.id;
1416 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1418 var grid = $scope.gridControls = {
1419 activateItem : function(item) {
1420 $location.path('/circ/patron/' + item.id + '/checkout');
1422 itemRetrieved : function(item) {
1424 if (item.id == patronSvc.current.id()) {
1425 item.stats = patronSvc.patron_stats;
1428 // flesh stats for other group members
1429 patronSvc.getUserStats(item.id).then(function(stats) {
1431 $scope.totals.total_out += stats.checkouts.total_out;
1432 $scope.totals.overdue += stats.checkouts.overdue;
1436 setSort : function() {
1437 return ['create_date'];
1441 $scope.initTab('other', $routeParams.id)
1442 .then(function(redirect) {
1443 // if we are redirecting to the alerts page, avoid updating the
1445 if (redirect) return;
1446 // let initTab() fetch the user first so we can know the usrgroup
1449 usrgroup : patronSvc.current.usrgroup(),
1452 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1455 $scope.removeFromGroup = function(selected) {
1457 angular.forEach(selected, function(user) {
1458 console.debug('removing user ' + user.id + ' from group');
1463 'open-ils.actor.usergroup.new',
1464 egCore.auth.token(), user.id, true
1469 $q.all(promises).then(function() {grid.refresh()});
1472 function addUserToGroup(user) {
1473 user.usrgroup(patronSvc.current.usrgroup());
1474 user.ischanged(true);
1477 'open-ils.actor.patron.update',
1478 egCore.auth.token(), user
1480 ).then(function() {grid.refresh()});
1483 // fetch each user ("selected" has flattened users)
1484 // update the usrgroup, then update the user object
1485 // After all updates are complete, refresh the grid.
1486 function moveUsersToGroup(target_user, selected) {
1489 angular.forEach(selected, function(user) {
1491 egCore.pcrud.retrieve('au', user.id)
1493 u.usrgroup(target_user.usrgroup());
1495 return egCore.net.request(
1497 'open-ils.actor.patron.update',
1498 egCore.auth.token(), u
1504 $q.all(promises).then(function() {grid.refresh()});
1507 function showMoveToGroupConfirm(barcode, selected, outbound) {
1510 egCore.pcrud.search('ac', {barcode : barcode})
1512 // fetch the fleshed user
1513 .then(function(card) {
1515 if (!card) return; // TODO: warn user
1517 egCore.pcrud.retrieve('au', card.usr())
1518 .then(function(user) {
1521 templateUrl: './circ/patron/t_move_to_group_dialog',
1523 '$scope','$uibModalInstance',
1524 function($scope , $uibModalInstance) {
1526 $scope.selected = selected;
1527 $scope.outbound = outbound;
1529 function(count) { $uibModalInstance.close() }
1531 function () { $uibModalInstance.dismiss() }
1534 }).result.then(function() {
1536 moveUsersToGroup(user, selected);
1538 addUserToGroup(user);
1545 // selected == move selected patrons to another patron's group
1546 // !selected == patron from a different group moves into our group
1547 function moveToGroup(selected, outbound) {
1548 egPromptDialog.open(
1549 egCore.strings.GROUP_ADD_USER, '',
1550 {ok : function(value) {
1552 showMoveToGroupConfirm(value, selected, outbound);
1557 $scope.moveToGroup = function() { moveToGroup([], false) };
1558 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1560 $scope.cloneUser = function(selected) {
1561 if (!selected.length) return;
1562 var url = $location.absUrl().replace(
1564 '/patron/register/clone/' + selected[0].id);
1565 $window.open(url, '_blank').focus();
1568 $scope.retrieveSelected = function(selected) {
1569 if (!selected.length) return;
1570 angular.forEach(selected, function(usr) {
1571 $timeout(function() {
1572 var url = $location.absUrl().replace(
1574 '/patron/' + usr.id + '/checkout');
1575 $window.open(url, '_blank')
1582 .controller('PatronStatCatsCtrl',
1583 ['$scope','$routeParams','$q','egCore','patronSvc',
1584 function($scope, $routeParams , $q , egCore , patronSvc) {
1585 $scope.initTab('other', $routeParams.id)
1586 .then(function(redirect) {
1587 // Entries for org-visible stat cats are fleshed. Any others
1588 // have to be fleshed within.
1591 angular.forEach(patronSvc.current.stat_cat_entries(),
1593 if (!angular.isObject(entry.stat_cat())) {
1594 to_flesh[entry.stat_cat()] = entry;
1599 if (!Object.keys(to_flesh).length) return;
1601 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1602 .then(null, null, function(cat) { // stream
1603 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1604 to_flesh[cat.id()].stat_cat(cat);
1609 .controller('PatronFetchLastCtrl',
1610 ['$scope','$location','egCore',
1611 function($scope , $location , egCore) {
1613 var id = egCore.hatch.getLoginSessionItem('eg.circ.last_patron');
1614 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1616 $scope.no_last = true;
1619 .controller('PatronTriggeredEventsCtrl',
1620 ['$scope','$routeParams','$location','egCore','patronSvc',
1621 function($scope, $routeParams, $location , egCore , patronSvc) {
1622 $scope.initTab('other', $routeParams.id);
1624 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1625 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1627 $scope.triggered_events_url = url;
1631 .controller('PatronPermsCtrl',
1632 ['$scope','$routeParams','$window','$location','egCore',
1633 function($scope , $routeParams , $window , $location , egCore) {
1634 $scope.initTab('other', $routeParams.id);
1636 var url = $location.absUrl().replace(
1637 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1639 url += '?usr=' + encodeURIComponent($routeParams.id);
1641 // user_edit does not load the session via cookie. It uses URL
1642 // params or xulG instead. Pass via xulG.
1644 ses : egCore.auth.token(),
1645 on_patron_save : function() {
1646 $scope.funcs.reload();
1650 $scope.user_perms_url = url;