]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
LP#1402797 browser client noncat counts in patron summary
[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', 
8     'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod'])
9
10 .config(function($routeProvider, $locationProvider, $compileProvider) {
11     $locationProvider.html5Mode(true);
12     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
13
14     // data loaded at startup which only requires an authtoken goes
15     // here. this allows the requests to be run in parallel instead of
16     // waiting until startup has completed.
17     var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
18
19         // fetch the org settings we care about during egStartup
20         // and toss them into egCore.env as egCore.env.aous[name] = value.
21         // note: only load settings here needed by all tabs; load tab-
22         // specific settings from within their respective controllers
23         egCore.env.classLoaders.aous = function() {
24             return egCore.org.settings([
25                 'circ.obscure_dob',
26                 'ui.circ.show_billing_tab_on_bills',
27                 'circ.patron_expires_soon_warning',
28                 'ui.circ.items_out.lost',
29                 'ui.circ.items_out.longoverdue',
30                 'ui.circ.items_out.claimsreturned'
31             ]).then(function(settings) { 
32                 // local settings are cached within egOrg.  Caching them
33                 // again in egEnv just simplifies the syntax for access.
34                 egCore.env.aous = settings;
35             });
36         }
37
38         egCore.env.loadClasses.push('aous');
39
40         // app-globally modify the default flesh fields for 
41         // fleshed user retrieval.
42         if (egUser.defaultFleshFields.indexOf('profile') == -1) {
43             egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
44                 'profile',
45                 'net_access_level',
46                 'ident_type',
47                 'ident_type2',
48                 'cards'
49             ]);
50         }
51
52         return egCore.startup.go().then(function() {
53
54             // This call requires orgs to be loaded, because it
55             // calls egCore.org.ancestors(), so call it after startup
56             return egCore.pcrud.search('actsc', 
57                 {owner : egCore.org.ancestors(
58                     egCore.auth.user().ws_ou(), true)},
59                 {}, {atomic : true}
60             ).then(function(cats) {
61                 egCore.env.absorbList(cats, 'actsc');
62             });
63         });
64     }]};
65
66     $routeProvider.when('/circ/patron/search', {
67         templateUrl: './circ/patron/t_search',
68         controller: 'PatronSearchCtrl',
69         resolve : resolver
70     });
71
72     $routeProvider.when('/circ/patron/bcsearch', {
73         templateUrl: './circ/patron/t_bcsearch',
74         controller: 'PatronBarcodeSearchCtrl',
75         resolve : resolver
76     });
77
78     $routeProvider.when('/circ/patron/credentials', {
79         templateUrl: './circ/patron/t_credentials',
80         controller: 'PatronVerifyCredentialsCtrl',
81         resolve : resolver
82     });
83
84     $routeProvider.when('/circ/patron/last', {
85         templateUrl: './circ/patron/t_last_patron',
86         controller: 'PatronFetchLastCtrl',
87         resolve : resolver
88     });
89
90     // the following require a patron ID
91
92     $routeProvider.when('/circ/patron/:id/alerts', {
93         templateUrl: './circ/patron/t_alerts',
94         controller: 'PatronAlertsCtrl',
95         resolve : resolver
96     });
97
98     $routeProvider.when('/circ/patron/:id/checkout', {
99         templateUrl: './circ/patron/t_checkout',
100         controller: 'PatronCheckoutCtrl',
101         resolve : resolver
102     });
103
104     $routeProvider.when('/circ/patron/:id/items_out', {
105         templateUrl: './circ/patron/t_items_out',
106         controller: 'PatronItemsOutCtrl',
107         resolve : resolver
108     });
109
110     $routeProvider.when('/circ/patron/:id/holds', {
111         templateUrl: './circ/patron/t_holds',
112         controller: 'PatronHoldsCtrl',
113         resolve : resolver
114     });
115
116     $routeProvider.when('/circ/patron/:id/holds/create', {
117         templateUrl: './circ/patron/t_holds_create',
118         controller: 'PatronHoldsCreateCtrl',
119         resolve : resolver
120     });
121
122     $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
123         templateUrl: './circ/patron/t_holds',
124         controller: 'PatronHoldsCtrl',
125         resolve : resolver
126     });
127
128     $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
129         templateUrl: './circ/patron/t_hold_details',
130         controller: 'PatronHoldDetailsCtrl',
131         resolve : resolver
132     });
133
134     $routeProvider.when('/circ/patron/:id/bills', {
135         templateUrl: './circ/patron/t_bills',
136         controller: 'PatronBillsCtrl',
137         resolve : resolver
138     });
139
140     $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
141         templateUrl: './circ/patron/t_xact_details',
142         controller: 'XactDetailsCtrl',
143         resolve : resolver
144     });
145
146     $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
147         templateUrl: './circ/patron/t_bill_history',
148         controller: 'BillHistoryCtrl',
149         resolve : resolver
150     });
151
152     $routeProvider.when('/circ/patron/:id/messages', {
153         templateUrl: './circ/patron/t_messages',
154         controller: 'PatronMessagesCtrl',
155         resolve : resolver
156     });
157
158     $routeProvider.when('/circ/patron/:id/edit', {
159         templateUrl: './circ/patron/t_edit',
160         controller: 'PatronEditCtrl',
161         resolve : resolver
162     });
163
164     $routeProvider.when('/circ/patron/:id/credentials', {
165         templateUrl: './circ/patron/t_credentials',
166         controller: 'PatronVerifyCredentialsCtrl',
167         resolve : resolver
168     });
169
170     $routeProvider.when('/circ/patron/:id/notes', {
171         templateUrl: './circ/patron/t_notes',
172         controller: 'PatronNotesCtrl',
173         resolve : resolver
174     });
175
176     $routeProvider.when('/circ/patron/:id/triggered_events', {
177         templateUrl: './circ/patron/t_triggered_events',
178         controller: 'PatronTriggeredEventsCtrl',
179         resolve : resolver
180     });
181
182     $routeProvider.when('/circ/patron/:id/edit_perms', {
183         templateUrl: './circ/patron/t_edit_perms',
184         controller: 'PatronPermsCtrl',
185         resolve : resolver
186     });
187
188     $routeProvider.when('/circ/patron/:id/group', {
189         templateUrl: './circ/patron/t_group',
190         controller: 'PatronGroupCtrl',
191         resolve : resolver
192     });
193
194     $routeProvider.when('/circ/patron/:id/stat_cats', {
195         templateUrl: './circ/patron/t_stat_cats',
196         controller: 'PatronStatCatsCtrl',
197         resolve : resolver
198     });
199
200     $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
201 })
202
203 /**
204  * Patron service
205  */
206 .factory('patronSvc',
207        ['$q','$timeout','$location','egCore','egUser','$locale',
208 function($q , $timeout , $location , egCore,  egUser , $locale) {
209
210     var service = {
211         // cached patron search results
212         patrons : [],
213
214         // currently selected patron object
215         current : null, 
216
217         // patron circ stats (overdues, fines, holds)
218         patron_stats : null,
219
220         // event types manually overridden, which should always be
221         // overridden for checkouts to this patron for this instance of
222         // the interface.
223         checkout_overrides : {},
224     };
225
226     // when we change the default patron, we need to clear out any
227     // data collected on that patron
228     service.resetPatronLists = function() {
229         service.checkouts = [];
230         service.items_out = []
231         service.items_out_ids = [];
232         service.holds = [];
233         service.hold_ids = [];
234         service.checkout_overrides = {};
235         service.patron_stats = null;
236         service.noncat_ids = [];
237         service.hasAlerts = false;
238         service.alertsShown = false;
239         service.patronExpired = false;
240         service.patronExpiresSoon = false;
241         service.retrievedWithInactive = false;
242         service.invalidAddresses = false;
243     }
244     service.resetPatronLists();  // initialize
245
246     // shortcut to force-reload the current primary
247     service.refreshPrimary = function() {
248         if (!service.current) return $q.when();
249         return service.setPrimary(service.current.id(), null, true);
250     }
251
252     // clear the currently focused user
253     service.clearPrimary = function() {
254         // reset with no patron
255         service.resetPatronLists();
256         service.current = null;
257         service.patron_stats = null;
258         return $q.when();
259     }
260
261     // sets the primary display user, fetching data as necessary.
262     service.setPrimary = function(id, user, force) {
263         var user_id = id ? id : (user ? user.id() : null);
264
265         console.debug('setting primary user to: ' + user_id);
266
267         if (!user_id) return $q.reject();
268
269         // when loading a new patron, update the last patron setting
270         if (!service.current || service.current.id() != user_id)
271             egCore.hatch.setLocalItem('eg.circ.last_patron', user_id);
272
273         // avoid running multiple retrievals for the same patron, which
274         // can happen during dbl-click by maintaining a single running
275         // data retrieval promise
276         if (service.primaryUserPromise) {
277             if (service.primaryUserId == user_id) {
278                 return service.primaryUserPromise.promise;
279             } else {
280                 service.primaryUserPromise = null;
281             }
282         }
283
284         service.primaryUserPromise = $q.defer();
285         service.primaryUserId = user_id;
286
287         service.getPrimary(id, user, force)
288         .then(function() {
289             var p = service.primaryUserPromise;
290             service.primaryUserId = null;
291             // clear before resolution just to be safe.
292             service.primaryUserPromise = null;
293             p.resolve();
294         });
295
296         return service.primaryUserPromise.promise;
297     }
298
299     service.getPrimary = function(id, user, force) {
300
301         if (user) {
302             if (!force && service.current && 
303                 service.current.id() == user.id()) {
304                 if (service.patron_stats) {
305                     return $q.when();
306                 } else {
307                     return service.fetchUserStats();
308                 }
309             }
310
311             service.resetPatronLists();
312             service.current = user;
313             service.localFlesh(user);
314             return service.fetchUserStats();
315
316         } else if (id) {
317             if (!force && service.current && service.current.id() == id) {
318                 if (service.patron_stats) {
319                     return $q.when();
320                 } else {
321                     return service.fetchUserStats();
322                 }
323             }
324
325             service.resetPatronLists();
326
327             return egUser.get(id).then(
328                 function(user) {
329                     service.current = user;
330                     service.localFlesh(user);
331                     return service.fetchUserStats();
332                 },
333                 function(err) {
334                     console.error(
335                         "unable to fetch user "+id+': '+js2JSON(err))
336                 }
337             );
338         } else {
339
340             // fetching a null user clears the primary user.
341             // NOTE: this should probably reject() and log an error, 
342             // but calling clear for backwards compat for now.
343             return service.clearPrimary();
344         }
345     }
346
347     // flesh some additional user fields locally
348     service.localFlesh = function(user) {
349         if (!angular.isObject(typeof user.home_ou()))
350             user.home_ou(egCore.org.get(user.home_ou()));
351
352         angular.forEach(
353             user.standing_penalties(),
354             function(penalty) {
355                 if (!angular.isObject(penalty.org_unit()))
356                     penalty.org_unit(egCore.org.get(penalty.org_unit()));
357             }
358         );
359
360         // stat_cat_entries == stat_cat_entry_user_map
361         angular.forEach(user.stat_cat_entries(), function(map) {
362             if (angular.isObject(map.stat_cat())) return;
363             // At page load, we only retrieve org-visible stat cats.
364             // For the common case, ignore entries for remote stat cats.
365             var cat = egCore.env.actsc.map[map.stat_cat()];
366             if (cat) {
367                 map.stat_cat(cat);
368                 cat.owner(egCore.org.get(cat.owner()));
369             }
370         });
371     }
372
373     // resolves to true if the patron account has expired or will
374     // expire soon, based on YAOUS circ.patron_expires_soon_warning
375     // note: returning a promise is no longer strictly necessary
376     // (no more async activity) if the calling function is changed too.
377     service.testExpire = function() {
378
379         var expire = Date.parse(service.current.expire_date());
380         if (expire < new Date()) {
381             return $q.when(service.patronExpired = true);
382         }
383
384         var soon = egCore.env.aous['circ.patron_expires_soon_warning'];
385         if (Number(soon)) {
386             var preExpire = new Date();
387             preExpire.setDate(preExpire.getDate() + Number(soon));
388             if (expire < preExpire) 
389                 return $q.when(service.patronExpiresSoon = true);
390         }
391
392         return $q.when(false);
393     }
394
395     // resolves to true if the patron account has any invalid addresses.
396     service.testInvalidAddrs = function() {
397
398         if (service.invalidAddresses)
399             return $q.when(true);
400
401         var fail = false;
402
403         angular.forEach(
404             service.current.addresses(), 
405             function(addr) { if (addr.valid() == 'f') fail = true }
406         );
407
408         return $q.when(fail);
409     }
410
411     // resolves to true if there is any aspect of the patron account
412     // which should produce a message in the alerts panel
413     service.checkAlerts = function() {
414
415         if (service.hasAlerts) // already checked
416             return $q.when(true); 
417
418         var deferred = $q.defer();
419         var p = service.current;
420
421         if (service.alert_penalties.length ||
422             p.alert_message() ||
423             p.active() == 'f' ||
424             p.barred() == 't' ||
425             service.patron_stats.holds.ready) {
426
427             service.hasAlerts = true;
428         }
429
430         // see if the user was retrieved with an inactive card
431         if (bc = $location.search().card) {
432             var card = p.cards().filter(
433                 function(c) { return c.barcode() == bc })[0];
434
435             if (card && card.active() == 'f') {
436                 service.hasAlerts = true;
437                 service.retrievedWithInactive = true;
438             }
439         }
440
441         // regardless of whether we know of alerts, we still need 
442         // to test/fetch the expire data for display
443         service.testExpire().then(function(bool) {
444             if (bool) service.hasAlerts = true;
445             deferred.resolve(service.hasAlerts);
446         });
447
448         service.testInvalidAddrs().then(function(bool) {
449             if (bool) service.invalidAddresses = true;
450             deferred.resolve(service.invalidAddresses);
451         });
452
453         return deferred.promise;
454     }
455
456     service.fetchGroupFines = function() {
457         return egCore.net.request(
458             'open-ils.actor',
459             'open-ils.actor.usergroup.members.balance_owed',
460             egCore.auth.token(), service.current.usrgroup()
461         ).then(function(list) {
462             var total = 0;
463             angular.forEach(list, function(u) { 
464                 total += 100 * Number(u.balance_owed)
465             });
466             service.patron_stats.fines.group_balance_owed = total / 100;
467         });
468     }
469
470     service.getUserStats = function(id) {
471         return egCore.net.request(
472             'open-ils.actor',
473             'open-ils.actor.user.opac.vital_stats.authoritative', 
474             egCore.auth.token(), id
475         ).then(
476             function(stats) {
477                 // force numeric to ensure correct boolean handling in templates
478                 stats.fines.balance_owed = Number(stats.fines.balance_owed);
479                 stats.checkouts.overdue = Number(stats.checkouts.overdue);
480                 stats.checkouts.claims_returned = 
481                     Number(stats.checkouts.claims_returned);
482                 stats.checkouts.lost = Number(stats.checkouts.lost);
483                 stats.checkouts.out = Number(stats.checkouts.out);
484                 stats.checkouts.total_out = 
485                     stats.checkouts.out + stats.checkouts.overdue;
486                 return stats;
487             }
488         );
489     }
490
491     // Fetches the IDs of any active non-cat checkouts for the current
492     // user.  Also sets the patron_stats non_cat count value to match.
493     service.getUserNonCats = function(id) {
494         return egCore.net.request(
495             'open-ils.circ',
496             'open-ils.circ.open_non_cataloged_circulation.user.authoritative',
497             egCore.auth.token(), id
498         ).then(function(noncat_ids) {
499             service.noncat_ids = noncat_ids;
500             service.patron_stats.checkouts.noncat = noncat_ids.length;
501         });
502     }
503
504     // grab additional circ info
505     service.fetchUserStats = function() {
506         return service.getUserStats(service.current.id())
507         .then(function(stats) {
508             service.patron_stats = stats
509             service.alert_penalties = service.current.standing_penalties()
510                 .filter(function(pen) { 
511                 return pen.standing_penalty().staff_alert() == 't' 
512             });
513
514             service.summary_stat_cats = [];
515             angular.forEach(service.current.stat_cat_entries(), 
516                 function(map) {
517                     if (angular.isObject(map.stat_cat()) &&
518                         map.stat_cat().usr_summary() == 't') {
519                         service.summary_stat_cats.push(map);
520                     }
521                 }
522             );
523
524             // run these two in parallel
525             var p1 = service.getUserNonCats(service.current.id());
526             var p2 = service.fetchGroupFines();
527             return $q.all([p1, p2]);
528         });
529     }
530
531     // Avoid using parens [e.g. (1.23)] to indicate negative numbers, 
532     // which is the Angular default.
533     // http://stackoverflow.com/questions/17441254/why-angularjs-currency-filter-formats-negative-numbers-with-parenthesis
534     // FIXME: This change needs to be moved into a project-wide collection
535     // of locale overrides.
536     $locale.NUMBER_FORMATS.PATTERNS[1].negPre = '-';
537     $locale.NUMBER_FORMATS.PATTERNS[1].negSuf = '';
538
539     return service;
540 }])
541
542 /**
543  * Manages tabbed patron view.
544  * This is the parent scope of all patron tab scopes.
545  *
546  * */
547 .controller('PatronCtrl',
548        ['$scope','$q','$location','$filter','egCore','egUser','patronSvc',
549 function($scope,  $q,  $location , $filter,  egCore,  egUser,  patronSvc) {
550
551     // returns true if a redirect occurs
552     function redirectToAlertPanel() {
553
554         $scope.alert_penalties = 
555             function() {return patronSvc.alert_penalties}
556
557         if (patronSvc.alertsShown) return false;
558         patronSvc.alertsShown = true;
559
560         // if the patron has any unshown alerts, show them now
561         if (patronSvc.hasAlerts && 
562             !$location.path().match(/alerts$/)) {
563
564             $location
565                 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
566                 .search('card', null);
567             return true;
568         }
569
570         // no alert required.  If the patron has fines and the show-bills
571         // OUS is applied, direct to the bills page.
572         if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
573             && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
574             && !$location.path().match(/bills$/)) {
575
576             $location
577                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
578                 .search('card', null);
579
580             return true;
581         }
582
583         return false;
584     }
585
586     // called after each route-specified controller is instantiated.
587     // this doubles as a way to inform the top-level controller that
588     // egStartup.go() has completed, which means we are clear to 
589     // fetch the patron, etc.
590     $scope.initTab = function(tab, patron_id) {
591         console.log('init tab ' + tab);
592         $scope.tab = tab;
593         $scope.aous = egCore.env.aous;
594
595         if (patron_id) {
596             $scope.patron_id = patron_id;
597             return patronSvc.setPrimary($scope.patron_id)
598             .then(function() {return patronSvc.checkAlerts()})
599             .then(redirectToAlertPanel);
600         }
601         return $q.when();
602     }
603
604     $scope.patron = function() { return patronSvc.current }
605     $scope.patron_stats = function() { return patronSvc.patron_stats }
606     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
607
608     $scope.print_address = function(addr) {
609         egCore.print.print({
610             context : 'default', 
611             template : 'patron_address', 
612             scope : {
613                 patron : egCore.idl.toHash(patronSvc.current),
614                 address : egCore.idl.toHash(addr)
615             }
616         });
617     }
618
619     $scope.toggle_expand_summary = function() {
620         if ($scope.collapsePatronSummary) {
621             $scope.collapsePatronSummary = false;
622             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
623         } else {
624             $scope.collapsePatronSummary = true;
625             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
626         }
627     }
628     
629     // always expand the patron summary in the search UI, regardless
630     // of stored preference.
631     $scope.collapse_summary = function() {
632         return $scope.tab != 'search' && $scope.collapsePatronSummary;
633     }
634
635     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
636     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
637 }])
638
639 .controller('PatronBarcodeSearchCtrl',
640        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
641 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
642     $scope.selectMe = true; // focus text input
643     patronSvc.clearPrimary(); // clear the default user
644
645     // jump to the patron checkout UI
646     function loadPatron(user_id) {
647         $location
648         .path('/circ/patron/' + user_id + '/checkout')
649         .search('card', $scope.args.barcode);
650     }
651
652     // create an opt-in=yes response for the loaded user
653     function createOptIn(user_id) {
654         egCore.net.request(
655             'open-ils.actor',
656             'open-ils.actor.user.org_unit_opt_in.create',
657             egCore.auth.token(), user_id).then(function(resp) {
658                 if (evt = egCore.evt.parse(resp)) return alert(evt);
659                 loadPatron(user_id);
660             }
661         );
662     }
663
664     $scope.submitBarcode = function(args) {
665         $scope.bcNotFound = null;
666         if (!args.barcode) return;
667
668         // blur so next time it's set to true it will re-apply select()
669         $scope.selectMe = false;
670
671         var user_id;
672
673         // lookup barcode
674         egCore.net.request(
675             'open-ils.actor',
676             'open-ils.actor.get_barcodes',
677             egCore.auth.token(), egCore.auth.user().ws_ou(), 
678             'actor', args.barcode)
679
680         .then(function(resp) { // get_barcodes
681
682             if (evt = egCore.evt.parse(resp)) {
683                 alert(evt); // FIXME
684                 return;
685             }
686
687             if (!resp || !resp[0]) {
688                 $scope.bcNotFound = args.barcode;
689                 $scope.selectMe = true;
690                 return;
691             }
692
693             // see if an opt-in request is needed
694             user_id = resp[0].id;
695             return egCore.net.request(
696                 'open-ils.actor',
697                 'open-ils.actor.user.org_unit_opt_in.check',
698                 egCore.auth.token(), user_id);
699
700         }).then(function(optInResp) { // opt_in_check
701
702             if (evt = egCore.evt.parse(optInResp)) {
703                 alert(evt); // FIXME
704                 return;
705             }
706            
707             if (optInResp == 1) {
708                 // opt-in handled or not needed
709                 return loadPatron(user_id);
710             }
711
712             // opt-in needed, show the opt-in dialog
713             egUser.get(user_id, {useFields : []})
714
715             .then(function(user) { // retrieve user
716                 egConfirmDialog.open(
717                     egCore.strings.OPT_IN_DIALOG, '',
718                     {   org : egCore.org.get(user.home_ou()),
719                         user : user,
720                         ok : function() { createOptIn(user.id()) },
721                         cancel : function() {}
722                     }
723                 );
724             })
725         });
726     }
727 }])
728
729
730 /**
731  * Manages patron search
732  */
733 .controller('PatronSearchCtrl',
734        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
735        '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
736 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore,
737         $filter,  egUser,  patronSvc , egGridDataProvider , $document) {
738
739     $scope.initTab('search');
740     $scope.focusMe = true;
741     $scope.searchArgs = {
742         // default to searching globally
743         home_ou : egCore.org.tree()
744     };
745
746     // last used patron search form element
747     var lastFormElement;
748
749     $scope.gridControls = {
750         activateItem : function(item) {
751             $location.path('/circ/patron/' + item.id() + '/checkout');
752         },
753         selectedItems : function() {return []}
754     }
755
756     // Handle URL-encoded searches
757     if ($location.search().search) {
758         patronSvc.urlSearch = {search : JSON2js($location.search().search)};
759
760         // why the double-JSON encoded sort?
761         patronSvc.urlSearch.sort = 
762             JSON2js(patronSvc.urlSearch.search.search_sort);
763         delete patronSvc.urlSearch.search.search_sort;
764     }
765
766     var propagate;
767     if (patronSvc.lastSearch) {
768         propagate = patronSvc.lastSearch.search;
769     } else if (patronSvc.urlSearch) {
770         propagate = patronSvc.urlSearch.search;
771     }
772
773     if (propagate) {
774         // populate the search form with our cached / preexisting search info
775         angular.forEach(propagate, function(val, key) {
776             $scope.searchArgs[key] = val.value;
777         });
778     }
779
780     var provider = egGridDataProvider.instance({});
781
782     $scope.$watch(
783         function() {return $scope.gridControls.selectedItems()},
784         function(list) {
785             if (list[0]) 
786                 patronSvc.setPrimary(null, list[0]);
787         },
788         true
789     );
790         
791     provider.get = function(offset, count) {
792         var deferred = $q.defer();
793
794         var fullSearch;
795         if (patronSvc.urlSearch) {
796             fullSearch = patronSvc.urlSearch;
797             // enusre the urlSearch only runs once.
798             delete patronSvc.urlSearch;
799
800         } else {
801
802             var search = compileSearch($scope.searchArgs);
803             if (Object.keys(search) == 0) return $q.when();
804
805             var home_ou = search.home_ou;
806             delete search.home_ou;
807             var inactive = search.inactive;
808             delete search.inactive;
809
810             fullSearch = {
811                 search : search,
812                 sort : compileSort(),
813                 inactive : inactive,
814                 home_ou : home_ou,
815             };
816         }
817
818         fullSearch.count = count;
819         fullSearch.offset = offset;
820
821         if (patronSvc.lastSearch) {
822             // search repeated, return the cached results
823             if (angular.equals(fullSearch, patronSvc.lastSearch)) {
824                 console.log('patron search returning ' + 
825                     patronSvc.patrons.length + ' cached results');
826                 
827                 // notify has to happen after returning the promise
828                 $timeout(
829                     function() {
830                         angular.forEach(patronSvc.patrons, function(user) {
831                             deferred.notify(user);
832                         });
833                         deferred.resolve();
834                     }
835                 );
836                 return deferred.promise;
837             }
838         }
839
840         patronSvc.lastSearch = fullSearch;
841
842         if (fullSearch.search.id) {
843             // search by user id performs a direct ID lookup
844             var userId = fullSearch.search.id.value;
845             $timeout(
846                 function() {
847                     egUser.get(userId).then(function(user) {
848                         patronSvc.localFlesh(user);
849                         patronSvc.patrons = [user];
850                         deferred.notify(user);
851                         deferred.resolve();
852                     });
853                 }
854             );
855             return deferred.promise;
856         }
857
858         patronSvc.patrons = [];
859         egCore.net.request(
860             'open-ils.actor',
861             'open-ils.actor.patron.search.advanced.fleshed',
862             egCore.auth.token(), 
863             fullSearch.search, 
864             fullSearch.count,
865             fullSearch.sort,
866             fullSearch.inactive,
867             fullSearch.home_ou,
868             egUser.defaultFleshFields,
869             fullSearch.offset
870
871         ).then(
872             function() { deferred.resolve() },
873             null, // onerror
874             function(user) {
875                 patronSvc.localFlesh(user); // inline
876                 patronSvc.patrons.push(user);
877                 deferred.notify(user);
878             }
879         );
880
881         return deferred.promise;
882     };
883
884     $scope.patronSearchGridProvider = provider;
885
886     if (egCore.env.pgt) {
887         $scope.profiles = egCore.env.pgt.list;
888     } else {
889         egCore.pcrud.search('pgt', {parent : null}, 
890             {flesh : -1, flesh_fields : {pgt : ['children']}}
891         ).then(
892             function(tree) {
893                 egCore.env.absorbTree(tree, 'pgt')
894                 $scope.profiles = egCore.env.pgt.list;
895             }
896         );
897     }
898
899     // determine the tree depth of the profile group
900     $scope.pgt_depth = function(grp) {
901         var d = 0;
902         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
903         return d;
904     }
905
906     $scope.clearForm = function () {
907         $scope.searchArgs={};
908         if (lastFormElement) lastFormElement.focus();
909     }
910
911     $scope.applyShowExtras = function($event, bool) {
912         if (bool) {
913             $scope.showExtras = true;
914             egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
915         } else {
916             $scope.showExtras = false;
917             egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
918         }
919         if (lastFormElement) lastFormElement.focus();
920         $event.preventDefault();
921     }
922
923     egCore.hatch.getItem('eg.prefs.circ.patron.search.showExtras')
924     .then(function(val) {$scope.showExtras = val});
925
926     // map form arguments into search params
927     function compileSearch(args) {
928         var search = {};
929         angular.forEach(args, function(val, key) {
930             if (!val) return;
931             if (key == 'profile' && args.profile) {
932                 search.profile = {value : args.profile.id(), group : 0};
933             } else if (key == 'home_ou' && args.home_ou) {
934                 search.home_ou = args.home_ou.id(); // passed separately
935             } else if (key == 'inactive') {
936                 search.inactive = val;
937             } else {
938                 search[key] = {value : val, group : 0};
939             }
940             if (key.match(/phone|ident/)) {
941                 search[key].group = 2;
942             } else {
943                 if (key.match(/street|city|state|post_code/)) {
944                     search[key].group = 1;
945                 } else if (key == 'card') {
946                     search[key].group = 3
947                 }
948             }
949         });
950
951         return search;
952     }
953
954     function compileSort() {
955
956         if (!provider.sort.length) {
957             return [ // default
958                 "family_name ASC",
959                 "first_given_name ASC",
960                 "second_given_name ASC",
961                 "dob DESC"
962             ];
963         }
964
965         var sort = [];
966         angular.forEach(
967             provider.sort,
968             function(sortdef) {
969                 if (angular.isObject(sortdef)) {
970                     var name = Object.keys(sortdef)[0];
971                     var dir = sortdef[name];
972                     sort.push(name + ' ' + dir);
973                 } else {
974                     sort.push(sortdef);
975                 }
976             }
977         );
978
979         return sort;
980     }
981
982     $scope.setLastFormElement = function() {
983         lastFormElement = $document[0].activeElement;
984     }
985
986     // search form submit action; tells the results grid to
987     // refresh itself.
988     $scope.search = function(args) { // args === $scope.searchArgs
989         if (args && Object.keys(args).length) 
990             $scope.gridControls.refresh();
991         if (lastFormElement) lastFormElement.focus();
992     }
993
994     // TODO: move this into the (forthcoming) grid row activate action
995     $scope.onPatronDblClick = function($event, user) {
996         $location.path('/circ/patron/' + user.id() + '/checkout');
997     }
998
999     if (patronSvc.urlSearch) {
1000         // force the grid to load the url-based search on page load
1001         provider.refresh();
1002     }
1003    
1004 }])
1005
1006 /**
1007  * Manages messages
1008  */
1009 .controller('PatronMessagesCtrl',
1010        ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
1011 function($scope , $q , $routeParams,  egCore , $modal , patronSvc , egCirc) {
1012     $scope.initTab('messages', $routeParams.id);
1013     var usr_id = $routeParams.id;
1014
1015     // setup date filters
1016     var start = new Date(); // now - 1 year
1017     start.setFullYear(start.getFullYear() - 1),
1018     $scope.dates = {
1019         start_date : start,
1020         end_date : new Date()
1021     }
1022
1023     function date_range() {
1024         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1025         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1026         var today = new Date().toISOString().replace(/T.*/,'');
1027         if (end == today) end = 'now';
1028         return [start, end];
1029     }
1030
1031     // grid queries
1032    
1033     var activeGrid = $scope.activeGridControls = {
1034         setSort : function() {
1035             return ['set_date'];
1036         },
1037         setQuery : function() {
1038             return {
1039                 usr : usr_id,
1040                 '-or' : [
1041                     {stop_date : null},
1042                     {stop_date : {'>' : 'now'}}
1043                 ]
1044             }
1045         }
1046     }
1047
1048     var archiveGrid = $scope.archiveGridControls = {
1049         setSort : function() {
1050             return ['set_date'];
1051         },
1052         setQuery : function() {
1053             return {
1054                 usr : usr_id, 
1055                 stop_date : {'<=' : 'now'},
1056                 set_date : {between : date_range()}
1057             };
1058         }
1059     };
1060
1061     $scope.removePenalty = function(selected) {
1062         // the grid stores flattened penalties.  Fetch penalty objects first
1063
1064         var ids = selected.map(function(s){ return s.id });
1065         egCore.pcrud.search('ausp', 
1066             {id : ids}, {}, 
1067             {atomic : true, authoritative : true}
1068
1069         // then delete them
1070         ).then(function(penalties) {
1071             return egCore.pcrud.remove(penalties);
1072
1073         // then refresh the grid
1074         }).then(function() {
1075             activeGrid.refresh();
1076         });
1077     }
1078
1079     $scope.archivePenalty = function(selected) {
1080         // the grid stores flattened penalties.  Fetch penalty objects first
1081
1082         var ids = selected.map(function(s){ return s.id });
1083         egCore.pcrud.search('ausp', 
1084             {id : ids}, {}, 
1085             {atomic : true, authoritative : true}
1086
1087         // then delete them
1088         ).then(function(penalties) {
1089             angular.forEach(penalties, function(p){ p.stop_date('now') });
1090             return egCore.pcrud.update(penalties);
1091
1092         // then refresh the grid
1093         }).then(function() {
1094             activeGrid.refresh();
1095             archiveGrid.refresh();
1096         });
1097     }
1098
1099     // leverage egEnv for caching
1100     function fetchPenaltyTypes() {
1101         if (egCore.env.csp) 
1102             return $q.when(egCore.env.csp.list);
1103         return egCore.pcrud.search(
1104             // id <= 100 are reserved for system use
1105             'csp', {id : {'>': 100}}, {}, {atomic : true})
1106         .then(function(penalties) {
1107             egCore.env.absorbList(penalties, 'csp');
1108             return penalties;
1109         });
1110     }
1111
1112     $scope.createPenalty = function() {
1113         egCirc.create_penalty(usr_id).then(function() {
1114             activeGrid.refresh();
1115             // force a refresh of the user, since they may now
1116             // have blocking penalties, etc.
1117             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1118         });
1119     }
1120
1121     $scope.editPenalty = function(selected) {
1122         if (selected.length == 0) return;
1123
1124         // grab the penalty from the user object
1125         var penalty = patronSvc.current.standing_penalties().filter(
1126             function(p) {return p.id() == selected[0].id})[0];
1127
1128         egCirc.edit_penalty(penalty).then(function() {
1129             activeGrid.refresh();
1130             // force a refresh of the user, since they may now
1131             // have blocking penalties, etc.
1132             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1133         });
1134     }
1135 }])
1136
1137
1138 /**
1139  * Link to patron edit UI
1140  */
1141 .controller('PatronEditCtrl',
1142        ['$scope','$routeParams','$location','egCore','patronSvc',
1143 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1144     $scope.initTab('edit', $routeParams.id);
1145
1146     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/register');
1147     url += '?usr=' + encodeURIComponent($routeParams.id);
1148
1149     $scope.funcs = {
1150         on_save : function() {
1151             patronSvc.refreshPrimary();
1152         }
1153     }
1154
1155     $scope.patron_edit_url = url;
1156 }])
1157
1158 /**
1159  * Credentials tester
1160  */
1161 .controller('PatronVerifyCredentialsCtrl',
1162        ['$scope','$routeParams','$location','egCore',
1163 function($scope,  $routeParams , $location , egCore) {
1164     $scope.verified = null;
1165     $scope.focusMe = true;
1166
1167     // called with a patron, pre-populate the form args
1168     $scope.initTab('other', $routeParams.id).then(
1169         function() {
1170             if ($scope.patron()) {
1171                 $scope.prepop = true;
1172                 $scope.username = $scope.patron().usrname();
1173                 $scope.barcode = $scope.patron().card().barcode();
1174             }
1175         }
1176     );
1177
1178     // verify login credentials
1179     $scope.verify = function() {
1180         $scope.verified = null;
1181         $scope.notFound = false;
1182
1183         egCore.net.request(
1184             'open-ils.actor',
1185             'open-ils.actor.verify_user_password',
1186             egCore.auth.token(), $scope.barcode,
1187             $scope.username, hex_md5($scope.password || '')
1188
1189         ).then(function(resp) {
1190             $scope.focusMe = true;
1191             if (evt = egCore.evt.parse(resp)) {
1192                 alert(evt);
1193             } else if (resp == 1) {
1194                 $scope.verified = true;
1195             } else {
1196                 $scope.verified = false;
1197             }
1198         });
1199     }
1200
1201     // load the main patron UI for the provided username or barcode
1202     $scope.load = function($event) {
1203         $scope.notFound = false;
1204         $scope.verified = null;
1205
1206         egCore.net.request(
1207             'open-ils.actor',
1208             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1209             egCore.auth.token(), $scope.barcode, $scope.username
1210
1211         ).then(function(resp) {
1212
1213             if (Number(resp)) {
1214                 $location.path('/circ/patron/' + resp + '/checkout');
1215                 return;
1216             }
1217
1218             // something went wrong...
1219             $scope.focusMe = true;
1220             if (evt = egCore.evt.parse(resp)) {
1221                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1222                     $scope.notFound = true;
1223                     return;
1224                 }
1225                 return alert(evt);
1226             } else {
1227                 alert(resp);
1228             }
1229         });
1230
1231         // load() button sits within the verify form.  
1232         // avoid submitting the verify() form action on load()
1233         $event.preventDefault();
1234     }
1235 }])
1236
1237 .controller('PatronAlertsCtrl',
1238        ['$scope','$routeParams','$location','egCore','patronSvc',
1239 function($scope,  $routeParams , $location , egCore , patronSvc) {
1240
1241     $scope.initTab('other', $routeParams.id)
1242     .then(function() {
1243         $scope.patronExpired = patronSvc.patronExpired;
1244         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1245         $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1246         $scope.invalidAddresses = patronSvc.invalidAddresses;
1247     });
1248
1249 }])
1250
1251 .controller('PatronNotesCtrl',
1252        ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1253 function($scope,  $routeParams , $location , egCore , patronSvc , $modal) {
1254     $scope.initTab('other', $routeParams.id);
1255     var usr_id = $routeParams.id;
1256
1257     // fetch the notes
1258     function refreshPage() {
1259         $scope.notes = [];
1260         egCore.pcrud.search('aun', 
1261             {usr : usr_id}, 
1262             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
1263             {authoritative : true})
1264         .then(null, null, function(note) {
1265             $scope.notes.push(note);
1266         });
1267     }
1268
1269     // open the new-note dialog and create the note
1270     $scope.newNote = function() {
1271         $modal.open({
1272             templateUrl: './circ/patron/t_new_note_dialog',
1273             controller: 
1274                 ['$scope', '$modalInstance',
1275             function($scope, $modalInstance) {
1276                 $scope.focusNote = true;
1277                 $scope.args = {};
1278                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1279                 $scope.cancel = function () { $modalInstance.dismiss() }
1280             }],
1281         }).result.then(
1282             function(args) {
1283                 if (!args.value) return;
1284                 var note = new egCore.idl.aun();
1285                 note.usr(usr_id);
1286                 note.title(args.title);
1287                 note.value(args.value);
1288                 note.pub(args.pub ? 't' : 'f');
1289                 note.creator(egCore.auth.user().id());
1290                 egCore.pcrud.create(note).then(function() {refreshPage()});
1291             }
1292         );
1293     }
1294
1295     // delete the selected note
1296     $scope.deleteNote = function(note) {
1297         egCore.pcrud.remove(note).then(function() {refreshPage()});
1298     }
1299
1300     // print the selected note
1301     $scope.printNote = function(note) {
1302         var hash = egCore.idl.toHash(note);
1303         hash.usr = egCore.idl.toHash($scope.patron());
1304         egCore.print.print({
1305             context : 'default', 
1306             template : 'patron_note', 
1307             scope : {note : hash}
1308         });
1309     }
1310
1311     // perform the initial note fetch
1312     refreshPage();
1313 }])
1314
1315 .controller('PatronGroupCtrl',
1316        ['$scope','$routeParams','$q','$window','$location','egCore',
1317         'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1318 function($scope,  $routeParams , $q , $window , $location , egCore ,
1319          patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1320
1321     var usr_id = $routeParams.id;
1322
1323     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1324
1325     var grid = $scope.gridControls = {
1326         activateItem : function(item) {
1327             $location.path('/circ/patron/' + item.id + '/checkout');
1328         },
1329         itemRetrieved : function(item) {
1330
1331             if (item.id == patronSvc.current.id()) {
1332                 item.stats = patronSvc.patron_stats;
1333
1334             } else {
1335                 // flesh stats for other group members
1336                 patronSvc.getUserStats(item.id).then(function(stats) {
1337                     item.stats = stats;
1338                     $scope.totals.total_out += stats.checkouts.total_out; 
1339                     $scope.totals.overdue += stats.checkouts.overdue; 
1340                 });
1341             }
1342         },
1343         setSort : function() {
1344             return ['create_date'];
1345         }
1346     }
1347
1348     $scope.initTab('other', $routeParams.id)
1349     .then(function(redirect) {
1350         // if we are redirecting to the alerts page, avoid updating the
1351         // grid query.
1352         if (redirect) return;
1353         // let initTab() fetch the user first so we can know the usrgroup
1354
1355         grid.setQuery({
1356             usrgroup : patronSvc.current.usrgroup(),
1357             deleted : 'f'
1358         });
1359         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1360     });
1361
1362     $scope.removeFromGroup = function(selected) {
1363         var promises = [];
1364         angular.forEach(selected, function(user) {
1365             console.debug('removing user ' + user.id + ' from group');
1366
1367             promises.push(
1368                 egCore.net.request(
1369                     'open-ils.actor',
1370                     'open-ils.actor.usergroup.new',
1371                     egCore.auth.token(), user.id, true
1372                 )
1373             );
1374         });
1375
1376         $q.all(promises).then(function() {grid.refresh()});
1377     }
1378
1379     function addUserToGroup(user) {
1380         user.usrgroup(patronSvc.current.usrgroup());
1381         user.ischanged(true);
1382         egCore.net.request(
1383             'open-ils.actor',
1384             'open-ils.actor.patron.update',
1385             egCore.auth.token(), user
1386
1387         ).then(function() {grid.refresh()});
1388     }
1389
1390     // fetch each user ("selected" has flattened users)
1391     // update the usrgroup, then update the user object
1392     // After all updates are complete, refresh the grid.
1393     function moveUsersToGroup(target_user, selected) {
1394         var promises = [];
1395
1396         angular.forEach(selected, function(user) {
1397             promises.push(
1398                 egCore.pcrud.retrieve('au', user.id)
1399                 .then(function(u) {
1400                     u.usrgroup(target_user.usrgroup());
1401                     u.ischanged(true);
1402                     return egCore.net.request(
1403                         'open-ils.actor',
1404                         'open-ils.actor.patron.update',
1405                         egCore.auth.token(), u
1406                     );
1407                 })
1408             );
1409         });
1410
1411         $q.all(promises).then(function() {grid.refresh()});
1412     }
1413
1414     function showMoveToGroupConfirm(barcode, selected) {
1415
1416         // find the user
1417         egCore.pcrud.search('ac', {barcode : barcode})
1418
1419         // fetch the fleshed user
1420         .then(function(card) {
1421
1422             if (!card) return; // TODO: warn user
1423
1424             egCore.pcrud.retrieve('au', card.usr())
1425             .then(function(user) {
1426                 user.card(card);
1427                 $modal.open({
1428                     templateUrl: './circ/patron/t_move_to_group_dialog',
1429                     controller: [
1430                                 '$scope','$modalInstance',
1431                         function($scope , $modalInstance) {
1432                             $scope.user = user;
1433                             $scope.outbound = Boolean(selected);
1434                             $scope.ok = 
1435                                 function(count) { $modalInstance.close() }
1436                             $scope.cancel = 
1437                                 function () { $modalInstance.dismiss() }
1438                         }
1439                     ]
1440                 }).result.then(function() {
1441                     if (selected) {
1442                         moveUsersToGroup(user, selected);
1443                     } else {
1444                         addUserToGroup(user);
1445                     }
1446                 });
1447             });
1448         });
1449     }
1450
1451     // selected == move selected patrons to another patron's group
1452     // !selected == patron from a different group moves into our group
1453     function moveToGroup(selected) {
1454         egPromptDialog.open(
1455             egCore.strings.GROUP_ADD_USER, '',
1456             {ok : function(value) {
1457                 if (value) 
1458                     showMoveToGroupConfirm(value, selected);
1459             }}
1460         );
1461     }
1462
1463     $scope.moveToGroup = function() { moveToGroup() };
1464     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected) };
1465
1466     $scope.cloneUser = function(selected) {
1467         if (!selected.length) return;
1468         var url = $location.absUrl().replace(
1469             /\/patron\/.*/, 
1470             '/patron/register/clone/' + selected[0].id);
1471         $window.open(url, '_blank').focus();
1472     }
1473
1474     $scope.retrieveSelected = function(selected) {
1475         if (!selected.length) return;
1476         var url = $location.absUrl().replace(
1477             /\/patron\/.*/, 
1478             '/patron/' + selected[0].id + '/checkout');
1479         $window.open(url, '_blank').focus();
1480     }
1481
1482 }])
1483
1484 .controller('PatronStatCatsCtrl',
1485        ['$scope','$routeParams','$q','egCore','patronSvc',
1486 function($scope,  $routeParams , $q , egCore , patronSvc) {
1487     $scope.initTab('other', $routeParams.id)
1488     .then(function(redirect) {
1489         // Entries for org-visible stat cats are fleshed.  Any others
1490         // have to be fleshed within.
1491
1492         var to_flesh = {};
1493         angular.forEach(patronSvc.current.stat_cat_entries(), 
1494             function(entry) {
1495                 if (!angular.isObject(entry.stat_cat())) {
1496                     to_flesh[entry.stat_cat()] = entry;
1497                 }
1498             }
1499         );
1500
1501         if (!Object.keys(to_flesh).length) return;
1502
1503         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1504         .then(null, null, function(cat) { // stream
1505             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1506             to_flesh[cat.id()].stat_cat(cat);
1507         });
1508     });
1509 }])
1510
1511 .controller('PatronFetchLastCtrl',
1512        ['$scope','$location','egCore',
1513 function($scope , $location , egCore) {
1514
1515     var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1516     if (id) return $location.path('/circ/patron/' + id + '/checkout');
1517
1518     $scope.no_last = true;
1519 }])
1520
1521 .controller('PatronTriggeredEventsCtrl',
1522        ['$scope','$routeParams','$location','egCore','patronSvc',
1523 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1524     $scope.initTab('other', $routeParams.id);
1525
1526     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1527     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1528
1529     $scope.triggered_events_url = url;
1530     $scope.funcs = {};
1531 }])
1532
1533 .controller('PatronPermsCtrl',
1534        ['$scope','$routeParams','$window','$location','egCore',
1535 function($scope , $routeParams , $window , $location , egCore) {
1536     $scope.initTab('other', $routeParams.id);
1537
1538     var url = $location.absUrl().replace(
1539         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1540
1541     url += '?usr=' + encodeURIComponent($routeParams.id);
1542
1543     // user_edit does not load the session via cookie.  It uses URL 
1544     // params or xulG instead.  Pass via xulG.
1545     $scope.funcs = {
1546         ses : egCore.auth.token(),
1547         on_patron_save : function() {
1548             $scope.funcs.reload();
1549         }
1550     }
1551
1552     $scope.user_perms_url = url;
1553 }])
1554
1555 .directive('aDisabled', function() {
1556     return {
1557         compile: function(tElement, tAttrs, transclude) {
1558             //Disable ngClick
1559             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
1560
1561             //Toggle "disabled" to class when aDisabled becomes true
1562             return function (scope, iElement, iAttrs) {
1563                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
1564                     if (newValue !== undefined) {
1565                         iElement.toggleClass("disabled", newValue);
1566                     }
1567                 });
1568
1569                 //Disable href on click
1570                 iElement.on("click", function(e) {
1571                     if (scope.$eval(iAttrs["aDisabled"])) {
1572                         e.preventDefault();
1573                     }
1574                 });
1575             };
1576         }
1577     };
1578 })
1579