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 .config(function($routeProvider, $locationProvider, $compileProvider) {
19 $locationProvider.html5Mode(true);
20 $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
22 // data loaded at startup which only requires an authtoken goes
23 // here. this allows the requests to be run in parallel instead of
24 // waiting until startup has completed.
25 var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
27 // fetch the org settings we care about during egStartup
28 // and toss them into egCore.env as egCore.env.aous[name] = value.
29 // note: only load settings here needed by all tabs; load tab-
30 // specific settings from within their respective controllers
31 egCore.env.classLoaders.aous = function() {
32 return egCore.org.settings([
33 'ui.staff.require_initials.patron_info_notes',
34 'circ.do_not_tally_claims_returned',
37 'ui.circ.show_billing_tab_on_bills',
38 'circ.patron_expires_soon_warning',
39 'ui.circ.items_out.lost',
40 'ui.circ.items_out.longoverdue',
41 'ui.circ.items_out.claimsreturned'
42 ]).then(function(settings) {
43 // local settings are cached within egOrg. Caching them
44 // again in egEnv just simplifies the syntax for access.
45 egCore.env.aous = settings;
49 egCore.env.loadClasses.push('aous');
51 // app-globally modify the default flesh fields for
52 // fleshed user retrieval.
53 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
54 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
64 return egCore.startup.go();
67 $routeProvider.when('/circ/patron/search', {
68 templateUrl: './circ/patron/t_search',
69 controller: 'PatronSearchCtrl',
73 $routeProvider.when('/circ/patron/bcsearch', {
74 templateUrl: './circ/patron/t_bcsearch',
75 controller: 'PatronBarcodeSearchCtrl',
79 $routeProvider.when('/circ/patron/credentials', {
80 templateUrl: './circ/patron/t_credentials',
81 controller: 'PatronVerifyCredentialsCtrl',
85 $routeProvider.when('/circ/patron/last', {
86 templateUrl: './circ/patron/t_last_patron',
87 controller: 'PatronFetchLastCtrl',
91 // the following require a patron ID
93 $routeProvider.when('/circ/patron/:id/alerts', {
94 templateUrl: './circ/patron/t_alerts',
95 controller: 'PatronAlertsCtrl',
99 $routeProvider.when('/circ/patron/:id/checkout', {
100 templateUrl: './circ/patron/t_checkout',
101 controller: 'PatronCheckoutCtrl',
105 $routeProvider.when('/circ/patron/:id/items_out', {
106 templateUrl: './circ/patron/t_items_out',
107 controller: 'PatronItemsOutCtrl',
111 $routeProvider.when('/circ/patron/:id/holds', {
112 templateUrl: './circ/patron/t_holds',
113 controller: 'PatronHoldsCtrl',
117 $routeProvider.when('/circ/patron/:id/holds/create', {
118 templateUrl: './circ/patron/t_holds_create',
119 controller: 'PatronHoldsCreateCtrl',
123 $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
124 templateUrl: './circ/patron/t_holds',
125 controller: 'PatronHoldsCtrl',
129 $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
130 templateUrl: './circ/patron/t_hold_details',
131 controller: 'PatronHoldDetailsCtrl',
135 $routeProvider.when('/circ/patron/:id/bills', {
136 templateUrl: './circ/patron/t_bills',
137 controller: 'PatronBillsCtrl',
141 $routeProvider.when('/circ/patron/:id/bill/:xact_id/:xact_tab', {
142 templateUrl: './circ/patron/t_xact_details',
143 controller: 'XactDetailsCtrl',
147 $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
148 templateUrl: './circ/patron/t_bill_history',
149 controller: 'BillHistoryCtrl',
153 $routeProvider.when('/circ/patron/:id/messages', {
154 templateUrl: './circ/patron/t_messages',
155 controller: 'PatronMessagesCtrl',
159 $routeProvider.when('/circ/patron/:id/edit', {
160 templateUrl: './circ/patron/t_edit',
161 controller: 'PatronRegCtrl',
165 $routeProvider.when('/circ/patron/:id/credentials', {
166 templateUrl: './circ/patron/t_credentials',
167 controller: 'PatronVerifyCredentialsCtrl',
171 $routeProvider.when('/circ/patron/:id/notes', {
172 templateUrl: './circ/patron/t_notes',
173 controller: 'PatronNotesCtrl',
177 $routeProvider.when('/circ/patron/:id/triggered_events', {
178 templateUrl: './circ/patron/t_triggered_events',
179 controller: 'PatronTriggeredEventsCtrl',
183 $routeProvider.when('/circ/patron/:id/message_center', {
184 templateUrl: './circ/patron/t_message_center',
185 controller: 'PatronMessageCenterCtrl',
189 $routeProvider.when('/circ/patron/:id/edit_perms', {
190 templateUrl: './circ/patron/t_edit_perms',
191 controller: 'PatronPermsCtrl',
195 $routeProvider.when('/circ/patron/:id/group', {
196 templateUrl: './circ/patron/t_group',
197 controller: 'PatronGroupCtrl',
201 $routeProvider.when('/circ/patron/:id/stat_cats', {
202 templateUrl: './circ/patron/t_stat_cats',
203 controller: 'PatronStatCatsCtrl',
207 $routeProvider.when('/circ/patron/:id/surveys', {
208 templateUrl: './circ/patron/t_surveys',
209 controller: 'PatronSurveyCtrl',
213 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
217 * Manages tabbed patron view.
218 * This is the parent scope of all patron tab scopes.
221 .controller('PatronCtrl',
222 ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc',
223 function($scope, $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc) {
225 $scope.is_patron_edit = function() {
226 return Boolean($location.path().match(/patron\/\d+\/edit$/));
229 // To support the fixed position patron edit actions bar,
230 // its markup has to live outside the scope of the patron
231 // edit controller. Insert a scope blob here that can be
232 // modifed from within the patron edit controller.
233 $scope.edit_passthru = {};
235 // returns true if a redirect occurs
236 function redirectToAlertPanel() {
238 $scope.alert_penalties =
239 function() {return patronSvc.alert_penalties}
241 if (patronSvc.alertsShown()) return false;
243 // if the patron has any unshown alerts, show them now
244 if (patronSvc.hasAlerts &&
245 !$location.path().match(/alerts$/)) {
248 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
249 .search('card', null);
253 // no alert required. If the patron has fines and the show-bills
254 // OUS is applied, direct to the bills page.
255 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
256 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
257 && !$location.path().match(/bills$/)) {
259 $scope.tab = 'bills';
261 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
262 .search('card', null);
270 // called after each route-specified controller is instantiated.
271 // this doubles as a way to inform the top-level controller that
272 // egStartup.go() has completed, which means we are clear to
273 // fetch the patron, etc.
274 $scope.initTab = function(tab, patron_id) {
275 console.log('init tab ' + tab);
277 $scope.aous = egCore.env.aous;
278 $scope.auth_user_id = egCore.auth.user().id();
281 $scope.patron_id = patron_id;
282 return patronSvc.setPrimary($scope.patron_id)
284 // the page title context label comes from the tab.
285 egCore.strings.setPageTitle(
286 egCore.strings.PAGE_TITLE_PATRON_NAME,
287 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
288 { lname : patronSvc.current.family_name(),
289 fname : patronSvc.current.first_given_name(),
290 mname : patronSvc.current.second_given_name()
294 .then(function() {return patronSvc.checkAlerts()})
295 .then(redirectToAlertPanel)
297 $scope.ident_type_name = $scope.patron().ident_type().name()
298 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
301 // No patron, use the tab name as the page title.
302 egCore.strings.setPageTitle(
303 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
308 $scope._show_dob = {};
309 $scope.show_dob = function (val) {
310 if ($scope.patron()) {
311 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
312 return $scope._show_dob[$scope.patron().id()];
314 return !egCore.env.aous['circ.obscure_dob'];
317 $scope.obscure_dob = function() {
318 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
320 $scope.now_show_dob = function() {
321 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
322 $scope.show_dob() : true;
325 $scope.patron = function() { return patronSvc.current }
326 $scope.patron_stats = function() { return patronSvc.patron_stats }
327 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
328 $scope.hasAlerts = function() { return patronSvc.hasAlerts }
329 $scope.isPatronExpired = function() { return patronSvc.patronExpired }
330 $scope.doesPatronExpireSoon = function() { return patronSvc.patronExpiresSoon }
332 $scope.print_address = function(addr) {
335 template : 'patron_address',
337 patron : egCore.idl.toHash(patronSvc.current),
338 address : egCore.idl.toHash(addr)
343 $scope.copy_address = function(addr) {
344 // Alas, navigator.clipboard is not yet supported in FF and others.
345 var lNode = document.querySelector('#patron-address-copy-' + addr.id());
347 // Un-hide the textarea just long enough to copy its data.
348 // Using node.style instead of ng-show/ng-hide in hopes it
349 // will be quicker, so the user never sees the textarea.
350 lNode.style.visibility = 'visible';
354 if (!document.execCommand('copy')) {
355 console.error('Copy command failed');
358 lNode.style.visibility = 'hidden';
361 $scope.toggle_expand_summary = function() {
362 if ($scope.collapsePatronSummary) {
363 $scope.collapsePatronSummary = false;
364 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
366 $scope.collapsePatronSummary = true;
367 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
371 // always expand the patron summary in the search UI, regardless
372 // of stored preference.
373 $scope.collapse_summary = function() {
374 return $scope.tab != 'search' && $scope.collapsePatronSummary;
377 function _purge_account(dest_usr,override) {
380 'open-ils.actor.user.delete' + (override ? '.override' : ''),
382 $scope.patron().id(),
384 ).then(function(resp){
385 if (evt = egCore.evt.parse(resp)) {
386 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
387 egConfirmDialog.open(
388 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
390 _purge_account(dest_usr,true);
397 location.href = egCore.env.basePath + '/circ/patron/search';
402 function _purge_account_with_destination(dest_barcode) {
403 egCore.pcrud.search('ac', {barcode : dest_barcode})
404 .then(function(card) {
406 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
408 _purge_account(card.usr());
413 $scope.purge_account = function() {
414 egConfirmDialog.open(
415 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
417 egConfirmDialog.open(
418 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
422 'open-ils.actor.user.has_work_perm_at',
423 egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
424 ).then(function(resp) {
425 var is_staff = resp.length > 0;
428 egCore.strings.PATRON_PURGE_STAFF_PROMPT,
429 null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
430 {ok : function(barcode) {_purge_account_with_destination(barcode)}}
442 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
443 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
446 .controller('PatronBarcodeSearchCtrl',
447 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc','$uibModal','$q',
448 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc , $uibModal , $q) {
449 $scope.selectMe = true; // focus text input
450 patronSvc.clearPrimary(); // clear the default user
452 // jump to the patron checkout UI
453 function loadPatron(user_id) {
454 egCore.audio.play('success.patron.by_barcode');
456 .path('/circ/patron/' + user_id + '/checkout')
457 .search('card', $scope.args.barcode);
458 patronSvc.search_barcode = $scope.args.barcode;
461 // create an opt-in=yes response for the loaded user
462 function createOptIn(user_id) {
465 'open-ils.actor.user.org_unit_opt_in.create',
466 egCore.auth.token(), user_id).then(function(resp) {
467 if (evt = egCore.evt.parse(resp)) return alert(evt);
473 $scope.submitBarcode = function(args) {
474 $scope.bcNotFound = null;
475 $scope.optInRestricted = false;
476 if (!args.barcode) return;
477 args.barcode = args.barcode.replace(/^\s/g,'');
478 args.barcode = args.barcode.replace(/\s$/g,'');
479 // blur so next time it's set to true it will re-apply select()
480 $scope.selectMe = false;
484 // given a scanned barcode, this function finds any matching users
485 // and handles multiple matches due to barcode completion
486 function handleBarcodeCompletion(scanned_barcode) {
487 var deferred = $q.defer();
491 'open-ils.actor.get_barcodes',
492 egCore.auth.token(), egCore.auth.user().ws_ou(),
493 'actor', scanned_barcode)
495 .then(function(resp) { // get_barcodes
497 if (evt = egCore.evt.parse(resp)) {
503 if (!resp || !resp[0]) {
504 $scope.bcNotFound = args.barcode;
505 $scope.selectMe = true;
506 egCore.audio.play('warning.patron.not_found');
511 if (resp.length == 1) {
512 // exactly one matching barcode: return it
514 user_id = resp[0].id;
516 // multiple matching barcodes: let the user pick one
517 var barcode_map = {};
520 var selected_barcode;
521 angular.forEach(resp, function(match) {
523 egUser.get(match.id, {useFields : ['home_ou']}).then(function(user) {
524 barcode_map[match.barcode] = user.id();
526 barcode: match.barcode,
527 title: user.first_given_name() + ' ' + user.family_name(),
528 org_name: user.home_ou().name(),
529 org_shortname: user.home_ou().shortname()
534 return $q.all(promises)
537 templateUrl: './circ/share/t_barcode_choice_dialog',
539 ['$scope', '$uibModalInstance',
540 function($scope, $uibModalInstance) {
541 $scope.matches = matches;
542 $scope.ok = function(barcode) {
543 $uibModalInstance.close();
544 selected_barcode = barcode;
546 $scope.cancel = function() {$uibModalInstance.dismiss()}
548 }).result.then(function() {
550 user_id = barcode_map[selected_barcode];
555 return deferred.promise;
558 // call our function to lookup matching users for the scanned barcode
559 handleBarcodeCompletion(args.barcode).then(function() {
561 // see if an opt-in request is needed
562 return egCore.net.request(
564 'open-ils.actor.user.org_unit_opt_in.check',
565 egCore.auth.token(), user_id
566 ).then(function(optInResp) { // opt_in_check
568 if (evt = egCore.evt.parse(optInResp)) {
573 if (optInResp == 2) {
574 // opt-in disallowed at this location by patron's home library
575 $scope.optInRestricted = true;
576 $scope.selectMe = true;
577 egCore.audio.play('warning.patron.opt_in_restricted');
581 if (optInResp == 1) {
582 // opt-in handled or not needed
583 return loadPatron(user_id);
586 // opt-in needed, show the opt-in dialog
587 egUser.get(user_id, {useFields : []})
589 .then(function(user) { // retrieve user
590 var org = egCore.org.get(user.home_ou());
591 egConfirmDialog.open(
592 egCore.strings.OPT_IN_DIALOG_TITLE,
593 egCore.strings.OPT_IN_DIALOG,
594 { family_name : user.family_name(),
595 first_given_name : user.first_given_name(),
596 org_name : org.name(),
597 org_shortname : org.shortname(),
598 ok : function() { createOptIn(user.id()) },
599 cancel : function() {}
610 * Manages patron search
612 .controller('PatronSearchCtrl',
613 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
614 '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
615 'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
616 function($scope, $q, $routeParams, $timeout, $window, $location, egCore , ngToast,
617 $filter, egUser, patronSvc , egGridDataProvider , $document , bucketSvc,
618 egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
620 angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
621 $scope.initTab('search');
623 $scope.gridControls = {
624 activateItem : function(item) {
625 $location.path('/circ/patron/' + item.id() + '/checkout');
627 selectedItems : function() { return [] }
630 $scope.bucketSvc = bucketSvc;
631 $scope.bucketSvc.fetchUserBuckets();
632 $scope.addToBucket = function(item, data, recs) {
633 if (recs.length == 0) return;
635 var failed_count = 0;
636 var promise = $q.when();
637 angular.forEach(recs,
639 var item = new egCore.idl.cubi();
640 item.bucket(data.id());
641 item.target_user(rec.id());
642 promise = promise.then(function() {
643 return egCore.net.request(
645 'open-ils.actor.container.item.create',
646 egCore.auth.token(), 'user', item
649 function(){ added_count++ },
650 function(){ failed_count++ }
655 promise.then( function () {
656 if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
657 if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
661 var temp_scope = $scope;
662 $scope.openCreateBucketDialog = function() {
664 templateUrl: './circ/patron/bucket/t_bucket_create',
667 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
668 $scope.focusMe = true;
669 $scope.ok = function(args) { $uibModalInstance.close(args) }
670 $scope.cancel = function () { $uibModalInstance.dismiss() }
672 }).result.then(function (args) {
673 if (!args || !args.name) return;
674 bucketSvc.createBucket(args.name, args.desc).then(
677 $scope.bucketSvc.fetchBucket(id).then(function (b) {
681 $scope.gridControls.selectedItems()
683 $scope.bucketSvc.fetchUserBuckets(true);
692 function() {return $scope.gridControls.selectedItems()},
695 patronSvc.setPrimary(null, list[0]);
700 $scope.need_one_selected = function() {
701 var items = $scope.gridControls.selectedItems();
702 return (items.length > 0) ? false : true;
704 $scope.need_two_selected = function() {
705 var items = $scope.gridControls.selectedItems();
706 return (items.length == 2) ? false : true;
708 $scope.merge_patrons = function() {
709 var items = $scope.gridControls.selectedItems();
710 if (items.length != 2) return false;
713 angular.forEach(items, function(i) {
714 patron_ids.push(i.id());
716 egPatronMerge.do_merge(patron_ids).then(
718 // ensure that we're not drawing from cached
719 // resuts, as a successful merge just deleted a
721 delete patronSvc.lastSearch;
722 $scope.gridControls.refresh();
725 if (evt && evt.textcode == 'MERGE_SELF_NOT_ALLOWED') {
726 ngToast.warning(egCore.strings.MERGE_SELF_NOT_ALLOWED);
737 .controller('PatronMessagesCtrl',
738 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
739 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
740 $scope.initTab('messages', $routeParams.id);
741 var usr_id = $routeParams.id;
742 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
744 // setup date filters
745 var start = new Date(); // now - 1 year
746 start.setFullYear(start.getFullYear() - 1),
749 end_date : new Date()
752 function date_range() {
753 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
754 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
755 var today = new Date().toISOString().replace(/T.*/,'');
756 if (end == today) end = 'now';
762 var activeGrid = $scope.activeGridControls = {
763 setSort : function() {
766 setQuery : function() {
772 {stop_date : {'>' : 'now'}}
778 var archiveGrid = $scope.archiveGridControls = {
779 setSort : function() {
782 watchQuery : function() {
786 stop_date : {'<=' : 'now'},
787 set_date : {between : date_range()}
792 $scope.removePenalty = function(selected) {
793 // the grid stores flattened penalties. Fetch penalty objects first
795 var ids = selected.map(function(s){ return s.id });
796 egCore.pcrud.search('ausp',
798 {atomic : true, authoritative : true}
801 ).then(function(penalties) {
802 return egCore.pcrud.remove(penalties);
804 // then refresh the grid
806 activeGrid.refresh();
810 $scope.archivePenalty = function(selected) {
811 // the grid stores flattened penalties. Fetch penalty objects first
813 var ids = selected.map(function(s){ return s.id });
814 egCore.pcrud.search('ausp',
816 {atomic : true, authoritative : true}
819 ).then(function(penalties) {
820 angular.forEach(penalties, function(p){ p.stop_date('now') });
821 return egCore.pcrud.update(penalties);
823 // then refresh the grid
825 activeGrid.refresh();
826 archiveGrid.refresh();
830 // leverage egEnv for caching
831 function fetchPenaltyTypes() {
833 return $q.when(egCore.env.csp.list);
834 return egCore.pcrud.search(
835 // id <= 100 are reserved for system use
836 'csp', {id : {'>': 100}}, {}, {atomic : true})
837 .then(function(penalties) {
838 egCore.env.absorbList(penalties, 'csp');
843 $scope.createPenalty = function() {
844 egCirc.create_penalty(usr_id).then(function() {
845 activeGrid.refresh();
846 // force a refresh of the user, since they may now
847 // have blocking penalties, etc.
848 patronSvc.setPrimary(patronSvc.current.id(), null, true);
852 $scope.editPenalty = function(selected) {
853 if (selected.length == 0) return;
855 // grab the penalty from the user object
856 var penalty = patronSvc.current.standing_penalties().filter(
857 function(p) {return p.id() == selected[0].id})[0];
859 egCirc.edit_penalty(penalty).then(function() {
860 activeGrid.refresh();
861 // force a refresh of the user, since they may now
862 // have blocking penalties, etc.
863 patronSvc.setPrimary(patronSvc.current.id(), null, true);
872 .controller('PatronVerifyCredentialsCtrl',
873 ['$scope','$routeParams','$location','egCore',
874 function($scope, $routeParams , $location , egCore) {
875 $scope.verified = null;
876 $scope.focusMe = true;
878 // called with a patron, pre-populate the form args
879 $scope.initTab('other', $routeParams.id).then(
881 if ($routeParams.id && $scope.patron()) {
882 $scope.prepop = true;
883 $scope.username = $scope.patron().usrname();
884 $scope.barcode = $scope.patron().card().barcode();
886 $scope.username = '';
888 $scope.password = '';
893 // verify login credentials
894 $scope.verify = function() {
895 $scope.verified = null;
896 $scope.notFound = false;
900 'open-ils.actor.verify_user_password',
901 egCore.auth.token(), $scope.barcode,
902 $scope.username, hex_md5($scope.password || '')
904 ).then(function(resp) {
905 $scope.focusMe = true;
906 if (evt = egCore.evt.parse(resp)) {
908 } else if (resp == 1) {
909 $scope.verified = true;
911 $scope.verified = false;
916 // load the main patron UI for the provided username or barcode
917 $scope.load = function($event) {
918 $scope.notFound = false;
919 $scope.verified = null;
923 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
924 egCore.auth.token(), $scope.barcode, $scope.username
926 ).then(function(resp) {
929 $location.path('/circ/patron/' + resp + '/checkout');
933 // something went wrong...
934 $scope.focusMe = true;
935 if (evt = egCore.evt.parse(resp)) {
936 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
937 $scope.notFound = true;
946 // load() button sits within the verify form.
947 // avoid submitting the verify() form action on load()
948 $event.preventDefault();
952 .controller('PatronAlertsCtrl',
953 ['$scope','$routeParams','$location','egCore','patronSvc',
954 function($scope, $routeParams , $location , egCore , patronSvc) {
956 $scope.initTab('other', $routeParams.id)
958 $scope.patronExpired = patronSvc.patronExpired;
959 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
960 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
961 $scope.invalidAddresses = patronSvc.invalidAddresses;
966 .controller('PatronNotesCtrl',
967 ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
969 function($scope, $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
971 $scope.initTab('other', $routeParams.id);
972 var usr_id = $routeParams.id;
975 function refreshPage() {
977 egCore.pcrud.search('aun',
979 {flesh : 1, flesh_fields : {aun : ['creator']}},
980 {authoritative : true})
981 .then(null, null, function(note) {
982 $scope.notes.push(note);
986 // open the new-note dialog and create the note
987 $scope.newNote = function() {
989 templateUrl: './circ/patron/t_new_note_dialog',
992 ['$scope', '$uibModalInstance',
993 function($scope, $uibModalInstance) {
994 $scope.focusNote = true;
996 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
997 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
998 $scope.cancel = function () { $uibModalInstance.dismiss() }
1002 if (!args.value) return;
1003 var note = new egCore.idl.aun();
1005 note.title(args.title);
1006 note.value(args.value);
1007 note.pub(args.pub ? 't' : 'f');
1008 note.creator(egCore.auth.user().id());
1010 note.value(note.value() + ' [' + args.initials + ']');
1011 egCore.pcrud.create(note).then(function() {refreshPage()});
1016 // delete the selected note
1017 $scope.deleteNote = function(note) {
1018 egConfirmDialog.open(
1019 egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
1021 egCore.pcrud.remove(note).then(function() {refreshPage()});
1023 note_title : note.title(),
1024 create_date : note.create_date()
1028 // print the selected note
1029 $scope.printNote = function(note) {
1030 var hash = egCore.idl.toHash(note);
1031 hash.usr = egCore.idl.toHash($scope.patron());
1032 egCore.print.print({
1033 context : 'default',
1034 template : 'patron_note',
1035 scope : {note : hash}
1039 // perform the initial note fetch
1043 .controller('PatronGroupCtrl',
1044 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1045 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1046 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1047 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1049 var usr_id = $routeParams.id;
1051 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1053 var grid = $scope.gridControls = {
1054 activateItem : function(item) {
1055 $location.path('/circ/patron/' + item.id + '/checkout');
1057 itemRetrieved : function(item) {
1059 if (item.id == patronSvc.current.id()) {
1060 item.stats = patronSvc.patron_stats;
1063 // flesh stats for other group members
1064 patronSvc.getUserStats(item.id).then(function(stats) {
1066 $scope.totals.total_out += stats.checkouts.total_out;
1067 $scope.totals.overdue += stats.checkouts.overdue;
1071 setSort : function() {
1072 return ['create_date'];
1074 watchQuery: function() {
1075 if (patronSvc.current) {
1077 usrgroup : patronSvc.current.usrgroup(),
1085 $scope.initTab('other', $routeParams.id)
1086 .then(function(redirect) {
1087 // if we are redirecting to the alerts page, avoid updating the
1089 if (redirect) return;
1090 // let initTab() fetch the user first so we can know the usrgroup
1091 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1094 $scope.removeFromGroup = function(selected) {
1096 angular.forEach(selected, function(user) {
1097 console.debug('removing user ' + user.id + ' from group');
1102 'open-ils.actor.usergroup.new',
1103 egCore.auth.token(), user.id, true
1108 $q.all(promises).then(function() {grid.refresh()});
1111 function addUserToGroup(user) {
1112 user.usrgroup(patronSvc.current.usrgroup());
1113 user.ischanged(true);
1116 'open-ils.actor.patron.update',
1117 egCore.auth.token(), user
1119 ).then(function() {grid.refresh()});
1122 // fetch each user ("selected" has flattened users)
1123 // update the usrgroup, then update the user object
1124 // After all updates are complete, refresh the grid.
1125 function moveUsersToGroup(target_user, selected) {
1128 angular.forEach(selected, function(user) {
1130 egCore.pcrud.retrieve('au', user.id)
1132 u.usrgroup(target_user.usrgroup());
1134 return egCore.net.request(
1136 'open-ils.actor.patron.update',
1137 egCore.auth.token(), u
1143 $q.all(promises).then(function() {grid.refresh()});
1146 function showMoveToGroupConfirm(barcode, selected, outbound) {
1149 egCore.pcrud.search('ac', {barcode : barcode})
1151 // fetch the fleshed user
1152 .then(function(card) {
1154 if (!card) return; // TODO: warn user
1156 egCore.pcrud.retrieve('au', card.usr())
1157 .then(function(user) {
1160 templateUrl: './circ/patron/t_move_to_group_dialog',
1163 '$scope','$uibModalInstance',
1164 function($scope , $uibModalInstance) {
1166 $scope.selected = selected;
1167 $scope.outbound = outbound;
1169 function(count) { $uibModalInstance.close() }
1171 function () { $uibModalInstance.dismiss() }
1174 }).result.then(function() {
1176 moveUsersToGroup(user, selected);
1178 addUserToGroup(user);
1185 // selected == move selected patrons to another patron's group
1186 // !selected == patron from a different group moves into our group
1187 function moveToGroup(selected, outbound) {
1188 egPromptDialog.open(
1189 egCore.strings.GROUP_ADD_USER, '',
1190 {ok : function(value) {
1192 showMoveToGroupConfirm(value, selected, outbound);
1197 $scope.moveToGroup = function() { moveToGroup([], false) };
1198 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1200 $scope.cloneUser = function(selected) {
1201 if (!selected.length) return;
1202 var url = $location.absUrl().replace(
1204 '/patron/register/clone/' + selected[0].id);
1205 $window.open(url, '_blank').focus();
1208 $scope.retrieveSelected = function(selected) {
1209 if (!selected.length) return;
1210 angular.forEach(selected, function(usr) {
1211 $timeout(function() {
1212 var url = $location.absUrl().replace(
1214 '/patron/' + usr.id + '/checkout');
1215 $window.open(url, '_blank')
1222 .controller('PatronStatCatsCtrl',
1223 ['$scope','$routeParams','$q','egCore','patronSvc',
1224 function($scope, $routeParams , $q , egCore , patronSvc) {
1225 $scope.initTab('other', $routeParams.id)
1226 .then(function(redirect) {
1227 // Entries for org-visible stat cats are fleshed. Any others
1228 // have to be fleshed within.
1231 angular.forEach(patronSvc.current.stat_cat_entries(),
1233 if (!angular.isObject(entry.stat_cat())) {
1234 to_flesh[entry.stat_cat()] = entry;
1239 if (!Object.keys(to_flesh).length) return;
1241 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1242 .then(null, null, function(cat) { // stream
1243 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1244 to_flesh[cat.id()].stat_cat(cat);
1249 .controller('PatronSurveyCtrl',
1250 ['$scope','$routeParams','$location','egCore','patronSvc',
1251 function($scope, $routeParams , $location , egCore , patronSvc) {
1252 $scope.initTab('other', $routeParams.id);
1253 var usr_id = $routeParams.id;
1254 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1256 $scope.surveys = [];
1257 var svr_responses = {};
1259 // fetch all survey responses for this user.
1260 egCore.pcrud.search('asvr',
1262 {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1265 // All responses collected and deduplicated.
1266 // Create one collection of responses per survey.
1268 angular.forEach(svr_responses, function(questions, survey_id) {
1269 var collection = {responses : []};
1270 angular.forEach(questions, function(response) {
1271 collection.survey = response.survey(); // same for one.
1272 collection.responses.push(response);
1274 $scope.surveys.push(collection);
1278 function(response) {
1280 // Discard responses for out-of-scope surveys.
1281 if (org_ids.indexOf(response.survey().owner()) < 0)
1284 // survey_id => question_id => response
1285 var svr_id = response.survey().id();
1286 var qst_id = response.question().id();
1288 if (!svr_responses[svr_id])
1289 svr_responses[svr_id] = [];
1291 if (!svr_responses[svr_id][qst_id]) {
1292 svr_responses[svr_id][qst_id] = response;
1295 // We have multiple responses for the same question.
1296 // For this UI we only care about the most recent response.
1297 if (response.effective_date() >
1298 svr_responses[svr_id][qst_id].effective_date())
1299 svr_responses[svr_id][qst_id] = response;
1305 .controller('PatronFetchLastCtrl',
1306 ['$scope','$location','egCore',
1307 function($scope , $location , egCore) {
1309 var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1311 return $location.path('/circ/patron/' + ids[0] + '/checkout');
1313 $scope.no_last = true;
1316 .controller('PatronTriggeredEventsCtrl',
1317 ['$scope','$routeParams','$location','egCore','patronSvc',
1318 function($scope, $routeParams, $location , egCore , patronSvc) {
1319 $scope.initTab('other', $routeParams.id);
1321 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1322 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1324 $scope.triggered_events_url = url;
1328 .controller('PatronMessageCenterCtrl',
1329 ['$scope','$routeParams','$location','egCore','patronSvc',
1330 function($scope, $routeParams, $location , egCore , patronSvc) {
1331 $scope.initTab('other', $routeParams.id);
1333 var url = $location.protocol() + '://' + $location.host()
1334 + egCore.env.basePath.replace(/\/staff.*/, '/actor/user/message');
1335 url += '/' + encodeURIComponent($routeParams.id);
1337 $scope.message_center_url = url;
1341 .controller('PatronPermsCtrl',
1342 ['$scope','$routeParams','$window','$location','egCore',
1343 function($scope , $routeParams , $window , $location , egCore) {
1344 $scope.initTab('other', $routeParams.id);
1346 var url = $location.absUrl().replace(
1347 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1349 url += '?usr=' + encodeURIComponent($routeParams.id);
1351 // user_edit does not load the session via cookie. It uses URL
1352 // params or xulG instead. Pass via xulG.
1354 ses : egCore.auth.token(),
1355 on_patron_save : function() {
1356 $scope.funcs.reload();
1360 $scope.user_perms_url = url;