4 * Search, checkout, items out, holds, bills, edit, etc.
7 angular.module('egPatronApp', ['ngRoute', 'ui.bootstrap', 'egUserBucketMod',
8 'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod', 'ngToast',
11 .config(['ngToastProvider', function(ngToastProvider) {
12 ngToastProvider.configure({
13 verticalPosition: 'bottom',
18 .factory("hasPermAt",function(){
22 .config(function($routeProvider, $locationProvider, $compileProvider) {
23 $locationProvider.html5Mode(true);
24 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
26 // data loaded at startup which only requires an authtoken goes
27 // here. this allows the requests to be run in parallel instead of
28 // waiting until startup has completed.
29 var resolver = {delay : ['egCore','egUser','hasPermAt', function(egCore , egUser , hasPermAt) {
31 // fetch the org settings we care about during egStartup
32 // and toss them into egCore.env as egCore.env.aous[name] = value.
33 // note: only load settings here needed by all tabs; load tab-
34 // specific settings from within their respective controllers
35 egCore.env.classLoaders.aous = function() {
36 return egCore.org.settings([
37 'ui.staff.require_initials.patron_info_notes',
38 'circ.do_not_tally_claims_returned',
41 'ui.circ.show_billing_tab_on_bills',
42 'circ.patron_expires_soon_warning',
43 'ui.circ.items_out.lost',
44 'ui.circ.items_out.longoverdue',
45 'ui.circ.items_out.claimsreturned'
46 ]).then(function(settings) {
47 // local settings are cached within egOrg. Caching them
48 // again in egEnv just simplifies the syntax for access.
49 egCore.env.aous = settings;
53 egCore.env.loadClasses.push('aous');
55 // app-globally modify the default flesh fields for
56 // fleshed user retrieval.
57 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
58 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
68 return egCore.startup.go().then(function(go_promise) {
69 // FIXME: the following is really just for PatronMessagesCtrl
70 // and PatronCtrl, so we could refactor to avoid calling it
71 // for every controller
72 return egCore.perm.hasPermFullPathAt('VIEW_USER')
73 .then(function(orgList) {
74 hasPermAt['VIEW_USER'] = orgList;
80 $routeProvider.when('/circ/patron/search', {
81 templateUrl: './circ/patron/t_search',
82 controller: 'PatronSearchCtrl',
86 $routeProvider.when('/circ/patron/bcsearch', {
87 templateUrl: './circ/patron/t_bcsearch',
88 controller: 'PatronBarcodeSearchCtrl',
92 $routeProvider.when('/circ/patron/credentials', {
93 templateUrl: './circ/patron/t_credentials',
94 controller: 'PatronVerifyCredentialsCtrl',
98 $routeProvider.when('/circ/patron/last', {
99 templateUrl: './circ/patron/t_last_patron',
100 controller: 'PatronFetchLastCtrl',
104 // the following require a patron ID
106 $routeProvider.when('/circ/patron/:id/alerts', {
107 templateUrl: './circ/patron/t_alerts',
108 controller: 'PatronAlertsCtrl',
112 $routeProvider.when('/circ/patron/:id/checkout', {
113 templateUrl: './circ/patron/t_checkout',
114 controller: 'PatronCheckoutCtrl',
118 $routeProvider.when('/circ/patron/:id/items_out', {
119 templateUrl: './circ/patron/t_items_out',
120 controller: 'PatronItemsOutCtrl',
124 $routeProvider.when('/circ/patron/:id/holds', {
125 templateUrl: './circ/patron/t_holds',
126 controller: 'PatronHoldsCtrl',
130 $routeProvider.when('/circ/patron/:id/holds/create', {
131 templateUrl: './circ/patron/t_holds_create',
132 controller: 'PatronHoldsCreateCtrl',
136 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
137 templateUrl: './circ/patron/t_holds',
138 controller: 'PatronHoldsCtrl',
142 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
143 templateUrl: './circ/patron/t_hold_details',
144 controller: 'PatronHoldDetailsCtrl',
148 $routeProvider.when('/circ/patron/:id/bills', {
149 templateUrl: './circ/patron/t_bills',
150 controller: 'PatronBillsCtrl',
154 $routeProvider.when('/circ/patron/:id/bill/:xact_id/:xact_tab', {
155 templateUrl: './circ/patron/t_xact_details',
156 controller: 'XactDetailsCtrl',
160 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
161 templateUrl: './circ/patron/t_bill_history',
162 controller: 'BillHistoryCtrl',
166 $routeProvider.when('/circ/patron/:id/messages', {
167 templateUrl: './circ/patron/t_messages',
168 controller: 'PatronMessagesCtrl',
172 $routeProvider.when('/circ/patron/:id/edit', {
173 templateUrl: './circ/patron/t_edit',
174 controller: 'PatronRegCtrl',
178 $routeProvider.when('/circ/patron/:id/credentials', {
179 templateUrl: './circ/patron/t_credentials',
180 controller: 'PatronVerifyCredentialsCtrl',
184 $routeProvider.when('/circ/patron/:id/triggered_events', {
185 templateUrl: './circ/patron/t_triggered_events',
186 controller: 'PatronTriggeredEventsCtrl',
190 $routeProvider.when('/circ/patron/:id/message_center', {
191 templateUrl: './circ/patron/t_message_center',
192 controller: 'PatronMessageCenterCtrl',
196 $routeProvider.when('/circ/patron/:id/edit_perms', {
197 templateUrl: './circ/patron/t_edit_perms',
198 controller: 'PatronPermsCtrl',
202 $routeProvider.when('/circ/patron/:id/group', {
203 templateUrl: './circ/patron/t_group',
204 controller: 'PatronGroupCtrl',
208 $routeProvider.when('/circ/patron/:id/stat_cats', {
209 templateUrl: './circ/patron/t_stat_cats',
210 controller: 'PatronStatCatsCtrl',
214 $routeProvider.when('/circ/patron/:id/surveys', {
215 templateUrl: './circ/patron/t_surveys',
216 controller: 'PatronSurveyCtrl',
220 $routeProvider.when('/circ/patron/:id/hold_subscriptions', {
221 templateUrl: './circ/patron/t_hold_subscriptions',
222 controller: 'HoldSubscriptionsCtrl',
226 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
230 * Manages tabbed patron view.
231 * This is the parent scope of all patron tab scopes.
234 .controller('PatronCtrl',
235 ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc','egCirc','hasPermAt',
236 function($scope, $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc , egCirc , hasPermAt) {
238 $scope.is_patron_edit = function() {
239 return Boolean($location.path().match(/patron\/\d+\/edit$/));
242 // To support the fixed position patron edit actions bar,
243 // its markup has to live outside the scope of the patron
244 // edit controller. Insert a scope blob here that can be
245 // modifed from within the patron edit controller.
246 $scope.edit_passthru = {};
248 // returns true if a redirect occurs
249 function redirectToAlertPanel() {
251 $scope.alert_penalties =
252 function() {return patronSvc.alert_penalties}
254 if (patronSvc.alertsShown()) return false;
256 // if the patron has any unshown alerts, show them now
257 if (patronSvc.hasAlerts &&
258 !$location.path().match(/alerts$/)) {
261 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
262 .search('card', null);
266 // no alert required. If the patron has fines and the show-bills
267 // OUS is applied, direct to the bills page.
268 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
269 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
270 && !$location.path().match(/bills$/)) {
272 $scope.tab = 'bills';
274 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
275 .search('card', null);
283 // called after each route-specified controller is instantiated.
284 // this doubles as a way to inform the top-level controller that
285 // egStartup.go() has completed, which means we are clear to
286 // fetch the patron, etc.
287 $scope.initTab = function(tab, patron_id) {
288 console.log('init tab ' + tab);
290 $scope.aous = egCore.env.aous;
291 $scope.auth_user_id = egCore.auth.user().id();
293 if (tab == 'search') {
294 egCirc.reset(); // clear out auto-override and auto-skip selections when switching patrons
298 $scope.patron_id = patron_id;
299 return patronSvc.setPrimary($scope.patron_id)
301 // the page title context label comes from the tab.
302 egCore.strings.setPageTitle(
303 egCore.strings.PAGE_TITLE_PATRON_NAME,
304 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
305 { lname : patronSvc.current.family_name(),
306 fname : patronSvc.current.first_given_name(),
307 mname : patronSvc.current.second_given_name()
311 .then(function() {return patronSvc.checkAlerts()})
312 .then(redirectToAlertPanel)
314 $scope.ident_type_name = $scope.patron().ident_type().name()
315 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
318 // No patron, use the tab name as the page title.
319 egCore.strings.setPageTitle(
320 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
325 $scope._show_dob = {};
326 $scope.show_dob = function (val) {
327 if ($scope.patron()) {
328 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
329 return $scope._show_dob[$scope.patron().id()];
331 return !egCore.env.aous['circ.obscure_dob'];
334 $scope.obscure_dob = function() {
335 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
337 $scope.now_show_dob = function() {
338 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
339 $scope.show_dob() : true;
342 $scope.patron = function() { return patronSvc.current }
343 $scope.visible_notes = function() {
344 var p = patronSvc.current;
346 var org_ids = hasPermAt['VIEW_USER'];
347 var filtered_notes = p.notes().filter(function(n) { return org_ids.indexOf(n.org_unit()) > -1; });
348 return filtered_notes;
352 $scope.patron_stats = function() { return patronSvc.patron_stats }
353 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
354 $scope.hasAlerts = function() { return patronSvc.hasAlerts }
355 $scope.isPatronExpired = function() { return patronSvc.patronExpired }
356 $scope.doesPatronExpireSoon = function() { return patronSvc.patronExpiresSoon }
358 $scope.print_address = function(addr) {
361 template : 'patron_address',
363 patron : egCore.idl.toHash(patronSvc.current),
364 address : egCore.idl.toHash(addr)
369 $scope.copy_address = function(addr) {
370 // Alas, navigator.clipboard is not yet supported in FF and others.
371 var lNode = document.querySelector('#patron-address-copy-' + addr.id());
373 // Un-hide the textarea just long enough to copy its data.
374 // Using node.style instead of ng-show/ng-hide in hopes it
375 // will be quicker, so the user never sees the textarea.
376 lNode.style.visibility = 'visible';
380 if (!document.execCommand('copy')) {
381 console.error('Copy command failed');
384 lNode.style.visibility = 'hidden';
387 $scope.toggle_expand_summary = function() {
388 if ($scope.collapsePatronSummary) {
389 $scope.collapsePatronSummary = false;
390 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
392 $scope.collapsePatronSummary = true;
393 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
397 // always expand the patron summary in the search UI, regardless
398 // of stored preference.
399 $scope.collapse_summary = function() {
400 return $scope.tab != 'search' && $scope.collapsePatronSummary;
403 function _purge_account(dest_usr,override) {
406 'open-ils.actor.user.delete' + (override ? '.override' : ''),
408 $scope.patron().id(),
410 ).then(function(resp){
411 if (evt = egCore.evt.parse(resp)) {
412 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
413 egConfirmDialog.open(
414 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
416 _purge_account(dest_usr,true);
423 location.href = egCore.env.basePath + '/circ/patron/search';
428 function _purge_account_with_destination(dest_barcode) {
429 egCore.pcrud.search('ac', {barcode : dest_barcode})
430 .then(function(card) {
432 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
434 _purge_account(card.usr());
439 $scope.purge_account = function() {
440 egConfirmDialog.open(
441 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
443 egConfirmDialog.open(
444 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
448 'open-ils.actor.user.has_work_perm_at',
449 egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
450 ).then(function(resp) {
451 var is_staff = resp.length > 0;
454 egCore.strings.PATRON_PURGE_STAFF_PROMPT,
455 null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
456 {ok : function(barcode) {_purge_account_with_destination(barcode)}}
468 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
469 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
472 .controller('PatronBarcodeSearchCtrl',
473 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc','$uibModal','$q',
474 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc , $uibModal , $q) {
475 $scope.selectMe = true; // focus text input
476 patronSvc.clearPrimary(); // clear the default user
478 // jump to the patron checkout UI
479 function loadPatron(user_id) {
480 egCore.audio.play('success.patron.by_barcode');
482 .path('/circ/patron/' + user_id + '/checkout')
483 .search('card', $scope.args.barcode);
484 patronSvc.search_barcode = $scope.args.barcode;
487 // create an opt-in=yes response for the loaded user
488 function createOptIn(user_id) {
491 'open-ils.actor.user.org_unit_opt_in.create',
492 egCore.auth.token(), user_id).then(function(resp) {
493 if (evt = egCore.evt.parse(resp)) return alert(evt);
499 $scope.submitBarcode = function(args) {
500 $scope.bcNotFound = null;
501 $scope.optInRestricted = false;
502 if (!args.barcode) return;
503 args.barcode = args.barcode.replace(/^\s/g,'');
504 args.barcode = args.barcode.replace(/\s$/g,'');
505 // blur so next time it's set to true it will re-apply select()
506 $scope.selectMe = false;
510 // given a scanned barcode, this function finds any matching users
511 // and handles multiple matches due to barcode completion
512 function handleBarcodeCompletion(scanned_barcode) {
513 var deferred = $q.defer();
517 'open-ils.actor.get_barcodes',
518 egCore.auth.token(), egCore.auth.user().ws_ou(),
519 'actor', scanned_barcode)
521 .then(function(resp) { // get_barcodes
523 if (evt = egCore.evt.parse(resp)) {
529 if (!resp || !resp[0]) {
530 $scope.bcNotFound = args.barcode;
531 $scope.selectMe = true;
532 egCore.audio.play('warning.patron.not_found');
537 if (resp.length == 1) {
538 // exactly one matching barcode: return it
540 user_id = resp[0].id;
542 // multiple matching barcodes: let the user pick one
543 var barcode_map = {};
546 var selected_barcode;
547 angular.forEach(resp, function(match) {
549 egUser.get(match.id, {useFields : ['home_ou']}).then(function(user) {
550 barcode_map[match.barcode] = user.id();
552 barcode: match.barcode,
553 title: user.first_given_name() + ' ' + user.family_name(),
554 org_name: user.home_ou().name(),
555 org_shortname: user.home_ou().shortname()
560 return $q.all(promises)
563 templateUrl: './circ/share/t_barcode_choice_dialog',
565 ['$scope', '$uibModalInstance',
566 function($scope, $uibModalInstance) {
567 $scope.matches = matches;
568 $scope.ok = function(barcode) {
569 $uibModalInstance.close();
570 selected_barcode = barcode;
572 $scope.cancel = function() {$uibModalInstance.dismiss()}
574 }).result.then(function() {
576 user_id = barcode_map[selected_barcode];
581 return deferred.promise;
584 // call our function to lookup matching users for the scanned barcode
585 handleBarcodeCompletion(args.barcode).then(function() {
587 // see if an opt-in request is needed
588 return egCore.net.request(
590 'open-ils.actor.user.org_unit_opt_in.check',
591 egCore.auth.token(), user_id
592 ).then(function(optInResp) { // opt_in_check
594 if (evt = egCore.evt.parse(optInResp)) {
599 if (optInResp == 2) {
600 // opt-in disallowed at this location by patron's home library
601 $scope.optInRestricted = true;
602 $scope.selectMe = true;
603 egCore.audio.play('warning.patron.opt_in_restricted');
607 if (optInResp == 1) {
608 // opt-in handled or not needed
609 return loadPatron(user_id);
612 // opt-in needed, show the opt-in dialog
613 egUser.get(user_id, {useFields : []})
615 .then(function(user) { // retrieve user
616 var org = egCore.org.get(user.home_ou());
617 egConfirmDialog.open(
618 egCore.strings.OPT_IN_DIALOG_TITLE,
619 egCore.strings.OPT_IN_DIALOG,
620 { family_name : user.family_name(),
621 first_given_name : user.first_given_name(),
622 org_name : org.name(),
623 org_shortname : org.shortname(),
624 ok : function() { createOptIn(user.id()) },
625 cancel : function() {}
636 * Manages patron search
638 .controller('PatronSearchCtrl',
639 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
640 '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
641 'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
642 function($scope, $q, $routeParams, $timeout, $window, $location, egCore , ngToast,
643 $filter, egUser, patronSvc , egGridDataProvider , $document , bucketSvc,
644 egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
646 angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
647 $scope.initTab('search');
649 $scope.gridControls = {
650 activateItem : function(item) {
651 $location.path('/circ/patron/' + item.id() + '/checkout');
653 selectedItems : function() { return [] }
656 $scope.bucketSvc = bucketSvc;
657 $scope.bucketSvc.fetchUserBuckets();
658 $scope.bucketSvc.fetchUserSubscriptions();
659 $scope.addToBucket = function(item, data, recs) {
660 if (recs.length == 0) return;
662 var failed_count = 0;
663 var promise = $q.when();
664 angular.forEach(recs,
666 var item = new egCore.idl.cubi();
667 item.bucket(data.id());
668 item.target_user(rec.id());
669 promise = promise.then(function() {
670 return egCore.net.request(
672 'open-ils.actor.container.item.create',
673 egCore.auth.token(), 'user', item, 1
676 function(){ added_count++ },
677 function(){ failed_count++ }
682 promise.then( function () {
683 if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
684 if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
688 var temp_scope = $scope;
689 $scope.openCreateBucketDialog = function() {
691 templateUrl: './circ/patron/bucket/t_bucket_create',
694 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
695 $scope.focusMe = true;
696 $scope.ok = function(args) { $uibModalInstance.close(args) }
697 $scope.cancel = function () { $uibModalInstance.dismiss() }
699 }).result.then(function (args) {
700 if (!args || !args.name) return;
701 bucketSvc.createBucket(args.name, args.desc).then(
704 $scope.bucketSvc.fetchBucket(id).then(function (b) {
708 $scope.gridControls.selectedItems()
710 $scope.bucketSvc.fetchUserBuckets(true);
719 function() {return $scope.gridControls.selectedItems()},
722 patronSvc.setPrimary(null, list[0]);
727 $scope.need_one_selected = function() {
728 var items = $scope.gridControls.selectedItems();
729 return (items.length > 0) ? false : true;
731 $scope.need_two_selected = function() {
732 var items = $scope.gridControls.selectedItems();
733 return (items.length == 2) ? false : true;
735 $scope.merge_patrons = function() {
736 var items = $scope.gridControls.selectedItems();
737 if (items.length != 2) return false;
740 angular.forEach(items, function(i) {
741 patron_ids.push(i.id());
743 egPatronMerge.do_merge(patron_ids).then(
745 // ensure that we're not drawing from cached
746 // resuts, as a successful merge just deleted a
748 delete patronSvc.lastSearch;
749 $scope.gridControls.refresh();
752 if (evt && evt.textcode == 'MERGE_SELF_NOT_ALLOWED') {
753 ngToast.warning(egCore.strings.MERGE_SELF_NOT_ALLOWED);
764 .controller('PatronMessagesCtrl',
765 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc','hasPermAt',
766 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc , hasPermAt ) {
767 $scope.initTab('messages', $routeParams.id);
768 var usr_id = $routeParams.id;
769 var org_ids = hasPermAt.VIEW_USER;
771 // setup date filters
772 var start = new Date(); // now - 1 year
773 start.setFullYear(start.getFullYear() - 1),
776 end_date : new Date()
779 function date_range() {
780 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
781 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
782 var today = new Date().toISOString().replace(/T.*/,'');
783 if (end == today) end = 'now';
789 var activeGrid = $scope.activeGridControls = {
790 setSort : function() {
791 return [{'create_date' : 'DESC'}];
793 setQuery : function() {
799 {stop_date : {'>' : 'now'}}
805 var archiveGrid = $scope.archiveGridControls = {
806 setSort : function() {
807 return [{'create_date' : 'DESC'}];
809 watchQuery : function() {
813 stop_date : {'<=' : 'now'},
814 create_date : {between : date_range()}
819 $scope.test_for_disable_remove_penalty = function() {
820 var selected = $scope.activeGridControls.selectedItems();
821 var found_pub_and_read_and_not_deleted = false;
822 angular.forEach(selected, function(s) {
823 if (Boolean(s.pub == 't') && Boolean(s.read_date) && !Boolean(s.deleted == 't')) {
824 found_pub_and_read_and_not_deleted = true;
827 return found_pub_and_read_and_not_deleted;
830 $scope.removePenalty = function(selected) {
831 if (selected.length == 0) return;
833 // TODO: need confirmation dialog
836 // figure out the view components
839 angular.forEach(selected, function(s) {
840 if (s.aum_id) { aum_ids.push(s.aum_id); }
841 if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
844 // fetch all of them since trying to pull them
845 // off of patronSvc.current isn't reliable
846 if (ausp_ids.length > 0) {
848 egCore.pcrud.search('ausp',
850 {atomic : true, authoritative : true}
851 ).then(function(penalties) {
852 return egCore.pcrud.remove(penalties);
856 if (aum_ids.length > 0) {
858 egCore.pcrud.search('aum',
860 {atomic : true, authoritative : true}
861 ).then(function(messages) {
862 return egCore.pcrud.remove(messages);
866 $q.all(promises).then(function() {
867 activeGrid.refresh();
868 archiveGrid.refresh();
869 // force a refresh of the user
870 patronSvc.setPrimary(patronSvc.current.id(), null, true);
874 $scope.archivePenalty = function(selected) {
875 if (selected.length == 0) return;
877 // TODO: need confirmation dialog
880 // figure out the view components
883 angular.forEach(selected, function(s) {
884 if (s.aum_id) { aum_ids.push(s.aum_id); }
885 if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
888 // fetch all of them since trying to pull them
889 // off of patronSvc.current isn't reliable
890 if (ausp_ids.length > 0) {
892 egCore.pcrud.search('ausp',
894 {atomic : true, authoritative : true}
895 ).then(function(penalties) {
896 angular.forEach(penalties, function(p) {
899 return egCore.pcrud.update(penalties);
903 if (aum_ids.length > 0) {
905 egCore.pcrud.search('aum',
907 {atomic : true, authoritative : true}
908 ).then(function(messages) {
909 angular.forEach(messages, function(m) {
912 return egCore.pcrud.update(messages);
916 $q.all(promises).then(function() {
917 activeGrid.refresh();
918 archiveGrid.refresh();
919 // force a refresh of the user
920 patronSvc.setPrimary(patronSvc.current.id(), null, true);
924 // leverage egEnv for caching
925 function fetchPenaltyTypes() {
927 return $q.when(egCore.env.csp.list);
928 return egCore.pcrud.search(
929 // id <= 100 are reserved for system use
930 'csp', {id : {'>': 100}}, {}, {atomic : true})
931 .then(function(penalties) {
932 egCore.env.absorbList(penalties, 'csp');
937 $scope.createPenalty = function() {
938 egCirc.create_penalty(usr_id).then(function() {
939 activeGrid.refresh();
940 // force a refresh of the user, since they may now
941 // have blocking penalties, etc.
942 patronSvc.setPrimary(patronSvc.current.id(), null, true);
946 $scope.editPenalty = function(selected) {
947 if (selected.length == 0) return;
950 // figure out the view components
951 var aum_ids = []; var aum_objs = {};
952 var ausp_ids = []; var ausp_objs = {};
954 angular.forEach(selected, function(s) {
955 if (s.aum_id) { aum_ids.push(s.aum_id); }
956 if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
957 pairs.push( { aum_id : s.aum_id, ausp_id : s.ausp_id } );
960 // fetch all of them since trying to pull them
961 // off of patronSvc.current isn't reliable
962 // (we want deleted user messages too)
963 if (ausp_ids.length > 0) {
965 egCore.pcrud.search('ausp',
967 {atomic : true, authoritative : true}
968 ).then(function(penalties) {
969 angular.forEach(penalties, function(p) {
970 ausp_objs[p.id()] = p;
976 if (aum_ids.length > 0) {
978 egCore.pcrud.search('aum',
985 {atomic : true, authoritative : true}
986 ).then(function(messages) {
987 angular.forEach(messages, function(m) {
988 aum_objs[m.id()] = m;
994 $q.all(promises).then(function() {
995 angular.forEach(pairs, function(pair) {
996 egCirc.edit_penalty(ausp_objs[pair.ausp_id],aum_objs[pair.aum_id]).then(function() {
997 activeGrid.refresh();
998 // force a refresh of the user, since they may now
999 // have blocking penalties, etc.
1000 patronSvc.setPrimary(patronSvc.current.id(), null, true);
1009 * Credentials tester
1011 .controller('PatronVerifyCredentialsCtrl',
1012 ['$scope','$routeParams','$location','egCore',
1013 function($scope, $routeParams , $location , egCore) {
1014 $scope.verified = null;
1015 $scope.focusMe = true;
1017 // called with a patron, pre-populate the form args
1018 $scope.initTab('other', $routeParams.id).then(
1020 if ($routeParams.id && $scope.patron()) {
1021 $scope.prepop = true;
1022 $scope.username = $scope.patron().usrname();
1023 $scope.barcode = $scope.patron().card().barcode();
1025 $scope.username = '';
1026 $scope.barcode = '';
1027 $scope.password = '';
1032 // verify login credentials
1033 $scope.verify = function() {
1034 $scope.verified = null;
1035 $scope.notFound = false;
1039 'open-ils.actor.verify_user_password',
1040 egCore.auth.token(), $scope.barcode,
1041 $scope.username, hex_md5($scope.password || '')
1043 ).then(function(resp) {
1044 $scope.focusMe = true;
1045 if (evt = egCore.evt.parse(resp)) {
1047 } else if (resp == 1) {
1048 $scope.verified = true;
1050 $scope.verified = false;
1055 // load the main patron UI for the provided username or barcode
1056 $scope.load = function($event) {
1057 $scope.notFound = false;
1058 $scope.verified = null;
1062 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1063 egCore.auth.token(), $scope.barcode, $scope.username
1065 ).then(function(resp) {
1068 $location.path('/circ/patron/' + resp + '/checkout');
1072 // something went wrong...
1073 $scope.focusMe = true;
1074 if (evt = egCore.evt.parse(resp)) {
1075 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1076 $scope.notFound = true;
1085 // load() button sits within the verify form.
1086 // avoid submitting the verify() form action on load()
1087 $event.preventDefault();
1091 .controller('PatronAlertsCtrl',
1092 ['$scope','$routeParams','$location','egCore','patronSvc',
1093 function($scope, $routeParams , $location , egCore , patronSvc) {
1095 $scope.initTab('other', $routeParams.id)
1097 $scope.patronExpired = patronSvc.patronExpired;
1098 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1099 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1100 $scope.invalidAddresses = patronSvc.invalidAddresses;
1105 .controller('HoldSubscriptionsCtrl',
1106 ['$scope','$q','$routeParams','$location','egCore','patronSvc','bucketSvc','egGridDataProvider','egConfirmDialog','$timeout','$window',
1107 function($scope, $q , $routeParams , $location , egCore , patronSvc, bucketSvc, egGridDataProvider, egConfirmDialog, $timeout, $window) {
1109 $scope.initTab('other', $routeParams.id);
1111 $scope.bucket_ids = [];
1112 $scope.bucket_items = [];
1113 $scope.buckets = [];
1115 $scope.gridControls = {
1116 activateItem : function (item) {
1117 var url = $location.absUrl().replace(
1118 /\/circ\/patron\/.*/,
1119 '/cat/bucket/batch_hold/view/' + item.id());
1120 $window.open(url, '_blank').focus();
1124 $scope.gridDataProvider = egGridDataProvider.instance({
1125 get : function(offset, count) {
1126 return this.arrayNotifier($scope.buckets, offset, count);
1130 function fetchSubscriptions() {
1131 $scope.bucket_ids = [];
1132 $scope.bucket_items = [];
1133 $scope.buckets = [];
1134 egCore.pcrud.search('cubi',
1135 { target_user : $routeParams.id }
1138 if ($scope.bucket_ids.length > 0) {
1139 egCore.pcrud.search('cub',
1140 { id : $scope.bucket_ids, btype : 'hold_subscription' }
1142 function() { $scope.gridControls.refresh() },
1145 $scope.buckets.push(b);
1146 b.items( $scope.bucket_items.filter(i => i.bucket() == b.id()) );
1150 $scope.gridControls.refresh();
1155 $scope.bucket_ids.push(i.bucket());
1156 $scope.bucket_items.push(i);
1161 $scope.removeSubscriptions = function (buckets) {
1162 return egConfirmDialog.open(
1163 egCore.strings.REMOVE_HOLD_SUBSCRIPTIONS,'',{}
1164 ).result.then(function() {
1167 angular.forEach(buckets, function(b) {
1168 angular.forEach(b.items(), function (i) {
1169 promises.push(bucketSvc.detachUser(i.id()));
1173 $q.all(promises).then(fetchSubscriptions);
1177 $timeout(fetchSubscriptions);
1181 .controller('PatronGroupCtrl',
1182 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1183 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1184 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1185 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1187 var usr_id = $routeParams.id;
1189 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1191 var grid = $scope.gridControls = {
1192 activateItem : function(item) {
1193 $location.path('/circ/patron/' + item.id + '/checkout');
1195 itemRetrieved : function(item) {
1197 if (item.id == patronSvc.current.id()) {
1198 item.stats = patronSvc.patron_stats;
1201 // flesh stats for other group members
1202 patronSvc.getUserStats(item.id).then(function(stats) {
1204 $scope.totals.total_out += stats.checkouts.total_out;
1205 $scope.totals.overdue += stats.checkouts.overdue;
1209 setSort : function() {
1210 return ['create_date'];
1212 watchQuery: function() {
1213 if (patronSvc.current) {
1215 usrgroup : patronSvc.current.usrgroup(),
1223 $scope.initTab('other', $routeParams.id)
1224 .then(function(redirect) {
1225 // if we are redirecting to the alerts page, avoid updating the
1227 if (redirect) return;
1228 // let initTab() fetch the user first so we can know the usrgroup
1229 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1232 $scope.removeFromGroup = function(selected) {
1234 angular.forEach(selected, function(user) {
1235 console.debug('removing user ' + user.id + ' from group');
1240 'open-ils.actor.usergroup.new',
1241 egCore.auth.token(), user.id, true
1246 $q.all(promises).then(function() {grid.refresh()});
1249 function addUserToGroup(user) {
1250 user.usrgroup(patronSvc.current.usrgroup());
1251 user.ischanged(true);
1254 'open-ils.actor.patron.update',
1255 egCore.auth.token(), user
1257 ).then(function() {grid.refresh()});
1260 // fetch each user ("selected" has flattened users)
1261 // update the usrgroup, then update the user object
1262 // After all updates are complete, refresh the grid.
1263 function moveUsersToGroup(target_user, selected) {
1266 angular.forEach(selected, function(user) {
1268 egCore.pcrud.retrieve('au', user.id)
1270 u.usrgroup(target_user.usrgroup());
1272 return egCore.net.request(
1274 'open-ils.actor.patron.update',
1275 egCore.auth.token(), u
1281 $q.all(promises).then(function() {grid.refresh()});
1284 function showMoveToGroupConfirm(barcode, selected, outbound) {
1287 egCore.pcrud.search('ac', {barcode : barcode})
1289 // fetch the fleshed user
1290 .then(function(card) {
1292 if (!card) return; // TODO: warn user
1294 egCore.pcrud.retrieve('au', card.usr())
1295 .then(function(user) {
1298 templateUrl: './circ/patron/t_move_to_group_dialog',
1301 '$scope','$uibModalInstance',
1302 function($scope , $uibModalInstance) {
1304 $scope.selected = selected;
1305 $scope.outbound = outbound;
1307 function(count) { $uibModalInstance.close() }
1309 function () { $uibModalInstance.dismiss() }
1312 }).result.then(function() {
1314 moveUsersToGroup(user, selected);
1316 addUserToGroup(user);
1323 // selected == move selected patrons to another patron's group
1324 // !selected == patron from a different group moves into our group
1325 function moveToGroup(selected, outbound) {
1326 egPromptDialog.open(
1327 egCore.strings.GROUP_ADD_USER, '',
1328 {ok : function(value) {
1330 showMoveToGroupConfirm(value, selected, outbound);
1335 $scope.moveToGroup = function() { moveToGroup([], false) };
1336 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1338 $scope.cloneUser = function(selected) {
1339 if (!selected.length) return;
1340 var url = $location.absUrl().replace(
1342 '/patron/register/clone/' + selected[0].id);
1343 $window.open(url, '_blank').focus();
1346 $scope.retrieveSelected = function(selected) {
1347 if (!selected.length) return;
1348 angular.forEach(selected, function(usr) {
1349 $timeout(function() {
1350 var url = $location.absUrl().replace(
1352 '/patron/' + usr.id + '/checkout');
1353 $window.open(url, '_blank')
1360 .controller('PatronStatCatsCtrl',
1361 ['$scope','$routeParams','$q','egCore','patronSvc',
1362 function($scope, $routeParams , $q , egCore , patronSvc) {
1363 $scope.initTab('other', $routeParams.id)
1364 .then(function(redirect) {
1365 // Entries for org-visible stat cats are fleshed. Any others
1366 // have to be fleshed within.
1369 angular.forEach(patronSvc.current.stat_cat_entries(),
1371 if (!angular.isObject(entry.stat_cat())) {
1372 to_flesh[entry.stat_cat()] = entry;
1377 if (!Object.keys(to_flesh).length) return;
1379 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1380 .then(null, null, function(cat) { // stream
1381 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1382 to_flesh[cat.id()].stat_cat(cat);
1387 .controller('PatronSurveyCtrl',
1388 ['$scope','$routeParams','$location','egCore','patronSvc',
1389 function($scope, $routeParams , $location , egCore , patronSvc) {
1390 $scope.initTab('other', $routeParams.id);
1391 var usr_id = $routeParams.id;
1392 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1394 $scope.surveys = [];
1395 var svr_responses = {};
1397 // fetch all survey responses for this user.
1398 egCore.pcrud.search('asvr',
1400 {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1403 // All responses collected and deduplicated.
1404 // Create one collection of responses per survey.
1406 angular.forEach(svr_responses, function(questions, survey_id) {
1407 var collection = {responses : []};
1408 angular.forEach(questions, function(response) {
1409 collection.survey = response.survey(); // same for one.
1410 collection.responses.push(response);
1412 $scope.surveys.push(collection);
1416 function(response) {
1418 // Discard responses for out-of-scope surveys.
1419 if (org_ids.indexOf(response.survey().owner()) < 0)
1422 // survey_id => question_id => response
1423 var svr_id = response.survey().id();
1424 var qst_id = response.question().id();
1426 if (!svr_responses[svr_id])
1427 svr_responses[svr_id] = [];
1429 if (!svr_responses[svr_id][qst_id]) {
1430 svr_responses[svr_id][qst_id] = response;
1433 // We have multiple responses for the same question.
1434 // For this UI we only care about the most recent response.
1435 if (response.effective_date() >
1436 svr_responses[svr_id][qst_id].effective_date())
1437 svr_responses[svr_id][qst_id] = response;
1443 .controller('PatronFetchLastCtrl',
1444 ['$scope','$location','egCore',
1445 function($scope , $location , egCore) {
1447 var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1449 return $location.path('/circ/patron/' + ids[0] + '/checkout');
1451 $scope.no_last = true;
1454 .controller('PatronTriggeredEventsCtrl',
1455 ['$scope','$routeParams','$location','egCore','patronSvc',
1456 function($scope, $routeParams, $location , egCore , patronSvc) {
1457 $scope.initTab('other', $routeParams.id);
1459 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1460 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1462 $scope.triggered_events_url = url;
1466 .controller('PatronMessageCenterCtrl',
1467 ['$scope','$routeParams','$location','egCore','patronSvc',
1468 function($scope, $routeParams, $location , egCore , patronSvc) {
1469 $scope.initTab('other', $routeParams.id);
1471 var url = $location.protocol() + '://' + $location.host()
1472 + egCore.env.basePath.replace(/\/staff.*/, '/actor/user/message');
1473 url += '/' + encodeURIComponent($routeParams.id);
1475 $scope.message_center_url = url;
1479 .controller('PatronPermsCtrl',
1480 ['$scope','$routeParams','$window','$location','egCore',
1481 function($scope , $routeParams , $window , $location , egCore) {
1482 $scope.initTab('other', $routeParams.id);
1484 var url = $location.absUrl().replace(
1485 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1487 url += '?usr=' + encodeURIComponent($routeParams.id);
1489 // user_edit does not load the session via cookie. It uses URL
1490 // params or xulG instead. Pass via xulG.
1492 ses : egCore.auth.token(),
1493 on_patron_save : function() {
1494 $scope.funcs.reload();
1498 $scope.user_perms_url = url;