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([
54 return egCore.startup.go().then(function() {
56 // This call requires orgs to be loaded, because it
57 // calls egCore.org.ancestors(), so call it after startup
58 return egCore.pcrud.search('actsc',
59 {owner : egCore.org.ancestors(
60 egCore.auth.user().ws_ou(), true)},
62 ).then(function(cats) {
63 egCore.env.absorbList(cats, 'actsc');
68 $routeProvider.when('/circ/patron/search', {
69 templateUrl: './circ/patron/t_search',
70 controller: 'PatronSearchCtrl',
74 $routeProvider.when('/circ/patron/bcsearch', {
75 templateUrl: './circ/patron/t_bcsearch',
76 controller: 'PatronBarcodeSearchCtrl',
80 $routeProvider.when('/circ/patron/credentials', {
81 templateUrl: './circ/patron/t_credentials',
82 controller: 'PatronVerifyCredentialsCtrl',
86 $routeProvider.when('/circ/patron/last', {
87 templateUrl: './circ/patron/t_last_patron',
88 controller: 'PatronFetchLastCtrl',
92 // the following require a patron ID
94 $routeProvider.when('/circ/patron/:id/alerts', {
95 templateUrl: './circ/patron/t_alerts',
96 controller: 'PatronAlertsCtrl',
100 $routeProvider.when('/circ/patron/:id/checkout', {
101 templateUrl: './circ/patron/t_checkout',
102 controller: 'PatronCheckoutCtrl',
106 $routeProvider.when('/circ/patron/:id/items_out', {
107 templateUrl: './circ/patron/t_items_out',
108 controller: 'PatronItemsOutCtrl',
112 $routeProvider.when('/circ/patron/:id/holds', {
113 templateUrl: './circ/patron/t_holds',
114 controller: 'PatronHoldsCtrl',
118 $routeProvider.when('/circ/patron/:id/holds/create', {
119 templateUrl: './circ/patron/t_holds_create',
120 controller: 'PatronHoldsCreateCtrl',
124 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
125 templateUrl: './circ/patron/t_holds',
126 controller: 'PatronHoldsCtrl',
130 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
131 templateUrl: './circ/patron/t_hold_details',
132 controller: 'PatronHoldDetailsCtrl',
136 $routeProvider.when('/circ/patron/:id/bills', {
137 templateUrl: './circ/patron/t_bills',
138 controller: 'PatronBillsCtrl',
142 $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
143 templateUrl: './circ/patron/t_xact_details',
144 controller: 'XactDetailsCtrl',
148 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
149 templateUrl: './circ/patron/t_bill_history',
150 controller: 'BillHistoryCtrl',
154 $routeProvider.when('/circ/patron/:id/messages', {
155 templateUrl: './circ/patron/t_messages',
156 controller: 'PatronMessagesCtrl',
160 $routeProvider.when('/circ/patron/:id/edit', {
161 templateUrl: './circ/patron/t_edit',
162 controller: 'PatronRegCtrl',
166 $routeProvider.when('/circ/patron/:id/credentials', {
167 templateUrl: './circ/patron/t_credentials',
168 controller: 'PatronVerifyCredentialsCtrl',
172 $routeProvider.when('/circ/patron/:id/notes', {
173 templateUrl: './circ/patron/t_notes',
174 controller: 'PatronNotesCtrl',
178 $routeProvider.when('/circ/patron/:id/triggered_events', {
179 templateUrl: './circ/patron/t_triggered_events',
180 controller: 'PatronTriggeredEventsCtrl',
184 $routeProvider.when('/circ/patron/:id/edit_perms', {
185 templateUrl: './circ/patron/t_edit_perms',
186 controller: 'PatronPermsCtrl',
190 $routeProvider.when('/circ/patron/:id/group', {
191 templateUrl: './circ/patron/t_group',
192 controller: 'PatronGroupCtrl',
196 $routeProvider.when('/circ/patron/:id/stat_cats', {
197 templateUrl: './circ/patron/t_stat_cats',
198 controller: 'PatronStatCatsCtrl',
202 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
208 .factory('patronSvc',
209 ['$q','$timeout','$location','egCore','egUser','$locale',
210 function($q , $timeout , $location , egCore, egUser , $locale) {
213 // cached patron search results
216 // currently selected patron object
219 // patron circ stats (overdues, fines, holds)
222 // event types manually overridden, which should always be
223 // overridden for checkouts to this patron for this instance of
225 checkout_overrides : {},
228 // when we change the default patron, we need to clear out any
229 // data collected on that patron
230 service.resetPatronLists = function() {
231 service.checkouts = [];
232 service.items_out = []
233 service.items_out_ids = [];
235 service.hold_ids = [];
236 service.checkout_overrides = {};
237 service.patron_stats = null;
238 service.noncat_ids = [];
239 service.hasAlerts = false;
240 service.alertsShown = false;
241 service.patronExpired = false;
242 service.patronExpiresSoon = false;
243 service.retrievedWithInactive = false;
244 service.invalidAddresses = false;
246 service.resetPatronLists(); // initialize
248 // shortcut to force-reload the current primary
249 service.refreshPrimary = function() {
250 if (!service.current) return $q.when();
251 return service.setPrimary(service.current.id(), null, true);
254 // clear the currently focused user
255 service.clearPrimary = function() {
256 // reset with no patron
257 service.resetPatronLists();
258 service.current = null;
259 service.patron_stats = null;
263 // sets the primary display user, fetching data as necessary.
264 service.setPrimary = function(id, user, force) {
265 var user_id = id ? id : (user ? user.id() : null);
267 console.debug('setting primary user to: ' + user_id);
269 if (!user_id) return $q.reject();
271 // when loading a new patron, update the last patron setting
272 if (!service.current || service.current.id() != user_id)
273 egCore.hatch.setLocalItem('eg.circ.last_patron', user_id);
275 // avoid running multiple retrievals for the same patron, which
276 // can happen during dbl-click by maintaining a single running
277 // data retrieval promise
278 if (service.primaryUserPromise) {
279 if (service.primaryUserId == user_id) {
280 return service.primaryUserPromise.promise;
282 service.primaryUserPromise = null;
286 service.primaryUserPromise = $q.defer();
287 service.primaryUserId = user_id;
289 service.getPrimary(id, user, force)
291 var p = service.primaryUserPromise;
292 service.primaryUserId = null;
293 // clear before resolution just to be safe.
294 service.primaryUserPromise = null;
298 return service.primaryUserPromise.promise;
301 service.getPrimary = function(id, user, force) {
304 if (!force && service.current &&
305 service.current.id() == user.id()) {
306 if (service.patron_stats) {
309 return service.fetchUserStats();
313 service.resetPatronLists();
314 service.current = user;
315 service.localFlesh(user);
316 return service.fetchUserStats();
319 if (!force && service.current && service.current.id() == id) {
320 if (service.patron_stats) {
323 return service.fetchUserStats();
327 service.resetPatronLists();
329 return egUser.get(id).then(
331 service.current = user;
332 service.localFlesh(user);
333 return service.fetchUserStats();
337 "unable to fetch user "+id+': '+js2JSON(err))
342 // fetching a null user clears the primary user.
343 // NOTE: this should probably reject() and log an error,
344 // but calling clear for backwards compat for now.
345 return service.clearPrimary();
349 // flesh some additional user fields locally
350 service.localFlesh = function(user) {
351 if (!angular.isObject(typeof user.home_ou()))
352 user.home_ou(egCore.org.get(user.home_ou()));
355 user.standing_penalties(),
357 if (!angular.isObject(penalty.org_unit()))
358 penalty.org_unit(egCore.org.get(penalty.org_unit()));
362 // stat_cat_entries == stat_cat_entry_user_map
363 angular.forEach(user.stat_cat_entries(), function(map) {
364 if (angular.isObject(map.stat_cat())) return;
365 // At page load, we only retrieve org-visible stat cats.
366 // For the common case, ignore entries for remote stat cats.
367 var cat = egCore.env.actsc.map[map.stat_cat()];
370 cat.owner(egCore.org.get(cat.owner()));
375 // resolves to true if the patron account has expired or will
376 // expire soon, based on YAOUS circ.patron_expires_soon_warning
377 // note: returning a promise is no longer strictly necessary
378 // (no more async activity) if the calling function is changed too.
379 service.testExpire = function() {
381 var expire = Date.parse(service.current.expire_date());
382 if (expire < new Date()) {
383 return $q.when(service.patronExpired = true);
386 var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
388 var preExpire = new Date();
389 preExpire.setDate(preExpire.getDate() + Number(soon));
390 if (expire < preExpire)
391 return $q.when(service.patronExpiresSoon = true);
394 return $q.when(false);
397 // resolves to true if the patron account has any invalid addresses.
398 service.testInvalidAddrs = function() {
400 if (service.invalidAddresses)
401 return $q.when(true);
406 service.current.addresses(),
407 function(addr) { if (addr.valid() == 'f') fail = true }
410 return $q.when(fail);
413 // resolves to true if there is any aspect of the patron account
414 // which should produce a message in the alerts panel
415 service.checkAlerts = function() {
417 if (service.hasAlerts) // already checked
418 return $q.when(true);
420 var deferred = $q.defer();
421 var p = service.current;
423 if (service.alert_penalties.length ||
427 service.patron_stats.holds.ready) {
429 service.hasAlerts = true;
432 // see if the user was retrieved with an inactive card
433 if (bc = $location.search().card) {
434 var card = p.cards().filter(
435 function(c) { return c.barcode() == bc })[0];
437 if (card && card.active() == 'f') {
438 service.hasAlerts = true;
439 service.retrievedWithInactive = true;
443 // regardless of whether we know of alerts, we still need
444 // to test/fetch the expire data for display
445 service.testExpire().then(function(bool) {
446 if (bool) service.hasAlerts = true;
447 deferred.resolve(service.hasAlerts);
450 service.testInvalidAddrs().then(function(bool) {
451 if (bool) service.invalidAddresses = true;
452 deferred.resolve(service.invalidAddresses);
455 return deferred.promise;
458 service.fetchGroupFines = function() {
459 return egCore.net.request(
461 'open-ils.actor.usergroup.members.balance_owed',
462 egCore.auth.token(), service.current.usrgroup()
463 ).then(function(list) {
465 angular.forEach(list, function(u) {
466 total += 100 * Number(u.balance_owed)
468 service.patron_stats.fines.group_balance_owed = total / 100;
472 service.getUserStats = function(id) {
473 return egCore.net.request(
475 'open-ils.actor.user.opac.vital_stats.authoritative',
476 egCore.auth.token(), id
479 // force numeric to ensure correct boolean handling in templates
480 stats.fines.balance_owed = Number(stats.fines.balance_owed);
481 stats.checkouts.overdue = Number(stats.checkouts.overdue);
482 stats.checkouts.claims_returned =
483 Number(stats.checkouts.claims_returned);
484 stats.checkouts.lost = Number(stats.checkouts.lost);
485 stats.checkouts.out = Number(stats.checkouts.out);
486 stats.checkouts.total_out =
487 stats.checkouts.out + stats.checkouts.overdue;
489 if (!egCore.env.aous['circ.do_not_tally_claims_returned'])
490 stats.checkouts.total_out += stats.checkouts.claims_returned;
492 if (egCore.env.aous['circ.tally_lost'])
493 stats.checkouts.total_out += stats.checkouts.lost
500 // Fetches the IDs of any active non-cat checkouts for the current
501 // user. Also sets the patron_stats non_cat count value to match.
502 service.getUserNonCats = function(id) {
503 return egCore.net.request(
505 'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
506 egCore.auth.token(), id
507 ).then(function(noncat_ids) {
508 service.noncat_ids = noncat_ids;
509 service.patron_stats.checkouts.noncat = noncat_ids.length;
513 // grab additional circ info
514 service.fetchUserStats = function() {
515 return service.getUserStats(service.current.id())
516 .then(function(stats) {
517 service.patron_stats = stats
518 service.alert_penalties = service.current.standing_penalties()
519 .filter(function(pen) {
520 return pen.standing_penalty().staff_alert() == 't'
523 service.summary_stat_cats = [];
524 angular.forEach(service.current.stat_cat_entries(),
526 if (angular.isObject(map.stat_cat()) &&
527 map.stat_cat().usr_summary() == 't') {
528 service.summary_stat_cats.push(map);
533 // run these two in parallel
534 var p1 = service.getUserNonCats(service.current.id());
535 var p2 = service.fetchGroupFines();
536 return $q.all([p1, p2]);
540 // Avoid using parens [e.g. (1.23)] to indicate negative numbers,
541 // which is the Angular default.
542 // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
543 // FIXME: This change needs to be moved into a project-wide collection
544 // of locale overrides.
545 $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
546 $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
552 * Manages tabbed patron view.
553 * This is the parent scope of all patron tab scopes.
556 .controller('PatronCtrl',
557 ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
558 function($scope, $q, $location , $filter, egCore, egUser, patronSvc) {
560 $scope.is_patron_edit = function() {
561 return Boolean($location.path().match(/patron\/\d+\/edit$/));
564 // returns true if a redirect occurs
565 function redirectToAlertPanel() {
567 $scope.alert_penalties =
568 function() {return patronSvc.alert_penalties}
570 if (patronSvc.alertsShown) return false;
571 patronSvc.alertsShown = true;
573 // if the patron has any unshown alerts, show them now
574 if (patronSvc.hasAlerts &&
575 !$location.path().match(/alerts$/)) {
578 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
579 .search('card', null);
583 // no alert required. If the patron has fines and the show-bills
584 // OUS is applied, direct to the bills page.
585 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
586 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
587 && !$location.path().match(/bills$/)) {
589 $scope.tab = 'bills';
591 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
592 .search('card', null);
600 // called after each route-specified controller is instantiated.
601 // this doubles as a way to inform the top-level controller that
602 // egStartup.go() has completed, which means we are clear to
603 // fetch the patron, etc.
604 $scope.initTab = function(tab, patron_id) {
605 console.log('init tab ' + tab);
607 $scope.aous = egCore.env.aous;
610 $scope.patron_id = patron_id;
611 return patronSvc.setPrimary($scope.patron_id)
612 .then(function() {return patronSvc.checkAlerts()})
613 .then(redirectToAlertPanel);
618 $scope._show_dob = {};
619 $scope.show_dob = function (val) {
620 if ($scope.patron()) {
621 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
622 return $scope._show_dob[$scope.patron().id()];
624 return !egCore.env.aous['circ.obscure_dob'];
627 $scope.obscure_dob = function() {
628 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
630 $scope.now_show_dob = function() {
631 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
632 $scope.show_dob() : true;
635 $scope.patron = function() { return patronSvc.current }
636 $scope.patron_stats = function() { return patronSvc.patron_stats }
637 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
639 $scope.print_address = function(addr) {
642 template : 'patron_address',
644 patron : egCore.idl.toHash(patronSvc.current),
645 address : egCore.idl.toHash(addr)
650 $scope.toggle_expand_summary = function() {
651 if ($scope.collapsePatronSummary) {
652 $scope.collapsePatronSummary = false;
653 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
655 $scope.collapsePatronSummary = true;
656 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
660 // always expand the patron summary in the search UI, regardless
661 // of stored preference.
662 $scope.collapse_summary = function() {
663 return $scope.tab != 'search' && $scope.collapsePatronSummary;
666 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
667 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
670 .controller('PatronBarcodeSearchCtrl',
671 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
672 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
673 $scope.selectMe = true; // focus text input
674 patronSvc.clearPrimary(); // clear the default user
676 // jump to the patron checkout UI
677 function loadPatron(user_id) {
679 .path('/circ/patron/' + user_id + '/checkout')
680 .search('card', $scope.args.barcode);
683 // create an opt-in=yes response for the loaded user
684 function createOptIn(user_id) {
687 'open-ils.actor.user.org_unit_opt_in.create',
688 egCore.auth.token(), user_id).then(function(resp) {
689 if (evt = egCore.evt.parse(resp)) return alert(evt);
695 $scope.submitBarcode = function(args) {
696 $scope.bcNotFound = null;
697 if (!args.barcode) return;
699 // blur so next time it's set to true it will re-apply select()
700 $scope.selectMe = false;
707 'open-ils.actor.get_barcodes',
708 egCore.auth.token(), egCore.auth.user().ws_ou(),
709 'actor', args.barcode)
711 .then(function(resp) { // get_barcodes
713 if (evt = egCore.evt.parse(resp)) {
718 if (!resp || !resp[0]) {
719 $scope.bcNotFound = args.barcode;
720 $scope.selectMe = true;
724 // see if an opt-in request is needed
725 user_id = resp[0].id;
726 return egCore.net.request(
728 'open-ils.actor.user.org_unit_opt_in.check',
729 egCore.auth.token(), user_id);
731 }).then(function(optInResp) { // opt_in_check
733 if (evt = egCore.evt.parse(optInResp)) {
738 if (optInResp == 1) {
739 // opt-in handled or not needed
740 return loadPatron(user_id);
743 // opt-in needed, show the opt-in dialog
744 egUser.get(user_id, {useFields : []})
746 .then(function(user) { // retrieve user
747 egConfirmDialog.open(
748 egCore.strings.OPT_IN_DIALOG, '',
749 { org : egCore.org.get(user.home_ou()),
751 ok : function() { createOptIn(user.id()) },
752 cancel : function() {}
762 * Manages patron search
764 .controller('PatronSearchCtrl',
765 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
766 '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
767 function($scope, $q, $routeParams, $timeout, $window, $location, egCore,
768 $filter, egUser, patronSvc , egGridDataProvider , $document) {
770 $scope.initTab('search');
771 $scope.focusMe = true;
772 $scope.searchArgs = {
773 // default to searching globally
774 home_ou : egCore.org.tree()
777 // last used patron search form element
780 $scope.gridControls = {
781 activateItem : function(item) {
782 $location.path('/circ/patron/' + item.id() + '/checkout');
784 selectedItems : function() {return []}
787 // Handle URL-encoded searches
788 if ($location.search().search) {
789 patronSvc.urlSearch = {search : JSON2js($location.search().search)};
791 // why the double-JSON encoded sort?
792 patronSvc.urlSearch.sort =
793 JSON2js(patronSvc.urlSearch.search.search_sort);
794 delete patronSvc.urlSearch.search.search_sort;
798 if (patronSvc.lastSearch) {
799 propagate = patronSvc.lastSearch.search;
800 } else if (patronSvc.urlSearch) {
801 propagate = patronSvc.urlSearch.search;
804 if (egCore.env.pgt) {
805 $scope.profiles = egCore.env.pgt.list;
807 egCore.pcrud.search('pgt', {parent : null},
808 {flesh : -1, flesh_fields : {pgt : ['children']}}
811 egCore.env.absorbTree(tree, 'pgt')
812 $scope.profiles = egCore.env.pgt.list;
818 // populate the search form with our cached / preexisting search info
819 angular.forEach(propagate, function(val, key) {
820 if (key == 'profile')
821 val.value = $scope.profiles.filter(function(p) { p.id() == val.value })[0];
822 if (key == 'home_ou')
823 val.value = egCore.org.get(val.value);
824 $scope.searchArgs[key] = val.value;
828 var provider = egGridDataProvider.instance({});
831 function() {return $scope.gridControls.selectedItems()},
834 patronSvc.setPrimary(null, list[0]);
839 provider.get = function(offset, count) {
840 var deferred = $q.defer();
843 if (patronSvc.urlSearch) {
844 fullSearch = patronSvc.urlSearch;
845 // enusre the urlSearch only runs once.
846 delete patronSvc.urlSearch;
850 var search = compileSearch($scope.searchArgs);
851 if (Object.keys(search) == 0) return $q.when();
853 var home_ou = search.home_ou;
854 delete search.home_ou;
855 var inactive = search.inactive;
856 delete search.inactive;
860 sort : compileSort(),
866 fullSearch.count = count;
867 fullSearch.offset = offset;
869 if (patronSvc.lastSearch) {
870 // search repeated, return the cached results
871 if (angular.equals(fullSearch, patronSvc.lastSearch)) {
872 console.log('patron search returning ' +
873 patronSvc.patrons.length + ' cached results');
875 // notify has to happen after returning the promise
878 angular.forEach(patronSvc.patrons, function(user) {
879 deferred.notify(user);
884 return deferred.promise;
888 patronSvc.lastSearch = fullSearch;
890 if (fullSearch.search.id) {
891 // search by user id performs a direct ID lookup
892 var userId = fullSearch.search.id.value;
895 egUser.get(userId).then(function(user) {
896 patronSvc.localFlesh(user);
897 patronSvc.patrons = [user];
898 deferred.notify(user);
903 return deferred.promise;
906 patronSvc.patrons = [];
909 'open-ils.actor.patron.search.advanced.fleshed',
916 egUser.defaultFleshFields,
920 function() { deferred.resolve() },
923 patronSvc.localFlesh(user); // inline
924 patronSvc.patrons.push(user);
925 deferred.notify(user);
929 return deferred.promise;
932 $scope.patronSearchGridProvider = provider;
934 // determine the tree depth of the profile group
935 $scope.pgt_depth = function(grp) {
937 while (grp = egCore.env.pgt.map[grp.parent()]) d++;
941 $scope.clearForm = function () {
942 $scope.searchArgs={};
943 if (lastFormElement) lastFormElement.focus();
946 $scope.applyShowExtras = function($event, bool) {
948 $scope.showExtras = true;
949 egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
951 $scope.showExtras = false;
952 egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
954 if (lastFormElement) lastFormElement.focus();
955 $event.preventDefault();
958 egCore.hatch.getItem('eg.circ.patron.search.show_extras')
959 .then(function(val) {$scope.showExtras = val});
961 // map form arguments into search params
962 function compileSearch(args) {
964 angular.forEach(args, function(val, key) {
966 if (key == 'profile' && args.profile) {
967 search.profile = {value : args.profile.id(), group : 0};
968 } else if (key == 'home_ou' && args.home_ou) {
969 search.home_ou = args.home_ou.id(); // passed separately
970 } else if (key == 'inactive') {
971 search.inactive = val;
973 search[key] = {value : val, group : 0};
975 if (key.match(/phone|ident/)) {
976 search[key].group = 2;
978 if (key.match(/street|city|state|post_code/)) {
979 search[key].group = 1;
980 } else if (key == 'card') {
981 search[key].group = 3
989 function compileSort() {
991 if (!provider.sort.length) {
994 "first_given_name ASC",
995 "second_given_name ASC",
1004 if (angular.isObject(sortdef)) {
1005 var name = Object.keys(sortdef)[0];
1006 var dir = sortdef[name];
1007 sort.push(name + ' ' + dir);
1017 $scope.setLastFormElement = function() {
1018 lastFormElement = $document[0].activeElement;
1021 // search form submit action; tells the results grid to
1023 $scope.search = function(args) { // args === $scope.searchArgs
1024 if (args && Object.keys(args).length)
1025 $scope.gridControls.refresh();
1026 if (lastFormElement) lastFormElement.focus();
1029 // TODO: move this into the (forthcoming) grid row activate action
1030 $scope.onPatronDblClick = function($event, user) {
1031 $location.path('/circ/patron/' + user.id() + '/checkout');
1034 if (patronSvc.urlSearch) {
1035 // force the grid to load the url-based search on page load
1044 .controller('PatronMessagesCtrl',
1045 ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
1046 function($scope , $q , $routeParams, egCore , $modal , patronSvc , egCirc) {
1047 $scope.initTab('messages', $routeParams.id);
1048 var usr_id = $routeParams.id;
1050 // setup date filters
1051 var start = new Date(); // now - 1 year
1052 start.setFullYear(start.getFullYear() - 1),
1055 end_date : new Date()
1058 function date_range() {
1059 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1060 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1061 var today = new Date().toISOString().replace(/T.*/,'');
1062 if (end == today) end = 'now';
1063 return [start, end];
1068 var activeGrid = $scope.activeGridControls = {
1069 setSort : function() {
1070 return ['set_date'];
1072 setQuery : function() {
1077 {stop_date : {'>' : 'now'}}
1083 var archiveGrid = $scope.archiveGridControls = {
1084 setSort : function() {
1085 return ['set_date'];
1087 setQuery : function() {
1090 stop_date : {'<=' : 'now'},
1091 set_date : {between : date_range()}
1096 $scope.removePenalty = function(selected) {
1097 // the grid stores flattened penalties. Fetch penalty objects first
1099 var ids = selected.map(function(s){ return s.id });
1100 egCore.pcrud.search('ausp',
1102 {atomic : true, authoritative : true}
1105 ).then(function(penalties) {
1106 return egCore.pcrud.remove(penalties);
1108 // then refresh the grid
1109 }).then(function() {
1110 activeGrid.refresh();
1114 $scope.archivePenalty = function(selected) {
1115 // the grid stores flattened penalties. Fetch penalty objects first
1117 var ids = selected.map(function(s){ return s.id });
1118 egCore.pcrud.search('ausp',
1120 {atomic : true, authoritative : true}
1123 ).then(function(penalties) {
1124 angular.forEach(penalties, function(p){ p.stop_date('now') });
1125 return egCore.pcrud.update(penalties);
1127 // then refresh the grid
1128 }).then(function() {
1129 activeGrid.refresh();
1130 archiveGrid.refresh();
1134 // leverage egEnv for caching
1135 function fetchPenaltyTypes() {
1137 return $q.when(egCore.env.csp.list);
1138 return egCore.pcrud.search(
1139 // id <= 100 are reserved for system use
1140 'csp', {id : {'>': 100}}, {}, {atomic : true})
1141 .then(function(penalties) {
1142 egCore.env.absorbList(penalties, 'csp');
1147 $scope.createPenalty = function() {
1148 egCirc.create_penalty(usr_id).then(function() {
1149 activeGrid.refresh();
1150 // force a refresh of the user, since they may now
1151 // have blocking penalties, etc.
1152 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1156 $scope.editPenalty = function(selected) {
1157 if (selected.length == 0) return;
1159 // grab the penalty from the user object
1160 var penalty = patronSvc.current.standing_penalties().filter(
1161 function(p) {return p.id() == selected[0].id})[0];
1163 egCirc.edit_penalty(penalty).then(function() {
1164 activeGrid.refresh();
1165 // force a refresh of the user, since they may now
1166 // have blocking penalties, etc.
1167 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1174 * Credentials tester
1176 .controller('PatronVerifyCredentialsCtrl',
1177 ['$scope','$routeParams','$location','egCore',
1178 function($scope, $routeParams , $location , egCore) {
1179 $scope.verified = null;
1180 $scope.focusMe = true;
1182 // called with a patron, pre-populate the form args
1183 $scope.initTab('other', $routeParams.id).then(
1185 if ($routeParams.id && $scope.patron()) {
1186 $scope.prepop = true;
1187 $scope.username = $scope.patron().usrname();
1188 $scope.barcode = $scope.patron().card().barcode();
1190 $scope.username = '';
1191 $scope.barcode = '';
1192 $scope.password = '';
1197 // verify login credentials
1198 $scope.verify = function() {
1199 $scope.verified = null;
1200 $scope.notFound = false;
1204 'open-ils.actor.verify_user_password',
1205 egCore.auth.token(), $scope.barcode,
1206 $scope.username, hex_md5($scope.password || '')
1208 ).then(function(resp) {
1209 $scope.focusMe = true;
1210 if (evt = egCore.evt.parse(resp)) {
1212 } else if (resp == 1) {
1213 $scope.verified = true;
1215 $scope.verified = false;
1220 // load the main patron UI for the provided username or barcode
1221 $scope.load = function($event) {
1222 $scope.notFound = false;
1223 $scope.verified = null;
1227 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1228 egCore.auth.token(), $scope.barcode, $scope.username
1230 ).then(function(resp) {
1233 $location.path('/circ/patron/' + resp + '/checkout');
1237 // something went wrong...
1238 $scope.focusMe = true;
1239 if (evt = egCore.evt.parse(resp)) {
1240 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1241 $scope.notFound = true;
1250 // load() button sits within the verify form.
1251 // avoid submitting the verify() form action on load()
1252 $event.preventDefault();
1256 .controller('PatronAlertsCtrl',
1257 ['$scope','$routeParams','$location','egCore','patronSvc',
1258 function($scope, $routeParams , $location , egCore , patronSvc) {
1260 $scope.initTab('other', $routeParams.id)
1262 $scope.patronExpired = patronSvc.patronExpired;
1263 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1264 $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1265 $scope.invalidAddresses = patronSvc.invalidAddresses;
1270 .controller('PatronNotesCtrl',
1271 ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1272 function($scope, $routeParams , $location , egCore , patronSvc , $modal) {
1273 $scope.initTab('other', $routeParams.id);
1274 var usr_id = $routeParams.id;
1277 function refreshPage() {
1279 egCore.pcrud.search('aun',
1281 {flesh : 1, flesh_fields : {aun : ['creator']}},
1282 {authoritative : true})
1283 .then(null, null, function(note) {
1284 $scope.notes.push(note);
1288 // open the new-note dialog and create the note
1289 $scope.newNote = function() {
1291 templateUrl: './circ/patron/t_new_note_dialog',
1293 ['$scope', '$modalInstance',
1294 function($scope, $modalInstance) {
1295 $scope.focusNote = true;
1297 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1298 $scope.cancel = function () { $modalInstance.dismiss() }
1302 if (!args.value) return;
1303 var note = new egCore.idl.aun();
1305 note.title(args.title);
1306 note.value(args.value);
1307 note.pub(args.pub ? 't' : 'f');
1308 note.creator(egCore.auth.user().id());
1309 egCore.pcrud.create(note).then(function() {refreshPage()});
1314 // delete the selected note
1315 $scope.deleteNote = function(note) {
1316 egCore.pcrud.remove(note).then(function() {refreshPage()});
1319 // print the selected note
1320 $scope.printNote = function(note) {
1321 var hash = egCore.idl.toHash(note);
1322 hash.usr = egCore.idl.toHash($scope.patron());
1323 egCore.print.print({
1324 context : 'default',
1325 template : 'patron_note',
1326 scope : {note : hash}
1330 // perform the initial note fetch
1334 .controller('PatronGroupCtrl',
1335 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1336 'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1337 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1338 patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1340 var usr_id = $routeParams.id;
1342 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1344 var grid = $scope.gridControls = {
1345 activateItem : function(item) {
1346 $location.path('/circ/patron/' + item.id + '/checkout');
1348 itemRetrieved : function(item) {
1350 if (item.id == patronSvc.current.id()) {
1351 item.stats = patronSvc.patron_stats;
1354 // flesh stats for other group members
1355 patronSvc.getUserStats(item.id).then(function(stats) {
1357 $scope.totals.total_out += stats.checkouts.total_out;
1358 $scope.totals.overdue += stats.checkouts.overdue;
1362 setSort : function() {
1363 return ['create_date'];
1367 $scope.initTab('other', $routeParams.id)
1368 .then(function(redirect) {
1369 // if we are redirecting to the alerts page, avoid updating the
1371 if (redirect) return;
1372 // let initTab() fetch the user first so we can know the usrgroup
1375 usrgroup : patronSvc.current.usrgroup(),
1378 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1381 $scope.removeFromGroup = function(selected) {
1383 angular.forEach(selected, function(user) {
1384 console.debug('removing user ' + user.id + ' from group');
1389 'open-ils.actor.usergroup.new',
1390 egCore.auth.token(), user.id, true
1395 $q.all(promises).then(function() {grid.refresh()});
1398 function addUserToGroup(user) {
1399 user.usrgroup(patronSvc.current.usrgroup());
1400 user.ischanged(true);
1403 'open-ils.actor.patron.update',
1404 egCore.auth.token(), user
1406 ).then(function() {grid.refresh()});
1409 // fetch each user ("selected" has flattened users)
1410 // update the usrgroup, then update the user object
1411 // After all updates are complete, refresh the grid.
1412 function moveUsersToGroup(target_user, selected) {
1415 angular.forEach(selected, function(user) {
1417 egCore.pcrud.retrieve('au', user.id)
1419 u.usrgroup(target_user.usrgroup());
1421 return egCore.net.request(
1423 'open-ils.actor.patron.update',
1424 egCore.auth.token(), u
1430 $q.all(promises).then(function() {grid.refresh()});
1433 function showMoveToGroupConfirm(barcode, selected, outbound) {
1436 egCore.pcrud.search('ac', {barcode : barcode})
1438 // fetch the fleshed user
1439 .then(function(card) {
1441 if (!card) return; // TODO: warn user
1443 egCore.pcrud.retrieve('au', card.usr())
1444 .then(function(user) {
1447 templateUrl: './circ/patron/t_move_to_group_dialog',
1449 '$scope','$modalInstance',
1450 function($scope , $modalInstance) {
1452 $scope.selected = selected;
1453 $scope.outbound = outbound;
1455 function(count) { $modalInstance.close() }
1457 function () { $modalInstance.dismiss() }
1460 }).result.then(function() {
1462 moveUsersToGroup(user, selected);
1464 addUserToGroup(user);
1471 // selected == move selected patrons to another patron's group
1472 // !selected == patron from a different group moves into our group
1473 function moveToGroup(selected, outbound) {
1474 egPromptDialog.open(
1475 egCore.strings.GROUP_ADD_USER, '',
1476 {ok : function(value) {
1478 showMoveToGroupConfirm(value, selected, outbound);
1483 $scope.moveToGroup = function() { moveToGroup([], false) };
1484 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1486 $scope.cloneUser = function(selected) {
1487 if (!selected.length) return;
1488 var url = $location.absUrl().replace(
1490 '/patron/register/clone/' + selected[0].id);
1491 $window.open(url, '_blank').focus();
1494 $scope.retrieveSelected = function(selected) {
1495 if (!selected.length) return;
1496 angular.forEach(selected, function(usr) {
1497 $timeout(function() {
1498 var url = $location.absUrl().replace(
1500 '/patron/' + usr.id + '/checkout');
1501 $window.open(url, '_blank')
1508 .controller('PatronStatCatsCtrl',
1509 ['$scope','$routeParams','$q','egCore','patronSvc',
1510 function($scope, $routeParams , $q , egCore , patronSvc) {
1511 $scope.initTab('other', $routeParams.id)
1512 .then(function(redirect) {
1513 // Entries for org-visible stat cats are fleshed. Any others
1514 // have to be fleshed within.
1517 angular.forEach(patronSvc.current.stat_cat_entries(),
1519 if (!angular.isObject(entry.stat_cat())) {
1520 to_flesh[entry.stat_cat()] = entry;
1525 if (!Object.keys(to_flesh).length) return;
1527 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1528 .then(null, null, function(cat) { // stream
1529 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1530 to_flesh[cat.id()].stat_cat(cat);
1535 .controller('PatronFetchLastCtrl',
1536 ['$scope','$location','egCore',
1537 function($scope , $location , egCore) {
1539 var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1540 if (id) return $location.path('/circ/patron/' + id + '/checkout');
1542 $scope.no_last = true;
1545 .controller('PatronTriggeredEventsCtrl',
1546 ['$scope','$routeParams','$location','egCore','patronSvc',
1547 function($scope, $routeParams, $location , egCore , patronSvc) {
1548 $scope.initTab('other', $routeParams.id);
1550 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1551 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1553 $scope.triggered_events_url = url;
1557 .controller('PatronPermsCtrl',
1558 ['$scope','$routeParams','$window','$location','egCore',
1559 function($scope , $routeParams , $window , $location , egCore) {
1560 $scope.initTab('other', $routeParams.id);
1562 var url = $location.absUrl().replace(
1563 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1565 url += '?usr=' + encodeURIComponent($routeParams.id);
1567 // user_edit does not load the session via cookie. It uses URL
1568 // params or xulG instead. Pass via xulG.
1570 ses : egCore.auth.token(),
1571 on_patron_save : function() {
1572 $scope.funcs.reload();
1576 $scope.user_perms_url = url;