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