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 'circ.auto_hide_patron_summary'
43 ]).then(function(settings) {
44 // local settings are cached within egOrg. Caching them
45 // again in egEnv just simplifies the syntax for access.
46 egCore.env.aous = settings;
50 egCore.env.loadClasses.push('aous');
52 // app-globally modify the default flesh fields for
53 // fleshed user retrieval.
54 if (egUser.defaultFleshFields.indexOf('profile') == -1) {
55 egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
65 return egCore.startup.go();
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/:xact_tab', {
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/message_center', {
185 templateUrl: './circ/patron/t_message_center',
186 controller: 'PatronMessageCenterCtrl',
190 $routeProvider.when('/circ/patron/:id/edit_perms', {
191 templateUrl: './circ/patron/t_edit_perms',
192 controller: 'PatronPermsCtrl',
196 $routeProvider.when('/circ/patron/:id/group', {
197 templateUrl: './circ/patron/t_group',
198 controller: 'PatronGroupCtrl',
202 $routeProvider.when('/circ/patron/:id/stat_cats', {
203 templateUrl: './circ/patron/t_stat_cats',
204 controller: 'PatronStatCatsCtrl',
208 $routeProvider.when('/circ/patron/:id/surveys', {
209 templateUrl: './circ/patron/t_surveys',
210 controller: 'PatronSurveyCtrl',
214 $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
218 * Manages tabbed patron view.
219 * This is the parent scope of all patron tab scopes.
222 .controller('PatronCtrl',
223 ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc',
224 function($scope, $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc) {
226 $scope.is_patron_edit = function() {
227 return Boolean($location.path().match(/patron\/\d+\/edit$/));
230 // To support the fixed position patron edit actions bar,
231 // its markup has to live outside the scope of the patron
232 // edit controller. Insert a scope blob here that can be
233 // modifed from within the patron edit controller.
234 $scope.edit_passthru = {};
236 // returns true if a redirect occurs
237 function redirectToAlertPanel() {
239 $scope.alert_penalties =
240 function() {return patronSvc.alert_penalties}
242 if (patronSvc.alertsShown()) return false;
244 // if the patron has any unshown alerts, show them now
245 if (patronSvc.hasAlerts &&
246 !$location.path().match(/alerts$/)) {
249 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
250 .search('card', null);
254 // no alert required. If the patron has fines and the show-bills
255 // OUS is applied, direct to the bills page.
256 if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
257 && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
258 && !$location.path().match(/bills$/)) {
260 $scope.tab = 'bills';
262 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
263 .search('card', null);
271 // Expand or collapse the patron summary side bar.
272 function setSummaryState(condition) {
274 egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
276 egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
280 // called after each route-specified controller is instantiated.
281 // this doubles as a way to inform the top-level controller that
282 // egStartup.go() has completed, which means we are clear to
283 // fetch the patron, etc.
284 $scope.initTab = function(tab, patron_id) {
285 console.log('init tab ' + tab);
287 $scope.aous = egCore.env.aous;
288 $scope.auth_user_id = egCore.auth.user().id();
290 if (egCore.env.aous && // cached in startup
291 egCore.env.aous['circ.auto_hide_patron_summary']) {
292 setSummaryState(true);
296 $scope.patron_id = patron_id;
297 return patronSvc.setPrimary($scope.patron_id)
299 // the page title context label comes from the tab.
300 egCore.strings.setPageTitle(
301 egCore.strings.PAGE_TITLE_PATRON_NAME,
302 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
303 { lname : patronSvc.current.family_name(),
304 fname : patronSvc.current.first_given_name(),
305 mname : patronSvc.current.second_given_name()
309 .then(function() {return patronSvc.checkAlerts()})
310 .then(redirectToAlertPanel)
312 $scope.ident_type_name = $scope.patron().ident_type().name()
313 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
316 // No patron, use the tab name as the page title.
317 egCore.strings.setPageTitle(
318 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
323 $scope._show_dob = {};
324 $scope.show_dob = function (val) {
325 if ($scope.patron()) {
326 if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
327 return $scope._show_dob[$scope.patron().id()];
329 return !egCore.env.aous['circ.obscure_dob'];
332 $scope.obscure_dob = function() {
333 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
335 $scope.now_show_dob = function() {
336 return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
337 $scope.show_dob() : true;
340 $scope.patron = function() { return patronSvc.current }
341 $scope.patron_stats = function() { return patronSvc.patron_stats }
342 $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
343 $scope.hasAlerts = function() { return patronSvc.hasAlerts }
344 $scope.isPatronExpired = function() { return patronSvc.patronExpired }
346 $scope.print_address = function(addr) {
349 template : 'patron_address',
351 patron : egCore.idl.toHash(patronSvc.current),
352 address : egCore.idl.toHash(addr)
357 $scope.copy_address = function(addr) {
358 // Alas, navigator.clipboard is not yet supported in FF and others.
359 var lNode = document.querySelector('#patron-address-copy-' + addr.id());
361 // Un-hide the textarea just long enough to copy its data.
362 // Using node.style instead of ng-show/ng-hide in hopes it
363 // will be quicker, so the user never sees the textarea.
364 lNode.style.visibility = 'visible';
368 if (!document.execCommand('copy')) {
369 console.error('Copy command failed');
372 lNode.style.visibility = 'hidden';
375 $scope.toggle_expand_summary = function() {
376 if ($scope.collapsePatronSummary) {
377 $scope.collapsePatronSummary = false;
379 $scope.collapsePatronSummary = true;
381 setSummaryState($scope.collapsePatronSummary);
384 // always expand the patron summary in the search UI, regardless
385 // of stored preference.
386 $scope.collapse_summary = function() {
387 return $scope.tab != 'search' && $scope.collapsePatronSummary;
390 function _purge_account(dest_usr,override) {
393 'open-ils.actor.user.delete' + (override ? '.override' : ''),
395 $scope.patron().id(),
397 ).then(function(resp){
398 if (evt = egCore.evt.parse(resp)) {
399 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
400 egConfirmDialog.open(
401 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
403 _purge_account(dest_usr,true);
410 location.href = egCore.env.basePath + '/circ/patron/search';
415 function _purge_account_with_destination(dest_barcode) {
416 egCore.pcrud.search('ac', {barcode : dest_barcode})
417 .then(function(card) {
419 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
421 _purge_account(card.usr());
426 $scope.purge_account = function() {
427 egConfirmDialog.open(
428 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
430 egConfirmDialog.open(
431 egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
435 'open-ils.actor.user.has_work_perm_at',
436 egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
437 ).then(function(resp) {
438 var is_staff = resp.length > 0;
441 egCore.strings.PATRON_PURGE_STAFF_PROMPT,
442 null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
443 {ok : function(barcode) {_purge_account_with_destination(barcode)}}
455 egCore.hatch.getItem('eg.circ.patron.summary.collapse')
456 .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
459 .controller('PatronBarcodeSearchCtrl',
460 ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc','$uibModal','$q',
461 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc , $uibModal , $q) {
462 $scope.selectMe = true; // focus text input
463 patronSvc.clearPrimary(); // clear the default user
465 // jump to the patron checkout UI
466 function loadPatron(user_id) {
467 egCore.audio.play('success.patron.by_barcode');
469 .path('/circ/patron/' + user_id + '/checkout')
470 .search('card', $scope.args.barcode);
471 patronSvc.search_barcode = $scope.args.barcode;
474 // create an opt-in=yes response for the loaded user
475 function createOptIn(user_id) {
478 'open-ils.actor.user.org_unit_opt_in.create',
479 egCore.auth.token(), user_id).then(function(resp) {
480 if (evt = egCore.evt.parse(resp)) return alert(evt);
486 $scope.submitBarcode = function(args) {
487 $scope.bcNotFound = null;
488 $scope.optInRestricted = false;
489 if (!args.barcode) return;
490 args.barcode = args.barcode.replace(/\s/g,'');
491 // blur so next time it's set to true it will re-apply select()
492 $scope.selectMe = false;
496 // given a scanned barcode, this function finds any matching users
497 // and handles multiple matches due to barcode completion
498 function handleBarcodeCompletion(scanned_barcode) {
499 var deferred = $q.defer();
503 'open-ils.actor.get_barcodes',
504 egCore.auth.token(), egCore.auth.user().ws_ou(),
505 'actor', scanned_barcode)
507 .then(function(resp) { // get_barcodes
509 if (evt = egCore.evt.parse(resp)) {
515 if (!resp || !resp[0]) {
516 $scope.bcNotFound = args.barcode;
517 $scope.selectMe = true;
518 egCore.audio.play('warning.patron.not_found');
523 if (resp.length == 1) {
524 // exactly one matching barcode: return it
526 user_id = resp[0].id;
528 // multiple matching barcodes: let the user pick one
529 var barcode_map = {};
532 var selected_barcode;
533 angular.forEach(resp, function(match) {
535 egUser.get(match.id, {useFields : ['home_ou']}).then(function(user) {
536 barcode_map[match.barcode] = user.id();
538 barcode: match.barcode,
539 title: user.first_given_name() + ' ' + user.family_name(),
540 org_name: user.home_ou().name(),
541 org_shortname: user.home_ou().shortname()
546 return $q.all(promises)
549 templateUrl: './circ/share/t_barcode_choice_dialog',
551 ['$scope', '$uibModalInstance',
552 function($scope, $uibModalInstance) {
553 $scope.matches = matches;
554 $scope.ok = function(barcode) {
555 $uibModalInstance.close();
556 selected_barcode = barcode;
558 $scope.cancel = function() {$uibModalInstance.dismiss()}
560 }).result.then(function() {
562 user_id = barcode_map[selected_barcode];
567 return deferred.promise;
570 // call our function to lookup matching users for the scanned barcode
571 handleBarcodeCompletion(args.barcode).then(function() {
573 // see if an opt-in request is needed
574 return egCore.net.request(
576 'open-ils.actor.user.org_unit_opt_in.check',
577 egCore.auth.token(), user_id
578 ).then(function(optInResp) { // opt_in_check
580 if (evt = egCore.evt.parse(optInResp)) {
585 if (optInResp == 2) {
586 // opt-in disallowed at this location by patron's home library
587 $scope.optInRestricted = true;
588 $scope.selectMe = true;
589 egCore.audio.play('warning.patron.opt_in_restricted');
593 if (optInResp == 1) {
594 // opt-in handled or not needed
595 return loadPatron(user_id);
598 // opt-in needed, show the opt-in dialog
599 egUser.get(user_id, {useFields : []})
601 .then(function(user) { // retrieve user
602 var org = egCore.org.get(user.home_ou());
603 egConfirmDialog.open(
604 egCore.strings.OPT_IN_DIALOG_TITLE,
605 egCore.strings.OPT_IN_DIALOG,
606 { family_name : user.family_name(),
607 first_given_name : user.first_given_name(),
608 org_name : org.name(),
609 org_shortname : org.shortname(),
610 ok : function() { createOptIn(user.id()) },
611 cancel : function() {}
622 * Manages patron search
624 .controller('PatronSearchCtrl',
625 ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
626 '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
627 'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
628 function($scope, $q, $routeParams, $timeout, $window, $location, egCore , ngToast,
629 $filter, egUser, patronSvc , egGridDataProvider , $document , bucketSvc,
630 egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
632 angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
633 $scope.initTab('search');
635 $scope.gridControls = {
636 activateItem : function(item) {
637 $location.path('/circ/patron/' + item.id() + '/checkout');
639 selectedItems : function() { return [] }
642 $scope.bucketSvc = bucketSvc;
643 $scope.bucketSvc.fetchUserBuckets();
644 $scope.addToBucket = function(item, data, recs) {
645 if (recs.length == 0) return;
647 var failed_count = 0;
649 angular.forEach(recs,
651 var item = new egCore.idl.cubi();
652 item.bucket(data.id());
653 item.target_user(rec.id());
654 p.push(egCore.net.request(
656 'open-ils.actor.container.item.create',
657 egCore.auth.token(), 'user', item
659 function(){ added_count++ },
660 function(){ failed_count++ }
665 $q.all(p).then( function () {
666 if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
667 if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
671 var temp_scope = $scope;
672 $scope.openCreateBucketDialog = function() {
674 templateUrl: './circ/patron/bucket/t_bucket_create',
677 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
678 $scope.focusMe = true;
679 $scope.ok = function(args) { $uibModalInstance.close(args) }
680 $scope.cancel = function () { $uibModalInstance.dismiss() }
682 }).result.then(function (args) {
683 if (!args || !args.name) return;
684 bucketSvc.createBucket(args.name, args.desc).then(
687 $scope.bucketSvc.fetchBucket(id).then(function (b) {
691 $scope.gridControls.selectedItems()
693 $scope.bucketSvc.fetchUserBuckets(true);
702 function() {return $scope.gridControls.selectedItems()},
705 patronSvc.setPrimary(null, list[0]);
710 $scope.need_one_selected = function() {
711 var items = $scope.gridControls.selectedItems();
712 return (items.length > 0) ? false : true;
714 $scope.need_two_selected = function() {
715 var items = $scope.gridControls.selectedItems();
716 return (items.length == 2) ? false : true;
718 $scope.merge_patrons = function() {
719 var items = $scope.gridControls.selectedItems();
720 if (items.length != 2) return false;
723 angular.forEach(items, function(i) {
724 patron_ids.push(i.id());
726 egPatronMerge.do_merge(patron_ids).then(
728 // ensure that we're not drawing from cached
729 // resuts, as a successful merge just deleted a
731 delete patronSvc.lastSearch;
732 $scope.gridControls.refresh();
735 if (evt && evt.textcode == 'MERGE_SELF_NOT_ALLOWED') {
736 ngToast.warning(egCore.strings.MERGE_SELF_NOT_ALLOWED);
747 .controller('PatronMessagesCtrl',
748 ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
749 function($scope , $q , $routeParams, egCore , $uibModal , patronSvc , egCirc) {
750 $scope.initTab('messages', $routeParams.id);
751 var usr_id = $routeParams.id;
752 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
754 // setup date filters
755 var start = new Date(); // now - 1 year
756 start.setFullYear(start.getFullYear() - 1),
759 end_date : new Date()
762 function date_range() {
763 var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
764 var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
765 var today = new Date().toISOString().replace(/T.*/,'');
766 if (end == today) end = 'now';
772 var activeGrid = $scope.activeGridControls = {
773 setSort : function() {
776 setQuery : function() {
782 {stop_date : {'>' : 'now'}}
788 var archiveGrid = $scope.archiveGridControls = {
789 setSort : function() {
792 setQuery : function() {
796 stop_date : {'<=' : 'now'},
797 set_date : {between : date_range()}
802 $scope.removePenalty = function(selected) {
803 // the grid stores flattened penalties. Fetch penalty objects first
805 var ids = selected.map(function(s){ return s.id });
806 egCore.pcrud.search('ausp',
808 {atomic : true, authoritative : true}
811 ).then(function(penalties) {
812 return egCore.pcrud.remove(penalties);
814 // then refresh the grid
816 activeGrid.refresh();
820 $scope.archivePenalty = function(selected) {
821 // the grid stores flattened penalties. Fetch penalty objects first
823 var ids = selected.map(function(s){ return s.id });
824 egCore.pcrud.search('ausp',
826 {atomic : true, authoritative : true}
829 ).then(function(penalties) {
830 angular.forEach(penalties, function(p){ p.stop_date('now') });
831 return egCore.pcrud.update(penalties);
833 // then refresh the grid
835 activeGrid.refresh();
836 archiveGrid.refresh();
840 // leverage egEnv for caching
841 function fetchPenaltyTypes() {
843 return $q.when(egCore.env.csp.list);
844 return egCore.pcrud.search(
845 // id <= 100 are reserved for system use
846 'csp', {id : {'>': 100}}, {}, {atomic : true})
847 .then(function(penalties) {
848 egCore.env.absorbList(penalties, 'csp');
853 $scope.createPenalty = function() {
854 egCirc.create_penalty(usr_id).then(function() {
855 activeGrid.refresh();
856 // force a refresh of the user, since they may now
857 // have blocking penalties, etc.
858 patronSvc.setPrimary(patronSvc.current.id(), null, true);
862 $scope.editPenalty = function(selected) {
863 if (selected.length == 0) return;
865 // grab the penalty from the user object
866 var penalty = patronSvc.current.standing_penalties().filter(
867 function(p) {return p.id() == selected[0].id})[0];
869 egCirc.edit_penalty(penalty).then(function() {
870 activeGrid.refresh();
871 // force a refresh of the user, since they may now
872 // have blocking penalties, etc.
873 patronSvc.setPrimary(patronSvc.current.id(), null, true);
882 .controller('PatronVerifyCredentialsCtrl',
883 ['$scope','$routeParams','$location','egCore',
884 function($scope, $routeParams , $location , egCore) {
885 $scope.verified = null;
886 $scope.focusMe = true;
888 // called with a patron, pre-populate the form args
889 $scope.initTab('other', $routeParams.id).then(
891 if ($routeParams.id && $scope.patron()) {
892 $scope.prepop = true;
893 $scope.username = $scope.patron().usrname();
894 $scope.barcode = $scope.patron().card().barcode();
896 $scope.username = '';
898 $scope.password = '';
903 // verify login credentials
904 $scope.verify = function() {
905 $scope.verified = null;
906 $scope.notFound = false;
910 'open-ils.actor.verify_user_password',
911 egCore.auth.token(), $scope.barcode,
912 $scope.username, hex_md5($scope.password || '')
914 ).then(function(resp) {
915 $scope.focusMe = true;
916 if (evt = egCore.evt.parse(resp)) {
918 } else if (resp == 1) {
919 $scope.verified = true;
921 $scope.verified = false;
926 // load the main patron UI for the provided username or barcode
927 $scope.load = function($event) {
928 $scope.notFound = false;
929 $scope.verified = null;
933 'open-ils.actor.user.retrieve_id_by_barcode_or_username',
934 egCore.auth.token(), $scope.barcode, $scope.username
936 ).then(function(resp) {
939 $location.path('/circ/patron/' + resp + '/checkout');
943 // something went wrong...
944 $scope.focusMe = true;
945 if (evt = egCore.evt.parse(resp)) {
946 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
947 $scope.notFound = true;
956 // load() button sits within the verify form.
957 // avoid submitting the verify() form action on load()
958 $event.preventDefault();
962 .controller('PatronAlertsCtrl',
963 ['$scope','$routeParams','$location','egCore','patronSvc',
964 function($scope, $routeParams , $location , egCore , patronSvc) {
966 $scope.initTab('other', $routeParams.id)
968 $scope.patronExpired = patronSvc.patronExpired;
969 $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
970 $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
971 $scope.invalidAddresses = patronSvc.invalidAddresses;
976 .controller('PatronNotesCtrl',
977 ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
979 function($scope, $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
981 $scope.initTab('other', $routeParams.id);
982 var usr_id = $routeParams.id;
985 function refreshPage() {
987 egCore.pcrud.search('aun',
989 {flesh : 1, flesh_fields : {aun : ['creator']}},
990 {authoritative : true})
991 .then(null, null, function(note) {
992 $scope.notes.push(note);
996 // open the new-note dialog and create the note
997 $scope.newNote = function() {
999 templateUrl: './circ/patron/t_new_note_dialog',
1002 ['$scope', '$uibModalInstance',
1003 function($scope, $uibModalInstance) {
1004 $scope.focusNote = true;
1006 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1007 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1008 $scope.cancel = function () { $uibModalInstance.dismiss() }
1012 if (!args.value) return;
1013 var note = new egCore.idl.aun();
1015 note.title(args.title);
1016 note.value(args.value);
1017 note.pub(args.pub ? 't' : 'f');
1018 note.creator(egCore.auth.user().id());
1020 note.value(note.value() + ' [' + args.initials + ']');
1021 egCore.pcrud.create(note).then(function() {refreshPage()});
1026 // delete the selected note
1027 $scope.deleteNote = function(note) {
1028 egConfirmDialog.open(
1029 egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
1031 egCore.pcrud.remove(note).then(function() {refreshPage()});
1033 note_title : note.title(),
1034 create_date : note.create_date()
1038 // print the selected note
1039 $scope.printNote = function(note) {
1040 var hash = egCore.idl.toHash(note);
1041 hash.usr = egCore.idl.toHash($scope.patron());
1042 egCore.print.print({
1043 context : 'default',
1044 template : 'patron_note',
1045 scope : {note : hash}
1049 // perform the initial note fetch
1053 .controller('PatronGroupCtrl',
1054 ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1055 'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1056 function($scope, $routeParams , $q , $window , $timeout, $location , egCore ,
1057 patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1059 var usr_id = $routeParams.id;
1061 $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1063 var grid = $scope.gridControls = {
1064 activateItem : function(item) {
1065 $location.path('/circ/patron/' + item.id + '/checkout');
1067 itemRetrieved : function(item) {
1069 if (item.id == patronSvc.current.id()) {
1070 item.stats = patronSvc.patron_stats;
1073 // flesh stats for other group members
1074 patronSvc.getUserStats(item.id).then(function(stats) {
1076 $scope.totals.total_out += stats.checkouts.total_out;
1077 $scope.totals.overdue += stats.checkouts.overdue;
1081 setSort : function() {
1082 return ['create_date'];
1086 $scope.initTab('other', $routeParams.id)
1087 .then(function(redirect) {
1088 // if we are redirecting to the alerts page, avoid updating the
1090 if (redirect) return;
1091 // let initTab() fetch the user first so we can know the usrgroup
1094 usrgroup : patronSvc.current.usrgroup(),
1097 $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1100 $scope.removeFromGroup = function(selected) {
1102 angular.forEach(selected, function(user) {
1103 console.debug('removing user ' + user.id + ' from group');
1108 'open-ils.actor.usergroup.new',
1109 egCore.auth.token(), user.id, true
1114 $q.all(promises).then(function() {grid.refresh()});
1117 function addUserToGroup(user) {
1118 user.usrgroup(patronSvc.current.usrgroup());
1119 user.ischanged(true);
1122 'open-ils.actor.patron.update',
1123 egCore.auth.token(), user
1125 ).then(function() {grid.refresh()});
1128 // fetch each user ("selected" has flattened users)
1129 // update the usrgroup, then update the user object
1130 // After all updates are complete, refresh the grid.
1131 function moveUsersToGroup(target_user, selected) {
1134 angular.forEach(selected, function(user) {
1136 egCore.pcrud.retrieve('au', user.id)
1138 u.usrgroup(target_user.usrgroup());
1140 return egCore.net.request(
1142 'open-ils.actor.patron.update',
1143 egCore.auth.token(), u
1149 $q.all(promises).then(function() {grid.refresh()});
1152 function showMoveToGroupConfirm(barcode, selected, outbound) {
1155 egCore.pcrud.search('ac', {barcode : barcode})
1157 // fetch the fleshed user
1158 .then(function(card) {
1160 if (!card) return; // TODO: warn user
1162 egCore.pcrud.retrieve('au', card.usr())
1163 .then(function(user) {
1166 templateUrl: './circ/patron/t_move_to_group_dialog',
1169 '$scope','$uibModalInstance',
1170 function($scope , $uibModalInstance) {
1172 $scope.selected = selected;
1173 $scope.outbound = outbound;
1175 function(count) { $uibModalInstance.close() }
1177 function () { $uibModalInstance.dismiss() }
1180 }).result.then(function() {
1182 moveUsersToGroup(user, selected);
1184 addUserToGroup(user);
1191 // selected == move selected patrons to another patron's group
1192 // !selected == patron from a different group moves into our group
1193 function moveToGroup(selected, outbound) {
1194 egPromptDialog.open(
1195 egCore.strings.GROUP_ADD_USER, '',
1196 {ok : function(value) {
1198 showMoveToGroupConfirm(value, selected, outbound);
1203 $scope.moveToGroup = function() { moveToGroup([], false) };
1204 $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1206 $scope.cloneUser = function(selected) {
1207 if (!selected.length) return;
1208 var url = $location.absUrl().replace(
1210 '/patron/register/clone/' + selected[0].id);
1211 $window.open(url, '_blank').focus();
1214 $scope.retrieveSelected = function(selected) {
1215 if (!selected.length) return;
1216 angular.forEach(selected, function(usr) {
1217 $timeout(function() {
1218 var url = $location.absUrl().replace(
1220 '/patron/' + usr.id + '/checkout');
1221 $window.open(url, '_blank')
1228 .controller('PatronStatCatsCtrl',
1229 ['$scope','$routeParams','$q','egCore','patronSvc',
1230 function($scope, $routeParams , $q , egCore , patronSvc) {
1231 $scope.initTab('other', $routeParams.id)
1232 .then(function(redirect) {
1233 // Entries for org-visible stat cats are fleshed. Any others
1234 // have to be fleshed within.
1237 angular.forEach(patronSvc.current.stat_cat_entries(),
1239 if (!angular.isObject(entry.stat_cat())) {
1240 to_flesh[entry.stat_cat()] = entry;
1245 if (!Object.keys(to_flesh).length) return;
1247 egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1248 .then(null, null, function(cat) { // stream
1249 cat.owner(egCore.org.get(cat.owner())); // owner flesh
1250 to_flesh[cat.id()].stat_cat(cat);
1255 .controller('PatronSurveyCtrl',
1256 ['$scope','$routeParams','$location','egCore','patronSvc',
1257 function($scope, $routeParams , $location , egCore , patronSvc) {
1258 $scope.initTab('other', $routeParams.id);
1259 var usr_id = $routeParams.id;
1260 var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1262 $scope.surveys = [];
1263 var svr_responses = {};
1265 // fetch all survey responses for this user.
1266 egCore.pcrud.search('asvr',
1268 {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1271 // All responses collected and deduplicated.
1272 // Create one collection of responses per survey.
1274 angular.forEach(svr_responses, function(questions, survey_id) {
1275 var collection = {responses : []};
1276 angular.forEach(questions, function(response) {
1277 collection.survey = response.survey(); // same for one.
1278 collection.responses.push(response);
1280 $scope.surveys.push(collection);
1284 function(response) {
1286 // Discard responses for out-of-scope surveys.
1287 if (org_ids.indexOf(response.survey().owner()) < 0)
1290 // survey_id => question_id => response
1291 var svr_id = response.survey().id();
1292 var qst_id = response.question().id();
1294 if (!svr_responses[svr_id])
1295 svr_responses[svr_id] = [];
1297 if (!svr_responses[svr_id][qst_id]) {
1298 svr_responses[svr_id][qst_id] = response;
1301 // We have multiple responses for the same question.
1302 // For this UI we only care about the most recent response.
1303 if (response.effective_date() >
1304 svr_responses[svr_id][qst_id].effective_date())
1305 svr_responses[svr_id][qst_id] = response;
1311 .controller('PatronFetchLastCtrl',
1312 ['$scope','$location','egCore',
1313 function($scope , $location , egCore) {
1315 var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1317 return $location.path('/circ/patron/' + ids[0] + '/checkout');
1319 $scope.no_last = true;
1322 .controller('PatronTriggeredEventsCtrl',
1323 ['$scope','$routeParams','$location','egCore','patronSvc',
1324 function($scope, $routeParams, $location , egCore , patronSvc) {
1325 $scope.initTab('other', $routeParams.id);
1327 var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1328 url += '?patron_id=' + encodeURIComponent($routeParams.id);
1330 $scope.triggered_events_url = url;
1334 .controller('PatronMessageCenterCtrl',
1335 ['$scope','$routeParams','$location','egCore','patronSvc',
1336 function($scope, $routeParams, $location , egCore , patronSvc) {
1337 $scope.initTab('other', $routeParams.id);
1339 var url = $location.protocol() + '://' + $location.host()
1340 + egCore.env.basePath.replace(/\/staff.*/, '/actor/user/message');
1341 url += '/' + encodeURIComponent($routeParams.id);
1343 $scope.message_center_url = url;
1347 .controller('PatronPermsCtrl',
1348 ['$scope','$routeParams','$window','$location','egCore',
1349 function($scope , $routeParams , $window , $location , egCore) {
1350 $scope.initTab('other', $routeParams.id);
1352 var url = $location.absUrl().replace(
1353 /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1355 url += '?usr=' + encodeURIComponent($routeParams.id);
1357 // user_edit does not load the session via cookie. It uses URL
1358 // params or xulG instead. Pass via xulG.
1360 ses : egCore.auth.token(),
1361 on_patron_save : function() {
1362 $scope.funcs.reload();
1366 $scope.user_perms_url = url;