]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
14a9bb8a708ccb1dafe44e0e490286e3bd95aef5
[working/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             $scope.tab = 'bills';
577             $location
578                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
579                 .search('card', null);
580
581             return true;
582         }
583
584         return false;
585     }
586
587     // called after each route-specified controller is instantiated.
588     // this doubles as a way to inform the top-level controller that
589     // egStartup.go() has completed, which means we are clear to 
590     // fetch the patron, etc.
591     $scope.initTab = function(tab, patron_id) {
592         console.log('init tab ' + tab);
593         $scope.tab = tab;
594         $scope.aous = egCore.env.aous;
595
596         if (patron_id) {
597             $scope.patron_id = patron_id;
598             return patronSvc.setPrimary($scope.patron_id)
599             .then(function() {return patronSvc.checkAlerts()})
600             .then(redirectToAlertPanel);
601         }
602         return $q.when();
603     }
604
605     $scope.patron = function() { return patronSvc.current }
606     $scope.patron_stats = function() { return patronSvc.patron_stats }
607     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
608
609     $scope.print_address = function(addr) {
610         egCore.print.print({
611             context : 'default', 
612             template : 'patron_address', 
613             scope : {
614                 patron : egCore.idl.toHash(patronSvc.current),
615                 address : egCore.idl.toHash(addr)
616             }
617         });
618     }
619
620     $scope.toggle_expand_summary = function() {
621         if ($scope.collapsePatronSummary) {
622             $scope.collapsePatronSummary = false;
623             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
624         } else {
625             $scope.collapsePatronSummary = true;
626             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
627         }
628     }
629     
630     // always expand the patron summary in the search UI, regardless
631     // of stored preference.
632     $scope.collapse_summary = function() {
633         return $scope.tab != 'search' && $scope.collapsePatronSummary;
634     }
635
636     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
637     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
638 }])
639
640 .controller('PatronBarcodeSearchCtrl',
641        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
642 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
643     $scope.selectMe = true; // focus text input
644     patronSvc.clearPrimary(); // clear the default user
645
646     // jump to the patron checkout UI
647     function loadPatron(user_id) {
648         $location
649         .path('/circ/patron/' + user_id + '/checkout')
650         .search('card', $scope.args.barcode);
651     }
652
653     // create an opt-in=yes response for the loaded user
654     function createOptIn(user_id) {
655         egCore.net.request(
656             'open-ils.actor',
657             'open-ils.actor.user.org_unit_opt_in.create',
658             egCore.auth.token(), user_id).then(function(resp) {
659                 if (evt = egCore.evt.parse(resp)) return alert(evt);
660                 loadPatron(user_id);
661             }
662         );
663     }
664
665     $scope.submitBarcode = function(args) {
666         $scope.bcNotFound = null;
667         if (!args.barcode) return;
668
669         // blur so next time it's set to true it will re-apply select()
670         $scope.selectMe = false;
671
672         var user_id;
673
674         // lookup barcode
675         egCore.net.request(
676             'open-ils.actor',
677             'open-ils.actor.get_barcodes',
678             egCore.auth.token(), egCore.auth.user().ws_ou(), 
679             'actor', args.barcode)
680
681         .then(function(resp) { // get_barcodes
682
683             if (evt = egCore.evt.parse(resp)) {
684                 alert(evt); // FIXME
685                 return;
686             }
687
688             if (!resp || !resp[0]) {
689                 $scope.bcNotFound = args.barcode;
690                 $scope.selectMe = true;
691                 return;
692             }
693
694             // see if an opt-in request is needed
695             user_id = resp[0].id;
696             return egCore.net.request(
697                 'open-ils.actor',
698                 'open-ils.actor.user.org_unit_opt_in.check',
699                 egCore.auth.token(), user_id);
700
701         }).then(function(optInResp) { // opt_in_check
702
703             if (evt = egCore.evt.parse(optInResp)) {
704                 alert(evt); // FIXME
705                 return;
706             }
707            
708             if (optInResp == 1) {
709                 // opt-in handled or not needed
710                 return loadPatron(user_id);
711             }
712
713             // opt-in needed, show the opt-in dialog
714             egUser.get(user_id, {useFields : []})
715
716             .then(function(user) { // retrieve user
717                 egConfirmDialog.open(
718                     egCore.strings.OPT_IN_DIALOG, '',
719                     {   org : egCore.org.get(user.home_ou()),
720                         user : user,
721                         ok : function() { createOptIn(user.id()) },
722                         cancel : function() {}
723                     }
724                 );
725             })
726         });
727     }
728 }])
729
730
731 /**
732  * Manages patron search
733  */
734 .controller('PatronSearchCtrl',
735        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
736        '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
737 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore,
738         $filter,  egUser,  patronSvc , egGridDataProvider , $document) {
739
740     $scope.initTab('search');
741     $scope.focusMe = true;
742     $scope.searchArgs = {
743         // default to searching globally
744         home_ou : egCore.org.tree()
745     };
746
747     // last used patron search form element
748     var lastFormElement;
749
750     $scope.gridControls = {
751         activateItem : function(item) {
752             $location.path('/circ/patron/' + item.id() + '/checkout');
753         },
754         selectedItems : function() {return []}
755     }
756
757     // Handle URL-encoded searches
758     if ($location.search().search) {
759         patronSvc.urlSearch = {search : JSON2js($location.search().search)};
760
761         // why the double-JSON encoded sort?
762         patronSvc.urlSearch.sort = 
763             JSON2js(patronSvc.urlSearch.search.search_sort);
764         delete patronSvc.urlSearch.search.search_sort;
765     }
766
767     var propagate;
768     if (patronSvc.lastSearch) {
769         propagate = patronSvc.lastSearch.search;
770     } else if (patronSvc.urlSearch) {
771         propagate = patronSvc.urlSearch.search;
772     }
773
774     if (egCore.env.pgt) {
775         $scope.profiles = egCore.env.pgt.list;
776     } else {
777         egCore.pcrud.search('pgt', {parent : null}, 
778             {flesh : -1, flesh_fields : {pgt : ['children']}}
779         ).then(
780             function(tree) {
781                 egCore.env.absorbTree(tree, 'pgt')
782                 $scope.profiles = egCore.env.pgt.list;
783             }
784         );
785     }
786
787     if (propagate) {
788         // populate the search form with our cached / preexisting search info
789         angular.forEach(propagate, function(val, key) {
790             if (key == 'profile')
791                 val.value = $scope.profiles.filter(function(p) { p.id() == val.value })[0];
792             if (key == 'home_ou')
793                 val.value = egCore.org.get(val.value);
794             $scope.searchArgs[key] = val.value;
795         });
796     }
797
798     var provider = egGridDataProvider.instance({});
799
800     $scope.$watch(
801         function() {return $scope.gridControls.selectedItems()},
802         function(list) {
803             if (list[0]) 
804                 patronSvc.setPrimary(null, list[0]);
805         },
806         true
807     );
808         
809     provider.get = function(offset, count) {
810         var deferred = $q.defer();
811
812         var fullSearch;
813         if (patronSvc.urlSearch) {
814             fullSearch = patronSvc.urlSearch;
815             // enusre the urlSearch only runs once.
816             delete patronSvc.urlSearch;
817
818         } else {
819
820             var search = compileSearch($scope.searchArgs);
821             if (Object.keys(search) == 0) return $q.when();
822
823             var home_ou = search.home_ou;
824             delete search.home_ou;
825             var inactive = search.inactive;
826             delete search.inactive;
827
828             fullSearch = {
829                 search : search,
830                 sort : compileSort(),
831                 inactive : inactive,
832                 home_ou : home_ou,
833             };
834         }
835
836         fullSearch.count = count;
837         fullSearch.offset = offset;
838
839         if (patronSvc.lastSearch) {
840             // search repeated, return the cached results
841             if (angular.equals(fullSearch, patronSvc.lastSearch)) {
842                 console.log('patron search returning ' + 
843                     patronSvc.patrons.length + ' cached results');
844                 
845                 // notify has to happen after returning the promise
846                 $timeout(
847                     function() {
848                         angular.forEach(patronSvc.patrons, function(user) {
849                             deferred.notify(user);
850                         });
851                         deferred.resolve();
852                     }
853                 );
854                 return deferred.promise;
855             }
856         }
857
858         patronSvc.lastSearch = fullSearch;
859
860         if (fullSearch.search.id) {
861             // search by user id performs a direct ID lookup
862             var userId = fullSearch.search.id.value;
863             $timeout(
864                 function() {
865                     egUser.get(userId).then(function(user) {
866                         patronSvc.localFlesh(user);
867                         patronSvc.patrons = [user];
868                         deferred.notify(user);
869                         deferred.resolve();
870                     });
871                 }
872             );
873             return deferred.promise;
874         }
875
876         patronSvc.patrons = [];
877         egCore.net.request(
878             'open-ils.actor',
879             'open-ils.actor.patron.search.advanced.fleshed',
880             egCore.auth.token(), 
881             fullSearch.search, 
882             fullSearch.count,
883             fullSearch.sort,
884             fullSearch.inactive,
885             fullSearch.home_ou,
886             egUser.defaultFleshFields,
887             fullSearch.offset
888
889         ).then(
890             function() { deferred.resolve() },
891             null, // onerror
892             function(user) {
893                 patronSvc.localFlesh(user); // inline
894                 patronSvc.patrons.push(user);
895                 deferred.notify(user);
896             }
897         );
898
899         return deferred.promise;
900     };
901
902     $scope.patronSearchGridProvider = provider;
903
904     // determine the tree depth of the profile group
905     $scope.pgt_depth = function(grp) {
906         var d = 0;
907         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
908         return d;
909     }
910
911     $scope.clearForm = function () {
912         $scope.searchArgs={};
913         if (lastFormElement) lastFormElement.focus();
914     }
915
916     $scope.applyShowExtras = function($event, bool) {
917         if (bool) {
918             $scope.showExtras = true;
919             egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
920         } else {
921             $scope.showExtras = false;
922             egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
923         }
924         if (lastFormElement) lastFormElement.focus();
925         $event.preventDefault();
926     }
927
928     egCore.hatch.getItem('eg.circ.patron.search.show_extras')
929     .then(function(val) {$scope.showExtras = val});
930
931     // map form arguments into search params
932     function compileSearch(args) {
933         var search = {};
934         angular.forEach(args, function(val, key) {
935             if (!val) return;
936             if (key == 'profile' && args.profile) {
937                 search.profile = {value : args.profile.id(), group : 0};
938             } else if (key == 'home_ou' && args.home_ou) {
939                 search.home_ou = args.home_ou.id(); // passed separately
940             } else if (key == 'inactive') {
941                 search.inactive = val;
942             } else {
943                 search[key] = {value : val, group : 0};
944             }
945             if (key.match(/phone|ident/)) {
946                 search[key].group = 2;
947             } else {
948                 if (key.match(/street|city|state|post_code/)) {
949                     search[key].group = 1;
950                 } else if (key == 'card') {
951                     search[key].group = 3
952                 }
953             }
954         });
955
956         return search;
957     }
958
959     function compileSort() {
960
961         if (!provider.sort.length) {
962             return [ // default
963                 "family_name ASC",
964                 "first_given_name ASC",
965                 "second_given_name ASC",
966                 "dob DESC"
967             ];
968         }
969
970         var sort = [];
971         angular.forEach(
972             provider.sort,
973             function(sortdef) {
974                 if (angular.isObject(sortdef)) {
975                     var name = Object.keys(sortdef)[0];
976                     var dir = sortdef[name];
977                     sort.push(name + ' ' + dir);
978                 } else {
979                     sort.push(sortdef);
980                 }
981             }
982         );
983
984         return sort;
985     }
986
987     $scope.setLastFormElement = function() {
988         lastFormElement = $document[0].activeElement;
989     }
990
991     // search form submit action; tells the results grid to
992     // refresh itself.
993     $scope.search = function(args) { // args === $scope.searchArgs
994         if (args && Object.keys(args).length) 
995             $scope.gridControls.refresh();
996         if (lastFormElement) lastFormElement.focus();
997     }
998
999     // TODO: move this into the (forthcoming) grid row activate action
1000     $scope.onPatronDblClick = function($event, user) {
1001         $location.path('/circ/patron/' + user.id() + '/checkout');
1002     }
1003
1004     if (patronSvc.urlSearch) {
1005         // force the grid to load the url-based search on page load
1006         provider.refresh();
1007     }
1008    
1009 }])
1010
1011 /**
1012  * Manages messages
1013  */
1014 .controller('PatronMessagesCtrl',
1015        ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
1016 function($scope , $q , $routeParams,  egCore , $modal , patronSvc , egCirc) {
1017     $scope.initTab('messages', $routeParams.id);
1018     var usr_id = $routeParams.id;
1019
1020     // setup date filters
1021     var start = new Date(); // now - 1 year
1022     start.setFullYear(start.getFullYear() - 1),
1023     $scope.dates = {
1024         start_date : start,
1025         end_date : new Date()
1026     }
1027
1028     function date_range() {
1029         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1030         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1031         var today = new Date().toISOString().replace(/T.*/,'');
1032         if (end == today) end = 'now';
1033         return [start, end];
1034     }
1035
1036     // grid queries
1037    
1038     var activeGrid = $scope.activeGridControls = {
1039         setSort : function() {
1040             return ['set_date'];
1041         },
1042         setQuery : function() {
1043             return {
1044                 usr : usr_id,
1045                 '-or' : [
1046                     {stop_date : null},
1047                     {stop_date : {'>' : 'now'}}
1048                 ]
1049             }
1050         }
1051     }
1052
1053     var archiveGrid = $scope.archiveGridControls = {
1054         setSort : function() {
1055             return ['set_date'];
1056         },
1057         setQuery : function() {
1058             return {
1059                 usr : usr_id, 
1060                 stop_date : {'<=' : 'now'},
1061                 set_date : {between : date_range()}
1062             };
1063         }
1064     };
1065
1066     $scope.removePenalty = function(selected) {
1067         // the grid stores flattened penalties.  Fetch penalty objects first
1068
1069         var ids = selected.map(function(s){ return s.id });
1070         egCore.pcrud.search('ausp', 
1071             {id : ids}, {}, 
1072             {atomic : true, authoritative : true}
1073
1074         // then delete them
1075         ).then(function(penalties) {
1076             return egCore.pcrud.remove(penalties);
1077
1078         // then refresh the grid
1079         }).then(function() {
1080             activeGrid.refresh();
1081         });
1082     }
1083
1084     $scope.archivePenalty = function(selected) {
1085         // the grid stores flattened penalties.  Fetch penalty objects first
1086
1087         var ids = selected.map(function(s){ return s.id });
1088         egCore.pcrud.search('ausp', 
1089             {id : ids}, {}, 
1090             {atomic : true, authoritative : true}
1091
1092         // then delete them
1093         ).then(function(penalties) {
1094             angular.forEach(penalties, function(p){ p.stop_date('now') });
1095             return egCore.pcrud.update(penalties);
1096
1097         // then refresh the grid
1098         }).then(function() {
1099             activeGrid.refresh();
1100             archiveGrid.refresh();
1101         });
1102     }
1103
1104     // leverage egEnv for caching
1105     function fetchPenaltyTypes() {
1106         if (egCore.env.csp) 
1107             return $q.when(egCore.env.csp.list);
1108         return egCore.pcrud.search(
1109             // id <= 100 are reserved for system use
1110             'csp', {id : {'>': 100}}, {}, {atomic : true})
1111         .then(function(penalties) {
1112             egCore.env.absorbList(penalties, 'csp');
1113             return penalties;
1114         });
1115     }
1116
1117     $scope.createPenalty = function() {
1118         egCirc.create_penalty(usr_id).then(function() {
1119             activeGrid.refresh();
1120             // force a refresh of the user, since they may now
1121             // have blocking penalties, etc.
1122             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1123         });
1124     }
1125
1126     $scope.editPenalty = function(selected) {
1127         if (selected.length == 0) return;
1128
1129         // grab the penalty from the user object
1130         var penalty = patronSvc.current.standing_penalties().filter(
1131             function(p) {return p.id() == selected[0].id})[0];
1132
1133         egCirc.edit_penalty(penalty).then(function() {
1134             activeGrid.refresh();
1135             // force a refresh of the user, since they may now
1136             // have blocking penalties, etc.
1137             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1138         });
1139     }
1140 }])
1141
1142
1143 /**
1144  * Link to patron edit UI
1145  */
1146 .controller('PatronEditCtrl',
1147        ['$scope','$routeParams','$location','egCore','patronSvc',
1148 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1149     $scope.initTab('edit', $routeParams.id);
1150
1151     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/register');
1152     url += '?usr=' + encodeURIComponent($routeParams.id);
1153
1154     $scope.funcs = {
1155         on_save : function() {
1156             patronSvc.refreshPrimary();
1157         }
1158     }
1159
1160     $scope.patron_edit_url = url;
1161 }])
1162
1163 /**
1164  * Credentials tester
1165  */
1166 .controller('PatronVerifyCredentialsCtrl',
1167        ['$scope','$routeParams','$location','egCore',
1168 function($scope,  $routeParams , $location , egCore) {
1169     $scope.verified = null;
1170     $scope.focusMe = true;
1171
1172     // called with a patron, pre-populate the form args
1173     $scope.initTab('other', $routeParams.id).then(
1174         function() {
1175             if ($routeParams.id && $scope.patron()) {
1176                 $scope.prepop = true;
1177                 $scope.username = $scope.patron().usrname();
1178                 $scope.barcode = $scope.patron().card().barcode();
1179             } else {
1180                 $scope.username = '';
1181                 $scope.barcode = '';
1182                 $scope.password = '';
1183             }
1184         }
1185     );
1186
1187     // verify login credentials
1188     $scope.verify = function() {
1189         $scope.verified = null;
1190         $scope.notFound = false;
1191
1192         egCore.net.request(
1193             'open-ils.actor',
1194             'open-ils.actor.verify_user_password',
1195             egCore.auth.token(), $scope.barcode,
1196             $scope.username, hex_md5($scope.password || '')
1197
1198         ).then(function(resp) {
1199             $scope.focusMe = true;
1200             if (evt = egCore.evt.parse(resp)) {
1201                 alert(evt);
1202             } else if (resp == 1) {
1203                 $scope.verified = true;
1204             } else {
1205                 $scope.verified = false;
1206             }
1207         });
1208     }
1209
1210     // load the main patron UI for the provided username or barcode
1211     $scope.load = function($event) {
1212         $scope.notFound = false;
1213         $scope.verified = null;
1214
1215         egCore.net.request(
1216             'open-ils.actor',
1217             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1218             egCore.auth.token(), $scope.barcode, $scope.username
1219
1220         ).then(function(resp) {
1221
1222             if (Number(resp)) {
1223                 $location.path('/circ/patron/' + resp + '/checkout');
1224                 return;
1225             }
1226
1227             // something went wrong...
1228             $scope.focusMe = true;
1229             if (evt = egCore.evt.parse(resp)) {
1230                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1231                     $scope.notFound = true;
1232                     return;
1233                 }
1234                 return alert(evt);
1235             } else {
1236                 alert(resp);
1237             }
1238         });
1239
1240         // load() button sits within the verify form.  
1241         // avoid submitting the verify() form action on load()
1242         $event.preventDefault();
1243     }
1244 }])
1245
1246 .controller('PatronAlertsCtrl',
1247        ['$scope','$routeParams','$location','egCore','patronSvc',
1248 function($scope,  $routeParams , $location , egCore , patronSvc) {
1249
1250     $scope.initTab('other', $routeParams.id)
1251     .then(function() {
1252         $scope.patronExpired = patronSvc.patronExpired;
1253         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1254         $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1255         $scope.invalidAddresses = patronSvc.invalidAddresses;
1256     });
1257
1258 }])
1259
1260 .controller('PatronNotesCtrl',
1261        ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1262 function($scope,  $routeParams , $location , egCore , patronSvc , $modal) {
1263     $scope.initTab('other', $routeParams.id);
1264     var usr_id = $routeParams.id;
1265
1266     // fetch the notes
1267     function refreshPage() {
1268         $scope.notes = [];
1269         egCore.pcrud.search('aun', 
1270             {usr : usr_id}, 
1271             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
1272             {authoritative : true})
1273         .then(null, null, function(note) {
1274             $scope.notes.push(note);
1275         });
1276     }
1277
1278     // open the new-note dialog and create the note
1279     $scope.newNote = function() {
1280         $modal.open({
1281             templateUrl: './circ/patron/t_new_note_dialog',
1282             controller: 
1283                 ['$scope', '$modalInstance',
1284             function($scope, $modalInstance) {
1285                 $scope.focusNote = true;
1286                 $scope.args = {};
1287                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1288                 $scope.cancel = function () { $modalInstance.dismiss() }
1289             }],
1290         }).result.then(
1291             function(args) {
1292                 if (!args.value) return;
1293                 var note = new egCore.idl.aun();
1294                 note.usr(usr_id);
1295                 note.title(args.title);
1296                 note.value(args.value);
1297                 note.pub(args.pub ? 't' : 'f');
1298                 note.creator(egCore.auth.user().id());
1299                 egCore.pcrud.create(note).then(function() {refreshPage()});
1300             }
1301         );
1302     }
1303
1304     // delete the selected note
1305     $scope.deleteNote = function(note) {
1306         egCore.pcrud.remove(note).then(function() {refreshPage()});
1307     }
1308
1309     // print the selected note
1310     $scope.printNote = function(note) {
1311         var hash = egCore.idl.toHash(note);
1312         hash.usr = egCore.idl.toHash($scope.patron());
1313         egCore.print.print({
1314             context : 'default', 
1315             template : 'patron_note', 
1316             scope : {note : hash}
1317         });
1318     }
1319
1320     // perform the initial note fetch
1321     refreshPage();
1322 }])
1323
1324 .controller('PatronGroupCtrl',
1325        ['$scope','$routeParams','$q','$window','$location','egCore',
1326         'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1327 function($scope,  $routeParams , $q , $window , $location , egCore ,
1328          patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1329
1330     var usr_id = $routeParams.id;
1331
1332     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1333
1334     var grid = $scope.gridControls = {
1335         activateItem : function(item) {
1336             $location.path('/circ/patron/' + item.id + '/checkout');
1337         },
1338         itemRetrieved : function(item) {
1339
1340             if (item.id == patronSvc.current.id()) {
1341                 item.stats = patronSvc.patron_stats;
1342
1343             } else {
1344                 // flesh stats for other group members
1345                 patronSvc.getUserStats(item.id).then(function(stats) {
1346                     item.stats = stats;
1347                     $scope.totals.total_out += stats.checkouts.total_out; 
1348                     $scope.totals.overdue += stats.checkouts.overdue; 
1349                 });
1350             }
1351         },
1352         setSort : function() {
1353             return ['create_date'];
1354         }
1355     }
1356
1357     $scope.initTab('other', $routeParams.id)
1358     .then(function(redirect) {
1359         // if we are redirecting to the alerts page, avoid updating the
1360         // grid query.
1361         if (redirect) return;
1362         // let initTab() fetch the user first so we can know the usrgroup
1363
1364         grid.setQuery({
1365             usrgroup : patronSvc.current.usrgroup(),
1366             deleted : 'f'
1367         });
1368         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1369     });
1370
1371     $scope.removeFromGroup = function(selected) {
1372         var promises = [];
1373         angular.forEach(selected, function(user) {
1374             console.debug('removing user ' + user.id + ' from group');
1375
1376             promises.push(
1377                 egCore.net.request(
1378                     'open-ils.actor',
1379                     'open-ils.actor.usergroup.new',
1380                     egCore.auth.token(), user.id, true
1381                 )
1382             );
1383         });
1384
1385         $q.all(promises).then(function() {grid.refresh()});
1386     }
1387
1388     function addUserToGroup(user) {
1389         user.usrgroup(patronSvc.current.usrgroup());
1390         user.ischanged(true);
1391         egCore.net.request(
1392             'open-ils.actor',
1393             'open-ils.actor.patron.update',
1394             egCore.auth.token(), user
1395
1396         ).then(function() {grid.refresh()});
1397     }
1398
1399     // fetch each user ("selected" has flattened users)
1400     // update the usrgroup, then update the user object
1401     // After all updates are complete, refresh the grid.
1402     function moveUsersToGroup(target_user, selected) {
1403         var promises = [];
1404
1405         angular.forEach(selected, function(user) {
1406             promises.push(
1407                 egCore.pcrud.retrieve('au', user.id)
1408                 .then(function(u) {
1409                     u.usrgroup(target_user.usrgroup());
1410                     u.ischanged(true);
1411                     return egCore.net.request(
1412                         'open-ils.actor',
1413                         'open-ils.actor.patron.update',
1414                         egCore.auth.token(), u
1415                     );
1416                 })
1417             );
1418         });
1419
1420         $q.all(promises).then(function() {grid.refresh()});
1421     }
1422
1423     function showMoveToGroupConfirm(barcode, selected, outbound) {
1424
1425         // find the user
1426         egCore.pcrud.search('ac', {barcode : barcode})
1427
1428         // fetch the fleshed user
1429         .then(function(card) {
1430
1431             if (!card) return; // TODO: warn user
1432
1433             egCore.pcrud.retrieve('au', card.usr())
1434             .then(function(user) {
1435                 user.card(card);
1436                 $modal.open({
1437                     templateUrl: './circ/patron/t_move_to_group_dialog',
1438                     controller: [
1439                                 '$scope','$modalInstance',
1440                         function($scope , $modalInstance) {
1441                             $scope.user = user;
1442                             $scope.selected = selected;
1443                             $scope.outbound = outbound;
1444                             $scope.ok = 
1445                                 function(count) { $modalInstance.close() }
1446                             $scope.cancel = 
1447                                 function () { $modalInstance.dismiss() }
1448                         }
1449                     ]
1450                 }).result.then(function() {
1451                     if (outbound) {
1452                         moveUsersToGroup(user, selected);
1453                     } else {
1454                         addUserToGroup(user);
1455                     }
1456                 });
1457             });
1458         });
1459     }
1460
1461     // selected == move selected patrons to another patron's group
1462     // !selected == patron from a different group moves into our group
1463     function moveToGroup(selected, outbound) {
1464         egPromptDialog.open(
1465             egCore.strings.GROUP_ADD_USER, '',
1466             {ok : function(value) {
1467                 if (value) 
1468                     showMoveToGroupConfirm(value, selected, outbound);
1469             }}
1470         );
1471     }
1472
1473     $scope.moveToGroup = function() { moveToGroup([], false) };
1474     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1475
1476     $scope.cloneUser = function(selected) {
1477         if (!selected.length) return;
1478         var url = $location.absUrl().replace(
1479             /\/patron\/.*/, 
1480             '/patron/register/clone/' + selected[0].id);
1481         $window.open(url, '_blank').focus();
1482     }
1483
1484     $scope.retrieveSelected = function(selected) {
1485         if (!selected.length) return;
1486         var url = $location.absUrl().replace(
1487             /\/patron\/.*/, 
1488             '/patron/' + selected[0].id + '/checkout');
1489         $window.open(url, '_blank').focus();
1490     }
1491
1492 }])
1493
1494 .controller('PatronStatCatsCtrl',
1495        ['$scope','$routeParams','$q','egCore','patronSvc',
1496 function($scope,  $routeParams , $q , egCore , patronSvc) {
1497     $scope.initTab('other', $routeParams.id)
1498     .then(function(redirect) {
1499         // Entries for org-visible stat cats are fleshed.  Any others
1500         // have to be fleshed within.
1501
1502         var to_flesh = {};
1503         angular.forEach(patronSvc.current.stat_cat_entries(), 
1504             function(entry) {
1505                 if (!angular.isObject(entry.stat_cat())) {
1506                     to_flesh[entry.stat_cat()] = entry;
1507                 }
1508             }
1509         );
1510
1511         if (!Object.keys(to_flesh).length) return;
1512
1513         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1514         .then(null, null, function(cat) { // stream
1515             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1516             to_flesh[cat.id()].stat_cat(cat);
1517         });
1518     });
1519 }])
1520
1521 .controller('PatronFetchLastCtrl',
1522        ['$scope','$location','egCore',
1523 function($scope , $location , egCore) {
1524
1525     var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1526     if (id) return $location.path('/circ/patron/' + id + '/checkout');
1527
1528     $scope.no_last = true;
1529 }])
1530
1531 .controller('PatronTriggeredEventsCtrl',
1532        ['$scope','$routeParams','$location','egCore','patronSvc',
1533 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1534     $scope.initTab('other', $routeParams.id);
1535
1536     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1537     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1538
1539     $scope.triggered_events_url = url;
1540     $scope.funcs = {};
1541 }])
1542
1543 .controller('PatronPermsCtrl',
1544        ['$scope','$routeParams','$window','$location','egCore',
1545 function($scope , $routeParams , $window , $location , egCore) {
1546     $scope.initTab('other', $routeParams.id);
1547
1548     var url = $location.absUrl().replace(
1549         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1550
1551     url += '?usr=' + encodeURIComponent($routeParams.id);
1552
1553     // user_edit does not load the session via cookie.  It uses URL 
1554     // params or xulG instead.  Pass via xulG.
1555     $scope.funcs = {
1556         ses : egCore.auth.token(),
1557         on_patron_save : function() {
1558             $scope.funcs.reload();
1559         }
1560     }
1561
1562     $scope.user_perms_url = url;
1563 }])
1564
1565 .directive('aDisabled', function() {
1566     return {
1567         compile: function(tElement, tAttrs, transclude) {
1568             //Disable ngClick
1569             tAttrs["ngClick"] = ("ng-click", "!("+tAttrs["aDisabled"]+") && ("+tAttrs["ngClick"]+")");
1570
1571             //Toggle "disabled" to class when aDisabled becomes true
1572             return function (scope, iElement, iAttrs) {
1573                 scope.$watch(iAttrs["aDisabled"], function(newValue) {
1574                     if (newValue !== undefined) {
1575                         iElement.toggleClass("disabled", newValue);
1576                     }
1577                 });
1578
1579                 //Disable href on click
1580                 iElement.on("click", function(e) {
1581                     if (scope.$eval(iAttrs["aDisabled"])) {
1582                         e.preventDefault();
1583                     }
1584                 });
1585             };
1586         }
1587     };
1588 })
1589