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