LP#1838995: Hold group buckets
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / circ / patron / app.js
1 /**
2  * Patron App
3  *
4  * Search, checkout, items out, holds, bills, edit, etc.
5  */
6
7 angular.module('egPatronApp', ['ngRoute', 'ui.bootstrap', 'egUserBucketMod', 
8     'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod', 'ngToast',
9     'egPatronSearchMod'])
10
11 .config(['ngToastProvider', function(ngToastProvider) {
12     ngToastProvider.configure({
13         verticalPosition: 'bottom',
14         animation: 'fade'
15     });
16 }])
17
18 .config(function($routeProvider, $locationProvider, $compileProvider) {
19     $locationProvider.html5Mode(true);
20     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
21         
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) {
26
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',
35                 'circ.tally_lost',
36                 'circ.obscure_dob',
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;
46             });
47         }
48
49         egCore.env.loadClasses.push('aous');
50
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([
55                 'profile',
56                 'net_access_level',
57                 'ident_type',
58                 'ident_type2',
59                 'cards',
60                 'groups'
61             ]);
62         }
63
64         return egCore.startup.go();
65     }]};
66
67     $routeProvider.when('/circ/patron/search', {
68         templateUrl: './circ/patron/t_search',
69         controller: 'PatronSearchCtrl',
70         resolve : resolver
71     });
72
73     $routeProvider.when('/circ/patron/bcsearch', {
74         templateUrl: './circ/patron/t_bcsearch',
75         controller: 'PatronBarcodeSearchCtrl',
76         resolve : resolver
77     });
78
79     $routeProvider.when('/circ/patron/credentials', {
80         templateUrl: './circ/patron/t_credentials',
81         controller: 'PatronVerifyCredentialsCtrl',
82         resolve : resolver
83     });
84
85     $routeProvider.when('/circ/patron/last', {
86         templateUrl: './circ/patron/t_last_patron',
87         controller: 'PatronFetchLastCtrl',
88         resolve : resolver
89     });
90
91     // the following require a patron ID
92
93     $routeProvider.when('/circ/patron/:id/alerts', {
94         templateUrl: './circ/patron/t_alerts',
95         controller: 'PatronAlertsCtrl',
96         resolve : resolver
97     });
98
99     $routeProvider.when('/circ/patron/:id/checkout', {
100         templateUrl: './circ/patron/t_checkout',
101         controller: 'PatronCheckoutCtrl',
102         resolve : resolver
103     });
104
105     $routeProvider.when('/circ/patron/:id/items_out', {
106         templateUrl: './circ/patron/t_items_out',
107         controller: 'PatronItemsOutCtrl',
108         resolve : resolver
109     });
110
111     $routeProvider.when('/circ/patron/:id/holds', {
112         templateUrl: './circ/patron/t_holds',
113         controller: 'PatronHoldsCtrl',
114         resolve : resolver
115     });
116
117     $routeProvider.when('/circ/patron/:id/holds/create', {
118         templateUrl: './circ/patron/t_holds_create',
119         controller: 'PatronHoldsCreateCtrl',
120         resolve : resolver
121     });
122
123     $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
124         templateUrl: './circ/patron/t_holds',
125         controller: 'PatronHoldsCtrl',
126         resolve : resolver
127     });
128
129     $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
130         templateUrl: './circ/patron/t_hold_details',
131         controller: 'PatronHoldDetailsCtrl',
132         resolve : resolver
133     });
134
135     $routeProvider.when('/circ/patron/:id/bills', {
136         templateUrl: './circ/patron/t_bills',
137         controller: 'PatronBillsCtrl',
138         resolve : resolver
139     });
140
141     $routeProvider.when('/circ/patron/:id/bill/:xact_id/:xact_tab', {
142         templateUrl: './circ/patron/t_xact_details',
143         controller: 'XactDetailsCtrl',
144         resolve : resolver
145     });
146
147     $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
148         templateUrl: './circ/patron/t_bill_history',
149         controller: 'BillHistoryCtrl',
150         resolve : resolver
151     });
152
153     $routeProvider.when('/circ/patron/:id/messages', {
154         templateUrl: './circ/patron/t_messages',
155         controller: 'PatronMessagesCtrl',
156         resolve : resolver
157     });
158
159     $routeProvider.when('/circ/patron/:id/edit', {
160         templateUrl: './circ/patron/t_edit',
161         controller: 'PatronRegCtrl',
162         resolve : resolver
163     });
164
165     $routeProvider.when('/circ/patron/:id/credentials', {
166         templateUrl: './circ/patron/t_credentials',
167         controller: 'PatronVerifyCredentialsCtrl',
168         resolve : resolver
169     });
170
171     $routeProvider.when('/circ/patron/:id/notes', {
172         templateUrl: './circ/patron/t_notes',
173         controller: 'PatronNotesCtrl',
174         resolve : resolver
175     });
176
177     $routeProvider.when('/circ/patron/:id/triggered_events', {
178         templateUrl: './circ/patron/t_triggered_events',
179         controller: 'PatronTriggeredEventsCtrl',
180         resolve : resolver
181     });
182
183     $routeProvider.when('/circ/patron/:id/message_center', {
184         templateUrl: './circ/patron/t_message_center',
185         controller: 'PatronMessageCenterCtrl',
186         resolve : resolver
187     });
188
189     $routeProvider.when('/circ/patron/:id/edit_perms', {
190         templateUrl: './circ/patron/t_edit_perms',
191         controller: 'PatronPermsCtrl',
192         resolve : resolver
193     });
194
195     $routeProvider.when('/circ/patron/:id/group', {
196         templateUrl: './circ/patron/t_group',
197         controller: 'PatronGroupCtrl',
198         resolve : resolver
199     });
200
201     $routeProvider.when('/circ/patron/:id/stat_cats', {
202         templateUrl: './circ/patron/t_stat_cats',
203         controller: 'PatronStatCatsCtrl',
204         resolve : resolver
205     });
206
207     $routeProvider.when('/circ/patron/:id/surveys', {
208         templateUrl: './circ/patron/t_surveys',
209         controller: 'PatronSurveyCtrl',
210         resolve : resolver
211     });
212
213     $routeProvider.when('/circ/patron/:id/hold_subscriptions', {
214         templateUrl: './circ/patron/t_hold_subscriptions',
215         controller: 'HoldSubscriptionsCtrl',
216         resolve : resolver
217     });
218
219     $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
220 })
221
222 /**
223  * Manages tabbed patron view.
224  * This is the parent scope of all patron tab scopes.
225  *
226  * */
227 .controller('PatronCtrl',
228        ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc',
229 function($scope,  $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc) {
230
231     $scope.is_patron_edit = function() {
232         return Boolean($location.path().match(/patron\/\d+\/edit$/));
233     }
234
235     // To support the fixed position patron edit actions bar,
236     // its markup has to live outside the scope of the patron 
237     // edit controller.  Insert a scope blob here that can be
238     // modifed from within the patron edit controller.
239     $scope.edit_passthru = {};
240
241     // returns true if a redirect occurs
242     function redirectToAlertPanel() {
243
244         $scope.alert_penalties = 
245             function() {return patronSvc.alert_penalties}
246
247         if (patronSvc.alertsShown()) return false;
248
249         // if the patron has any unshown alerts, show them now
250         if (patronSvc.hasAlerts && 
251             !$location.path().match(/alerts$/)) {
252
253             $location
254                 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
255                 .search('card', null);
256             return true;
257         }
258
259         // no alert required.  If the patron has fines and the show-bills
260         // OUS is applied, direct to the bills page.
261         if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
262             && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
263             && !$location.path().match(/bills$/)) {
264
265             $scope.tab = 'bills';
266             $location
267                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
268                 .search('card', null);
269
270             return true;
271         }
272
273         return false;
274     }
275
276     // called after each route-specified controller is instantiated.
277     // this doubles as a way to inform the top-level controller that
278     // egStartup.go() has completed, which means we are clear to 
279     // fetch the patron, etc.
280     $scope.initTab = function(tab, patron_id) {
281         console.log('init tab ' + tab);
282         $scope.tab = tab;
283         $scope.aous = egCore.env.aous;
284         $scope.auth_user_id = egCore.auth.user().id();
285
286         if (patron_id) {
287             $scope.patron_id = patron_id;
288             return patronSvc.setPrimary($scope.patron_id)
289             .then(function() {
290                 // the page title context label comes from the tab.
291                 egCore.strings.setPageTitle(
292                     egCore.strings.PAGE_TITLE_PATRON_NAME, 
293                     egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
294                     {   lname : patronSvc.current.family_name(),
295                         fname : patronSvc.current.first_given_name(),
296                         mname : patronSvc.current.second_given_name()
297                     }
298                 );
299             })
300             .then(function() {return patronSvc.checkAlerts()})
301             .then(redirectToAlertPanel)
302             .then(function(){
303                 $scope.ident_type_name = $scope.patron().ident_type().name()
304                 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
305             });
306         } else {
307             // No patron, use the tab name as the page title.
308             egCore.strings.setPageTitle(
309                 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
310         }
311         return $q.when();
312     }
313
314     $scope._show_dob = {};
315     $scope.show_dob = function (val) {
316         if ($scope.patron()) {
317             if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
318             return $scope._show_dob[$scope.patron().id()];
319         }
320         return !egCore.env.aous['circ.obscure_dob'];
321     }
322         
323     $scope.obscure_dob = function() { 
324         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
325     }
326     $scope.now_show_dob = function() { 
327         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
328             $scope.show_dob() : true; 
329     }
330
331     $scope.patron = function() { return patronSvc.current }
332     $scope.patron_stats = function() { return patronSvc.patron_stats }
333     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
334     $scope.hasAlerts = function() { return patronSvc.hasAlerts }
335     $scope.isPatronExpired = function() { return patronSvc.patronExpired }
336     $scope.doesPatronExpireSoon = function() { return patronSvc.patronExpiresSoon }
337
338     $scope.print_address = function(addr) {
339         egCore.print.print({
340             context : 'default', 
341             template : 'patron_address', 
342             scope : {
343                 patron : egCore.idl.toHash(patronSvc.current),
344                 address : egCore.idl.toHash(addr)
345             }
346         });
347     }
348
349     $scope.copy_address = function(addr) {
350         // Alas, navigator.clipboard is not yet supported in FF and others.
351         var lNode = document.querySelector('#patron-address-copy-' + addr.id());
352
353         // Un-hide the textarea just long enough to copy its data.
354         // Using node.style instead of ng-show/ng-hide in hopes it 
355         // will be quicker, so the user never sees the textarea.
356         lNode.style.visibility = 'visible';
357         lNode.focus();
358         lNode.select();
359
360         if (!document.execCommand('copy')) {
361             console.error('Copy command failed');
362         }
363
364         lNode.style.visibility = 'hidden';
365     }
366
367     $scope.toggle_expand_summary = function() {
368         if ($scope.collapsePatronSummary) {
369             $scope.collapsePatronSummary = false;
370             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
371         } else {
372             $scope.collapsePatronSummary = true;
373             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
374         }
375     }
376     
377     // always expand the patron summary in the search UI, regardless
378     // of stored preference.
379     $scope.collapse_summary = function() {
380         return $scope.tab != 'search' && $scope.collapsePatronSummary;
381     }
382
383     function _purge_account(dest_usr,override) {
384         egNet.request(
385             'open-ils.actor',
386             'open-ils.actor.user.delete' + (override ? '.override' : ''),
387             egCore.auth.token(),
388             $scope.patron().id(),
389             dest_usr
390         ).then(function(resp){
391             if (evt = egCore.evt.parse(resp)) {
392                 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
393                     egConfirmDialog.open(
394                         egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
395                         {ok : function() {
396                             _purge_account(dest_usr,true);
397                         }}
398                     );
399                 } else {
400                     alert(js2JSON(evt));
401                 }
402             } else {
403                 location.href = egCore.env.basePath + '/circ/patron/search';
404             }
405         });
406     }
407
408     function _purge_account_with_destination(dest_barcode) {
409         egCore.pcrud.search('ac', {barcode : dest_barcode})
410         .then(function(card) {
411             if (!card) {
412                 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
413             } else {
414                 _purge_account(card.usr());
415             }
416         });
417     }
418
419     $scope.purge_account = function() {
420         egConfirmDialog.open(
421             egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
422             {ok : function() {
423                 egConfirmDialog.open(
424                     egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
425                     {ok : function() {
426                         egNet.request(
427                             'open-ils.actor',
428                             'open-ils.actor.user.has_work_perm_at',
429                             egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
430                         ).then(function(resp) {
431                             var is_staff = resp.length > 0;
432                             if (is_staff) {
433                                 egPromptDialog.open(
434                                     egCore.strings.PATRON_PURGE_STAFF_PROMPT,
435                                     null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
436                                     {ok : function(barcode) {_purge_account_with_destination(barcode)}}
437                                 );
438                             } else {
439                                 _purge_account();
440                             }
441                         });
442                     }
443                 });
444             }
445         });
446     }
447
448     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
449     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
450 }])
451
452 .controller('PatronBarcodeSearchCtrl',
453        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc','$uibModal','$q',
454 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc , $uibModal , $q) {
455     $scope.selectMe = true; // focus text input
456     patronSvc.clearPrimary(); // clear the default user
457
458     // jump to the patron checkout UI
459     function loadPatron(user_id) {
460         egCore.audio.play('success.patron.by_barcode');
461         $location
462         .path('/circ/patron/' + user_id + '/checkout')
463         .search('card', $scope.args.barcode);
464         patronSvc.search_barcode = $scope.args.barcode;
465     }
466
467     // create an opt-in=yes response for the loaded user
468     function createOptIn(user_id) {
469         egCore.net.request(
470             'open-ils.actor',
471             'open-ils.actor.user.org_unit_opt_in.create',
472             egCore.auth.token(), user_id).then(function(resp) {
473                 if (evt = egCore.evt.parse(resp)) return alert(evt);
474                 loadPatron(user_id);
475             }
476         );
477     }
478
479     $scope.submitBarcode = function(args) {
480         $scope.bcNotFound = null;
481         $scope.optInRestricted = false;
482         if (!args.barcode) return;
483         args.barcode = args.barcode.replace(/^\s/g,'');
484         args.barcode = args.barcode.replace(/\s$/g,'');
485         // blur so next time it's set to true it will re-apply select()
486         $scope.selectMe = false;
487
488         var user_id;
489
490         // given a scanned barcode, this function finds any matching users
491         // and handles multiple matches due to barcode completion
492         function handleBarcodeCompletion(scanned_barcode) {
493             var deferred = $q.defer();
494
495             egCore.net.request(
496                 'open-ils.actor',
497                 'open-ils.actor.get_barcodes',
498                 egCore.auth.token(), egCore.auth.user().ws_ou(), 
499                 'actor', scanned_barcode)
500
501             .then(function(resp) { // get_barcodes
502
503                 if (evt = egCore.evt.parse(resp)) {
504                     alert(evt); // FIXME
505                     deferred.reject();
506                     return;
507                 }
508
509                 if (!resp || !resp[0]) {
510                     $scope.bcNotFound = args.barcode;
511                     $scope.selectMe = true;
512                     egCore.audio.play('warning.patron.not_found');
513                     deferred.reject();
514                     return;
515                 }
516
517                 if (resp.length == 1) {
518                     // exactly one matching barcode: return it
519                     deferred.resolve();
520                     user_id = resp[0].id;
521                 } else {
522                     // multiple matching barcodes: let the user pick one 
523                     var barcode_map = {};
524                     var matches = [];
525                     var promises = [];
526                     var selected_barcode;
527                     angular.forEach(resp, function(match) {
528                         promises.push(
529                             egUser.get(match.id, {useFields : ['home_ou']}).then(function(user) {
530                                 barcode_map[match.barcode] = user.id();
531                                 matches.push( {
532                                     barcode: match.barcode,
533                                     title: user.first_given_name() + ' ' + user.family_name(),
534                                     org_name: user.home_ou().name(),
535                                     org_shortname: user.home_ou().shortname()
536                                 });
537                             })
538                         );
539                     });
540                     return $q.all(promises)
541                     .then(function() {
542                         $uibModal.open({
543                             templateUrl: './circ/share/t_barcode_choice_dialog',
544                             controller:
545                                 ['$scope', '$uibModalInstance',
546                                 function($scope, $uibModalInstance) {
547                                 $scope.matches = matches;
548                                 $scope.ok = function(barcode) {
549                                     $uibModalInstance.close();
550                                     selected_barcode = barcode;
551                                 }
552                                 $scope.cancel = function() {$uibModalInstance.dismiss()}
553                             }],
554                         }).result.then(function() {
555                             deferred.resolve();
556                             user_id = barcode_map[selected_barcode];
557                         });
558                     });
559                 }
560             });
561             return deferred.promise;
562         }
563
564         // call our function to lookup matching users for the scanned barcode
565         handleBarcodeCompletion(args.barcode).then(function() {
566
567             // see if an opt-in request is needed
568             return egCore.net.request(
569                 'open-ils.actor',
570                 'open-ils.actor.user.org_unit_opt_in.check',
571                 egCore.auth.token(), user_id
572             ).then(function(optInResp) { // opt_in_check
573
574                 if (evt = egCore.evt.parse(optInResp)) {
575                     alert(evt); // FIXME
576                     return;
577                 }
578
579                 if (optInResp == 2) {
580                     // opt-in disallowed at this location by patron's home library
581                     $scope.optInRestricted = true;
582                     $scope.selectMe = true;
583                     egCore.audio.play('warning.patron.opt_in_restricted');
584                     return;
585                 }
586             
587                 if (optInResp == 1) {
588                     // opt-in handled or not needed
589                     return loadPatron(user_id);
590                 }
591
592                 // opt-in needed, show the opt-in dialog
593                 egUser.get(user_id, {useFields : []})
594
595                 .then(function(user) { // retrieve user
596                     var org = egCore.org.get(user.home_ou());
597                     egConfirmDialog.open(
598                         egCore.strings.OPT_IN_DIALOG_TITLE,
599                         egCore.strings.OPT_IN_DIALOG,
600                         {   family_name : user.family_name(),
601                             first_given_name : user.first_given_name(),
602                             org_name : org.name(),
603                             org_shortname : org.shortname(),
604                             ok : function() { createOptIn(user.id()) },
605                             cancel : function() {}
606                         }
607                     );
608                 })
609             })
610         })
611     }
612 }])
613
614
615 /**
616  * Manages patron search
617  */
618 .controller('PatronSearchCtrl',
619        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
620        '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
621        'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
622 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore , ngToast,
623          $filter,  egUser,  patronSvc , egGridDataProvider , $document , bucketSvc,
624         egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
625
626     angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
627     $scope.initTab('search');
628
629     $scope.gridControls = {
630         activateItem : function(item) {
631             $location.path('/circ/patron/' + item.id() + '/checkout');
632         },
633         selectedItems : function() { return [] }
634     }
635
636     $scope.bucketSvc = bucketSvc;
637     $scope.bucketSvc.fetchUserBuckets();
638     $scope.bucketSvc.fetchUserSubscriptions();
639     $scope.addToBucket = function(item, data, recs) {
640         if (recs.length == 0) return;
641         var added_count = 0;
642         var failed_count = 0;
643         var promise = $q.when();
644         angular.forEach(recs,
645             function(rec) {
646                 var item = new egCore.idl.cubi();
647                 item.bucket(data.id());
648                 item.target_user(rec.id());
649                 promise = promise.then(function() {
650                     return egCore.net.request(
651                         'open-ils.actor',
652                         'open-ils.actor.container.item.create',
653                         egCore.auth.token(), 'user', item, 1
654                     );
655                 }).then(
656                     function(){ added_count++ },
657                     function(){ failed_count++ }
658                 );
659             }
660         );
661
662         promise.then( function () {
663             if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
664             if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
665         });
666     }
667
668     var temp_scope = $scope;
669     $scope.openCreateBucketDialog = function() {
670         $uibModal.open({
671             templateUrl: './circ/patron/bucket/t_bucket_create',
672             backdrop: 'static',
673             controller:
674                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
675                 $scope.focusMe = true;
676                 $scope.ok = function(args) { $uibModalInstance.close(args) }
677                 $scope.cancel = function () { $uibModalInstance.dismiss() }
678             }]
679         }).result.then(function (args) {
680             if (!args || !args.name) return;
681             bucketSvc.createBucket(args.name, args.desc).then(
682                 function(id) {
683                     if (id) {
684                         $scope.bucketSvc.fetchBucket(id).then(function (b) {
685                             $scope.addToBucket(
686                                 null,
687                                 b,
688                                 $scope.gridControls.selectedItems()
689                             );
690                             $scope.bucketSvc.fetchUserBuckets(true);
691                         });
692                     }
693                 }
694             );
695         });
696     }
697
698     $scope.$watch(
699         function() {return $scope.gridControls.selectedItems()},
700         function(list) {
701             if (list[0]) 
702                 patronSvc.setPrimary(null, list[0]);
703         },
704         true
705     );
706
707     $scope.need_one_selected = function() {
708         var items = $scope.gridControls.selectedItems();
709         return (items.length > 0) ? false : true;
710     }
711     $scope.need_two_selected = function() {
712         var items = $scope.gridControls.selectedItems();
713         return (items.length == 2) ? false : true;
714     }
715     $scope.merge_patrons = function() {
716         var items = $scope.gridControls.selectedItems();
717         if (items.length != 2) return false;
718
719         var patron_ids = [];
720         angular.forEach(items, function(i) {
721             patron_ids.push(i.id());
722         });
723         egPatronMerge.do_merge(patron_ids).then(
724             function() {
725                 // ensure that we're not drawing from cached
726                 // resuts, as a successful merge just deleted a
727                 // record
728                 delete patronSvc.lastSearch;
729                 $scope.gridControls.refresh();
730             },
731             function(evt) {
732                 if (evt && evt.textcode == 'MERGE_SELF_NOT_ALLOWED') {
733                     ngToast.warning(egCore.strings.MERGE_SELF_NOT_ALLOWED);
734                 }
735             }
736         );
737     }
738    
739 }])
740
741 /**
742  * Manages messages
743  */
744 .controller('PatronMessagesCtrl',
745        ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
746 function($scope , $q , $routeParams,  egCore , $uibModal , patronSvc , egCirc) {
747     $scope.initTab('messages', $routeParams.id);
748     var usr_id = $routeParams.id;
749     var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
750
751     // setup date filters
752     var start = new Date(); // now - 1 year
753     start.setFullYear(start.getFullYear() - 1),
754     $scope.dates = {
755         start_date : start,
756         end_date : new Date()
757     }
758
759     function date_range() {
760         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
761         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
762         var today = new Date().toISOString().replace(/T.*/,'');
763         if (end == today) end = 'now';
764         return [start, end];
765     }
766
767     // grid queries
768    
769     var activeGrid = $scope.activeGridControls = {
770         setSort : function() {
771             return ['set_date'];
772         },
773         setQuery : function() {
774             return {
775                 usr : usr_id,
776                 org_unit : org_ids,
777                 '-or' : [
778                     {stop_date : null},
779                     {stop_date : {'>' : 'now'}}
780                 ]
781             }
782         }
783     }
784
785     var archiveGrid = $scope.archiveGridControls = {
786         setSort : function() {
787             return ['set_date'];
788         },
789         watchQuery : function() {
790             return {
791                 usr : usr_id, 
792                 org_unit : org_ids,
793                 stop_date : {'<=' : 'now'},
794                 set_date : {between : date_range()}
795             };
796         }
797     };
798
799     $scope.removePenalty = function(selected) {
800         // the grid stores flattened penalties.  Fetch penalty objects first
801
802         var ids = selected.map(function(s){ return s.id });
803         egCore.pcrud.search('ausp', 
804             {id : ids}, {}, 
805             {atomic : true, authoritative : true}
806
807         // then delete them
808         ).then(function(penalties) {
809             return egCore.pcrud.remove(penalties);
810
811         // then refresh the grid
812         }).then(function() {
813             activeGrid.refresh();
814         });
815     }
816
817     $scope.archivePenalty = function(selected) {
818         // the grid stores flattened penalties.  Fetch penalty objects first
819
820         var ids = selected.map(function(s){ return s.id });
821         egCore.pcrud.search('ausp', 
822             {id : ids}, {}, 
823             {atomic : true, authoritative : true}
824
825         // then delete them
826         ).then(function(penalties) {
827             angular.forEach(penalties, function(p){ p.stop_date('now') });
828             return egCore.pcrud.update(penalties);
829
830         // then refresh the grid
831         }).then(function() {
832             activeGrid.refresh();
833             archiveGrid.refresh();
834         });
835     }
836
837     // leverage egEnv for caching
838     function fetchPenaltyTypes() {
839         if (egCore.env.csp) 
840             return $q.when(egCore.env.csp.list);
841         return egCore.pcrud.search(
842             // id <= 100 are reserved for system use
843             'csp', {id : {'>': 100}}, {}, {atomic : true})
844         .then(function(penalties) {
845             egCore.env.absorbList(penalties, 'csp');
846             return penalties;
847         });
848     }
849
850     $scope.createPenalty = function() {
851         egCirc.create_penalty(usr_id).then(function() {
852             activeGrid.refresh();
853             // force a refresh of the user, since they may now
854             // have blocking penalties, etc.
855             patronSvc.setPrimary(patronSvc.current.id(), null, true);
856         });
857     }
858
859     $scope.editPenalty = function(selected) {
860         if (selected.length == 0) return;
861
862         // grab the penalty from the user object
863         var penalty = patronSvc.current.standing_penalties().filter(
864             function(p) {return p.id() == selected[0].id})[0];
865
866         egCirc.edit_penalty(penalty).then(function() {
867             activeGrid.refresh();
868             // force a refresh of the user, since they may now
869             // have blocking penalties, etc.
870             patronSvc.setPrimary(patronSvc.current.id(), null, true);
871         });
872     }
873 }])
874
875
876 /**
877  * Credentials tester
878  */
879 .controller('PatronVerifyCredentialsCtrl',
880        ['$scope','$routeParams','$location','egCore',
881 function($scope,  $routeParams , $location , egCore) {
882     $scope.verified = null;
883     $scope.focusMe = true;
884
885     // called with a patron, pre-populate the form args
886     $scope.initTab('other', $routeParams.id).then(
887         function() {
888             if ($routeParams.id && $scope.patron()) {
889                 $scope.prepop = true;
890                 $scope.username = $scope.patron().usrname();
891                 $scope.barcode = $scope.patron().card().barcode();
892             } else {
893                 $scope.username = '';
894                 $scope.barcode = '';
895                 $scope.password = '';
896             }
897         }
898     );
899
900     // verify login credentials
901     $scope.verify = function() {
902         $scope.verified = null;
903         $scope.notFound = false;
904
905         egCore.net.request(
906             'open-ils.actor',
907             'open-ils.actor.verify_user_password',
908             egCore.auth.token(), $scope.barcode,
909             $scope.username, hex_md5($scope.password || '')
910
911         ).then(function(resp) {
912             $scope.focusMe = true;
913             if (evt = egCore.evt.parse(resp)) {
914                 alert(evt);
915             } else if (resp == 1) {
916                 $scope.verified = true;
917             } else {
918                 $scope.verified = false;
919             }
920         });
921     }
922
923     // load the main patron UI for the provided username or barcode
924     $scope.load = function($event) {
925         $scope.notFound = false;
926         $scope.verified = null;
927
928         egCore.net.request(
929             'open-ils.actor',
930             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
931             egCore.auth.token(), $scope.barcode, $scope.username
932
933         ).then(function(resp) {
934
935             if (Number(resp)) {
936                 $location.path('/circ/patron/' + resp + '/checkout');
937                 return;
938             }
939
940             // something went wrong...
941             $scope.focusMe = true;
942             if (evt = egCore.evt.parse(resp)) {
943                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
944                     $scope.notFound = true;
945                     return;
946                 }
947                 return alert(evt);
948             } else {
949                 alert(resp);
950             }
951         });
952
953         // load() button sits within the verify form.  
954         // avoid submitting the verify() form action on load()
955         $event.preventDefault();
956     }
957 }])
958
959 .controller('PatronAlertsCtrl',
960        ['$scope','$routeParams','$location','egCore','patronSvc',
961 function($scope,  $routeParams , $location , egCore , patronSvc) {
962
963     $scope.initTab('other', $routeParams.id)
964     .then(function() {
965         $scope.patronExpired = patronSvc.patronExpired;
966         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
967         $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
968         $scope.invalidAddresses = patronSvc.invalidAddresses;
969     });
970
971 }])
972
973 .controller('HoldSubscriptionsCtrl',
974        ['$scope','$q','$routeParams','$location','egCore','patronSvc','bucketSvc','egGridDataProvider','egConfirmDialog','$timeout','$window',
975 function($scope,  $q , $routeParams , $location , egCore , patronSvc,  bucketSvc,  egGridDataProvider,  egConfirmDialog,  $timeout,  $window) {
976
977     $scope.initTab('other', $routeParams.id);
978
979     $scope.bucket_ids = [];
980     $scope.bucket_items = [];
981     $scope.buckets = [];
982
983     $scope.gridControls = {
984         activateItem : function (item) {
985             var url = $location.absUrl().replace(
986                 /\/circ\/patron\/.*/, 
987                 '/cat/bucket/batch_hold/view/' + item.id());
988             $window.open(url, '_blank').focus();
989         }
990     };
991
992     $scope.gridDataProvider = egGridDataProvider.instance({
993         get : function(offset, count) {
994             return this.arrayNotifier($scope.buckets, offset, count);
995         }
996     });
997
998     function fetchSubscriptions() {
999         $scope.bucket_ids = [];
1000         $scope.bucket_items = [];
1001         $scope.buckets = [];
1002         egCore.pcrud.search('cubi',
1003             { target_user : $routeParams.id }
1004         ).then(
1005             function() {
1006                 if ($scope.bucket_ids.length > 0) {
1007                     egCore.pcrud.search('cub',
1008                         { id : $scope.bucket_ids, btype : 'hold_subscription' }
1009                     ).then(
1010                         function() { $scope.gridControls.refresh() },
1011                         null,
1012                         function(b) {
1013                             $scope.buckets.push(b);
1014                             b.items( $scope.bucket_items.filter(i => i.bucket() == b.id()) );
1015                         }
1016                     );
1017                 } else {
1018                     $scope.gridControls.refresh();
1019                 }
1020             },
1021             null,
1022             function(i) {
1023                 $scope.bucket_ids.push(i.bucket());
1024                 $scope.bucket_items.push(i);
1025             }
1026         )
1027     }
1028
1029     $scope.removeSubscriptions = function (buckets) {
1030         return egConfirmDialog.open(
1031             egCore.strings.REMOVE_HOLD_SUBSCRIPTIONS,'',{}
1032         ).result.then(function() {
1033             var promises = [];
1034
1035             angular.forEach(buckets, function(b) {
1036                 angular.forEach(b.items(), function (i) {
1037                     promises.push(bucketSvc.detachUser(i.id()));
1038                 })
1039             });
1040
1041             $q.all(promises).then(fetchSubscriptions);
1042         });
1043     }
1044
1045     $timeout(fetchSubscriptions);
1046
1047 }])
1048
1049 .controller('PatronNotesCtrl',
1050        ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
1051         'egConfirmDialog',
1052 function($scope,  $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
1053          egConfirmDialog) {
1054     $scope.initTab('other', $routeParams.id);
1055     var usr_id = $routeParams.id;
1056
1057     // fetch the notes
1058     function refreshPage() {
1059         $scope.notes = [];
1060         egCore.pcrud.search('aun', 
1061             {usr : usr_id}, 
1062             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
1063             {authoritative : true})
1064         .then(null, null, function(note) {
1065             $scope.notes.push(note);
1066         });
1067     }
1068
1069     // open the new-note dialog and create the note
1070     $scope.newNote = function() {
1071         $uibModal.open({
1072             templateUrl: './circ/patron/t_new_note_dialog',
1073             backdrop: 'static',
1074             controller: 
1075                 ['$scope', '$uibModalInstance',
1076             function($scope, $uibModalInstance) {
1077                 $scope.focusNote = true;
1078                 $scope.args = {};
1079                 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
1080                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
1081                 $scope.cancel = function () { $uibModalInstance.dismiss() }
1082             }],
1083         }).result.then(
1084             function(args) {
1085                 if (!args.value) return;
1086                 var note = new egCore.idl.aun();
1087                 note.usr(usr_id);
1088                 note.title(args.title);
1089                 note.value(args.value);
1090                 note.pub(args.pub ? 't' : 'f');
1091                 note.creator(egCore.auth.user().id());
1092                 if (args.initials) 
1093                     note.value(note.value() + ' [' + args.initials + ']');
1094                 egCore.pcrud.create(note).then(function() {refreshPage()});
1095             }
1096         );
1097     }
1098
1099     // delete the selected note
1100     $scope.deleteNote = function(note) {
1101         egConfirmDialog.open(
1102             egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
1103             {ok : function() {
1104                 egCore.pcrud.remove(note).then(function() {refreshPage()});
1105             },
1106             note_title : note.title(),
1107             create_date : note.create_date()
1108         });
1109     }
1110
1111     // print the selected note
1112     $scope.printNote = function(note) {
1113         var hash = egCore.idl.toHash(note);
1114         hash.usr = egCore.idl.toHash($scope.patron());
1115         egCore.print.print({
1116             context : 'default', 
1117             template : 'patron_note', 
1118             scope : {note : hash}
1119         });
1120     }
1121
1122     // perform the initial note fetch
1123     refreshPage();
1124 }])
1125
1126 .controller('PatronGroupCtrl',
1127        ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1128         'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1129 function($scope,  $routeParams , $q , $window , $timeout,  $location , egCore ,
1130          patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1131
1132     var usr_id = $routeParams.id;
1133
1134     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1135
1136     var grid = $scope.gridControls = {
1137         activateItem : function(item) {
1138             $location.path('/circ/patron/' + item.id + '/checkout');
1139         },
1140         itemRetrieved : function(item) {
1141
1142             if (item.id == patronSvc.current.id()) {
1143                 item.stats = patronSvc.patron_stats;
1144
1145             } else {
1146                 // flesh stats for other group members
1147                 patronSvc.getUserStats(item.id).then(function(stats) {
1148                     item.stats = stats;
1149                     $scope.totals.total_out += stats.checkouts.total_out; 
1150                     $scope.totals.overdue += stats.checkouts.overdue; 
1151                 });
1152             }
1153         },
1154         setSort : function() {
1155             return ['create_date'];
1156         },
1157         watchQuery: function() {
1158             if (patronSvc.current) {
1159                 return {
1160                     usrgroup : patronSvc.current.usrgroup(),
1161                     deleted : 'f'
1162                 };
1163             }
1164             return null;
1165         }
1166     }
1167
1168     $scope.initTab('other', $routeParams.id)
1169     .then(function(redirect) {
1170         // if we are redirecting to the alerts page, avoid updating the
1171         // grid query.
1172         if (redirect) return;
1173         // let initTab() fetch the user first so we can know the usrgroup
1174         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1175     });
1176
1177     $scope.removeFromGroup = function(selected) {
1178         var promises = [];
1179         angular.forEach(selected, function(user) {
1180             console.debug('removing user ' + user.id + ' from group');
1181
1182             promises.push(
1183                 egCore.net.request(
1184                     'open-ils.actor',
1185                     'open-ils.actor.usergroup.new',
1186                     egCore.auth.token(), user.id, true
1187                 )
1188             );
1189         });
1190
1191         $q.all(promises).then(function() {grid.refresh()});
1192     }
1193
1194     function addUserToGroup(user) {
1195         user.usrgroup(patronSvc.current.usrgroup());
1196         user.ischanged(true);
1197         egCore.net.request(
1198             'open-ils.actor',
1199             'open-ils.actor.patron.update',
1200             egCore.auth.token(), user
1201
1202         ).then(function() {grid.refresh()});
1203     }
1204
1205     // fetch each user ("selected" has flattened users)
1206     // update the usrgroup, then update the user object
1207     // After all updates are complete, refresh the grid.
1208     function moveUsersToGroup(target_user, selected) {
1209         var promises = [];
1210
1211         angular.forEach(selected, function(user) {
1212             promises.push(
1213                 egCore.pcrud.retrieve('au', user.id)
1214                 .then(function(u) {
1215                     u.usrgroup(target_user.usrgroup());
1216                     u.ischanged(true);
1217                     return egCore.net.request(
1218                         'open-ils.actor',
1219                         'open-ils.actor.patron.update',
1220                         egCore.auth.token(), u
1221                     );
1222                 })
1223             );
1224         });
1225
1226         $q.all(promises).then(function() {grid.refresh()});
1227     }
1228
1229     function showMoveToGroupConfirm(barcode, selected, outbound) {
1230
1231         // find the user
1232         egCore.pcrud.search('ac', {barcode : barcode})
1233
1234         // fetch the fleshed user
1235         .then(function(card) {
1236
1237             if (!card) return; // TODO: warn user
1238
1239             egCore.pcrud.retrieve('au', card.usr())
1240             .then(function(user) {
1241                 user.card(card);
1242                 $uibModal.open({
1243                     templateUrl: './circ/patron/t_move_to_group_dialog',
1244                     backdrop: 'static',
1245                     controller: [
1246                                 '$scope','$uibModalInstance',
1247                         function($scope , $uibModalInstance) {
1248                             $scope.user = user;
1249                             $scope.selected = selected;
1250                             $scope.outbound = outbound;
1251                             $scope.ok = 
1252                                 function(count) { $uibModalInstance.close() }
1253                             $scope.cancel = 
1254                                 function () { $uibModalInstance.dismiss() }
1255                         }
1256                     ]
1257                 }).result.then(function() {
1258                     if (outbound) {
1259                         moveUsersToGroup(user, selected);
1260                     } else {
1261                         addUserToGroup(user);
1262                     }
1263                 });
1264             });
1265         });
1266     }
1267
1268     // selected == move selected patrons to another patron's group
1269     // !selected == patron from a different group moves into our group
1270     function moveToGroup(selected, outbound) {
1271         egPromptDialog.open(
1272             egCore.strings.GROUP_ADD_USER, '',
1273             {ok : function(value) {
1274                 if (value) 
1275                     showMoveToGroupConfirm(value, selected, outbound);
1276             }}
1277         );
1278     }
1279
1280     $scope.moveToGroup = function() { moveToGroup([], false) };
1281     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1282
1283     $scope.cloneUser = function(selected) {
1284         if (!selected.length) return;
1285         var url = $location.absUrl().replace(
1286             /\/patron\/.*/, 
1287             '/patron/register/clone/' + selected[0].id);
1288         $window.open(url, '_blank').focus();
1289     }
1290
1291     $scope.retrieveSelected = function(selected) {
1292         if (!selected.length) return;
1293         angular.forEach(selected, function(usr) {
1294             $timeout(function() {
1295                 var url = $location.absUrl().replace(
1296                     /\/patron\/.*/,
1297                     '/patron/' + usr.id + '/checkout');
1298                 $window.open(url, '_blank')
1299             });
1300         });
1301     }
1302
1303 }])
1304
1305 .controller('PatronStatCatsCtrl',
1306        ['$scope','$routeParams','$q','egCore','patronSvc',
1307 function($scope,  $routeParams , $q , egCore , patronSvc) {
1308     $scope.initTab('other', $routeParams.id)
1309     .then(function(redirect) {
1310         // Entries for org-visible stat cats are fleshed.  Any others
1311         // have to be fleshed within.
1312
1313         var to_flesh = {};
1314         angular.forEach(patronSvc.current.stat_cat_entries(), 
1315             function(entry) {
1316                 if (!angular.isObject(entry.stat_cat())) {
1317                     to_flesh[entry.stat_cat()] = entry;
1318                 }
1319             }
1320         );
1321
1322         if (!Object.keys(to_flesh).length) return;
1323
1324         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1325         .then(null, null, function(cat) { // stream
1326             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1327             to_flesh[cat.id()].stat_cat(cat);
1328         });
1329     });
1330 }])
1331
1332 .controller('PatronSurveyCtrl',
1333        ['$scope','$routeParams','$location','egCore','patronSvc',
1334 function($scope,  $routeParams , $location , egCore , patronSvc) {
1335     $scope.initTab('other', $routeParams.id);
1336     var usr_id = $routeParams.id;
1337     var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1338
1339     $scope.surveys = [];
1340     var svr_responses = {};
1341
1342     // fetch all survey responses for this user.
1343     egCore.pcrud.search('asvr',
1344         {usr : usr_id},
1345         {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1346     ).then(
1347         function() {
1348             // All responses collected and deduplicated.
1349             // Create one collection of responses per survey.
1350
1351             angular.forEach(svr_responses, function(questions, survey_id) {
1352                 var collection = {responses : []};
1353                 angular.forEach(questions, function(response) {
1354                     collection.survey = response.survey(); // same for one.
1355                     collection.responses.push(response);
1356                 });
1357                 $scope.surveys.push(collection);
1358             });
1359         },
1360         null, 
1361         function(response) {
1362
1363             // Discard responses for out-of-scope surveys.
1364             if (org_ids.indexOf(response.survey().owner()) < 0) 
1365                 return;
1366
1367             // survey_id => question_id => response
1368             var svr_id = response.survey().id();
1369             var qst_id = response.question().id();
1370
1371             if (!svr_responses[svr_id]) 
1372                 svr_responses[svr_id] = [];
1373
1374             if (!svr_responses[svr_id][qst_id]) {
1375                 svr_responses[svr_id][qst_id] = response;
1376
1377             } else {
1378                 // We have multiple responses for the same question.
1379                 // For this UI we only care about the most recent response.
1380                 if (response.effective_date() > 
1381                     svr_responses[svr_id][qst_id].effective_date())
1382                     svr_responses[svr_id][qst_id] = response;
1383             }
1384         }
1385     );
1386 }])
1387
1388 .controller('PatronFetchLastCtrl',
1389        ['$scope','$location','egCore',
1390 function($scope , $location , egCore) {
1391
1392     var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1393     if (ids.length) 
1394         return $location.path('/circ/patron/' + ids[0] + '/checkout');
1395
1396     $scope.no_last = true;
1397 }])
1398
1399 .controller('PatronTriggeredEventsCtrl',
1400        ['$scope','$routeParams','$location','egCore','patronSvc',
1401 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1402     $scope.initTab('other', $routeParams.id);
1403
1404     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1405     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1406
1407     $scope.triggered_events_url = url;
1408     $scope.funcs = {};
1409 }])
1410
1411 .controller('PatronMessageCenterCtrl',
1412        ['$scope','$routeParams','$location','egCore','patronSvc',
1413 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1414     $scope.initTab('other', $routeParams.id);
1415
1416     var url = $location.protocol() + '://' + $location.host()
1417         + egCore.env.basePath.replace(/\/staff.*/,  '/actor/user/message');
1418     url += '/' + encodeURIComponent($routeParams.id);
1419
1420     $scope.message_center_url = url;
1421     $scope.funcs = {};
1422 }])
1423
1424 .controller('PatronPermsCtrl',
1425        ['$scope','$routeParams','$window','$location','egCore',
1426 function($scope , $routeParams , $window , $location , egCore) {
1427     $scope.initTab('other', $routeParams.id);
1428
1429     var url = $location.absUrl().replace(
1430         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1431
1432     url += '?usr=' + encodeURIComponent($routeParams.id);
1433
1434     // user_edit does not load the session via cookie.  It uses URL 
1435     // params or xulG instead.  Pass via xulG.
1436     $scope.funcs = {
1437         ses : egCore.auth.token(),
1438         on_patron_save : function() {
1439             $scope.funcs.reload();
1440         }
1441     }
1442
1443     $scope.user_perms_url = url;
1444 }])
1445