]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
LP#1402797 Focus patron search field on search, expand, clear
[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     }
969
970     // TODO: move this into the (forthcoming) grid row activate action
971     $scope.onPatronDblClick = function($event, user) {
972         $location.path('/circ/patron/' + user.id() + '/checkout');
973     }
974
975     if (patronSvc.urlSearch) {
976         // force the grid to load the url-based search on page load
977         provider.refresh();
978     }
979    
980 }])
981
982 /**
983  * Manages messages
984  */
985 .controller('PatronMessagesCtrl',
986        ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
987 function($scope , $q , $routeParams,  egCore , $modal , patronSvc , egCirc) {
988     $scope.initTab('messages', $routeParams.id);
989     var usr_id = $routeParams.id;
990
991     // setup date filters
992     var start = new Date(); // now - 1 year
993     start.setFullYear(start.getFullYear() - 1),
994     $scope.dates = {
995         start_date : start,
996         end_date : new Date()
997     }
998
999     function date_range() {
1000         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1001         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1002         var today = new Date().toISOString().replace(/T.*/,'');
1003         if (end == today) end = 'now';
1004         return [start, end];
1005     }
1006
1007     // grid queries
1008    
1009     var activeGrid = $scope.activeGridControls = {
1010         setSort : function() {
1011             return ['set_date'];
1012         },
1013         setQuery : function() {
1014             return {
1015                 usr : usr_id,
1016                 '-or' : [
1017                     {stop_date : null},
1018                     {stop_date : {'>' : 'now'}}
1019                 ]
1020             }
1021         }
1022     }
1023
1024     var archiveGrid = $scope.archiveGridControls = {
1025         setSort : function() {
1026             return ['set_date'];
1027         },
1028         setQuery : function() {
1029             return {
1030                 usr : usr_id, 
1031                 stop_date : {'<=' : 'now'},
1032                 set_date : {between : date_range()}
1033             };
1034         }
1035     };
1036
1037     $scope.removePenalty = function(selected) {
1038         // the grid stores flattened penalties.  Fetch penalty objects first
1039
1040         var ids = selected.map(function(s){ return s.id });
1041         egCore.pcrud.search('ausp', 
1042             {id : ids}, {}, 
1043             {atomic : true, authoritative : true}
1044
1045         // then delete them
1046         ).then(function(penalties) {
1047             return egCore.pcrud.remove(penalties);
1048
1049         // then refresh the grid
1050         }).then(function() {
1051             activeGrid.refresh();
1052         });
1053     }
1054
1055     $scope.archivePenalty = function(selected) {
1056         // the grid stores flattened penalties.  Fetch penalty objects first
1057
1058         var ids = selected.map(function(s){ return s.id });
1059         egCore.pcrud.search('ausp', 
1060             {id : ids}, {}, 
1061             {atomic : true, authoritative : true}
1062
1063         // then delete them
1064         ).then(function(penalties) {
1065             angular.forEach(penalties, function(p){ p.stop_date('now') });
1066             return egCore.pcrud.update(penalties);
1067
1068         // then refresh the grid
1069         }).then(function() {
1070             activeGrid.refresh();
1071             archiveGrid.refresh();
1072         });
1073     }
1074
1075     // leverage egEnv for caching
1076     function fetchPenaltyTypes() {
1077         if (egCore.env.csp) 
1078             return $q.when(egCore.env.csp.list);
1079         return egCore.pcrud.search(
1080             // id <= 100 are reserved for system use
1081             'csp', {id : {'>': 100}}, {}, {atomic : true})
1082         .then(function(penalties) {
1083             egCore.env.absorbList(penalties, 'csp');
1084             return penalties;
1085         });
1086     }
1087
1088     $scope.createPenalty = function() {
1089         egCirc.create_penalty(usr_id).then(function() {
1090             activeGrid.refresh();
1091             // force a refresh of the user, since they may now
1092             // have blocking penalties, etc.
1093             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1094         });
1095     }
1096
1097     $scope.editPenalty = function(selected) {
1098         if (selected.length == 0) return;
1099
1100         // grab the penalty from the user object
1101         var penalty = patronSvc.current.standing_penalties().filter(
1102             function(p) {return p.id() == selected[0].id})[0];
1103
1104         egCirc.edit_penalty(penalty).then(function() {
1105             activeGrid.refresh();
1106             // force a refresh of the user, since they may now
1107             // have blocking penalties, etc.
1108             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1109         });
1110     }
1111 }])
1112
1113
1114 /**
1115  * Link to patron edit UI
1116  */
1117 .controller('PatronEditCtrl',
1118        ['$scope','$routeParams','$location','egCore','patronSvc',
1119 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1120     $scope.initTab('edit', $routeParams.id);
1121
1122     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/register');
1123     url += '?usr=' + encodeURIComponent($routeParams.id);
1124
1125     $scope.funcs = {
1126         on_save : function() {
1127             patronSvc.refreshPrimary();
1128         }
1129     }
1130
1131     $scope.patron_edit_url = url;
1132 }])
1133
1134 /**
1135  * Credentials tester
1136  */
1137 .controller('PatronVerifyCredentialsCtrl',
1138        ['$scope','$routeParams','$location','egCore',
1139 function($scope,  $routeParams , $location , egCore) {
1140     $scope.verified = null;
1141     $scope.focusMe = true;
1142
1143     // called with a patron, pre-populate the form args
1144     $scope.initTab('other', $routeParams.id).then(
1145         function() {
1146             if ($scope.patron()) {
1147                 $scope.prepop = true;
1148                 $scope.username = $scope.patron().usrname();
1149                 $scope.barcode = $scope.patron().card().barcode();
1150             }
1151         }
1152     );
1153
1154     // verify login credentials
1155     $scope.verify = function() {
1156         $scope.verified = null;
1157         $scope.notFound = false;
1158
1159         egCore.net.request(
1160             'open-ils.actor',
1161             'open-ils.actor.verify_user_password',
1162             egCore.auth.token(), $scope.barcode,
1163             $scope.username, hex_md5($scope.password || '')
1164
1165         ).then(function(resp) {
1166             $scope.focusMe = true;
1167             if (evt = egCore.evt.parse(resp)) {
1168                 alert(evt);
1169             } else if (resp == 1) {
1170                 $scope.verified = true;
1171             } else {
1172                 $scope.verified = false;
1173             }
1174         });
1175     }
1176
1177     // load the main patron UI for the provided username or barcode
1178     $scope.load = function($event) {
1179         $scope.notFound = false;
1180         $scope.verified = null;
1181
1182         egCore.net.request(
1183             'open-ils.actor',
1184             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1185             egCore.auth.token(), $scope.barcode, $scope.username
1186
1187         ).then(function(resp) {
1188
1189             if (Number(resp)) {
1190                 $location.path('/circ/patron/' + resp + '/checkout');
1191                 return;
1192             }
1193
1194             // something went wrong...
1195             $scope.focusMe = true;
1196             if (evt = egCore.evt.parse(resp)) {
1197                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1198                     $scope.notFound = true;
1199                     return;
1200                 }
1201                 return alert(evt);
1202             } else {
1203                 alert(resp);
1204             }
1205         });
1206
1207         // load() button sits within the verify form.  
1208         // avoid submitting the verify() form action on load()
1209         $event.preventDefault();
1210     }
1211 }])
1212
1213 .controller('PatronAlertsCtrl',
1214        ['$scope','$routeParams','$location','egCore','patronSvc',
1215 function($scope,  $routeParams , $location , egCore , patronSvc) {
1216
1217     $scope.initTab('other', $routeParams.id)
1218     .then(function() {
1219         $scope.patronExpired = patronSvc.patronExpired;
1220         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1221         $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1222         $scope.invalidAddresses = patronSvc.invalidAddresses;
1223     });
1224
1225 }])
1226
1227 .controller('PatronNotesCtrl',
1228        ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1229 function($scope,  $routeParams , $location , egCore , patronSvc , $modal) {
1230     $scope.initTab('other', $routeParams.id);
1231     var usr_id = $routeParams.id;
1232
1233     // fetch the notes
1234     function refreshPage() {
1235         $scope.notes = [];
1236         egCore.pcrud.search('aun', 
1237             {usr : usr_id}, 
1238             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
1239             {authoritative : true})
1240         .then(null, null, function(note) {
1241             $scope.notes.push(note);
1242         });
1243     }
1244
1245     // open the new-note dialog and create the note
1246     $scope.newNote = function() {
1247         $modal.open({
1248             templateUrl: './circ/patron/t_new_note_dialog',
1249             controller: 
1250                 ['$scope', '$modalInstance',
1251             function($scope, $modalInstance) {
1252                 $scope.focusNote = true;
1253                 $scope.args = {};
1254                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1255                 $scope.cancel = function () { $modalInstance.dismiss() }
1256             }],
1257         }).result.then(
1258             function(args) {
1259                 if (!args.value) return;
1260                 var note = new egCore.idl.aun();
1261                 note.usr(usr_id);
1262                 note.title(args.title);
1263                 note.value(args.value);
1264                 note.pub(args.pub ? 't' : 'f');
1265                 note.creator(egCore.auth.user().id());
1266                 egCore.pcrud.create(note).then(function() {refreshPage()});
1267             }
1268         );
1269     }
1270
1271     // delete the selected note
1272     $scope.deleteNote = function(note) {
1273         egCore.pcrud.remove(note).then(function() {refreshPage()});
1274     }
1275
1276     // print the selected note
1277     $scope.printNote = function(note) {
1278         var hash = egCore.idl.toHash(note);
1279         hash.usr = egCore.idl.toHash($scope.patron());
1280         egCore.print.print({
1281             context : 'default', 
1282             template : 'patron_note', 
1283             scope : {note : hash}
1284         });
1285     }
1286
1287     // perform the initial note fetch
1288     refreshPage();
1289 }])
1290
1291 .controller('PatronGroupCtrl',
1292        ['$scope','$routeParams','$q','$window','$location','egCore',
1293         'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1294 function($scope,  $routeParams , $q , $window , $location , egCore ,
1295          patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1296
1297     var usr_id = $routeParams.id;
1298
1299     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1300
1301     var grid = $scope.gridControls = {
1302         activateItem : function(item) {
1303             $location.path('/circ/patron/' + item.id + '/checkout');
1304         },
1305         itemRetrieved : function(item) {
1306
1307             if (item.id == patronSvc.current.id()) {
1308                 item.stats = patronSvc.patron_stats;
1309
1310             } else {
1311                 // flesh stats for other group members
1312                 patronSvc.getUserStats(item.id).then(function(stats) {
1313                     item.stats = stats;
1314                     $scope.totals.total_out += stats.checkouts.total_out; 
1315                     $scope.totals.overdue += stats.checkouts.overdue; 
1316                 });
1317             }
1318         },
1319         setSort : function() {
1320             return ['create_date'];
1321         }
1322     }
1323
1324     $scope.initTab('other', $routeParams.id)
1325     .then(function(redirect) {
1326         // if we are redirecting to the alerts page, avoid updating the
1327         // grid query.
1328         if (redirect) return;
1329         // let initTab() fetch the user first so we can know the usrgroup
1330
1331         grid.setQuery({
1332             usrgroup : patronSvc.current.usrgroup(),
1333             deleted : 'f'
1334         });
1335         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1336     });
1337
1338     $scope.removeFromGroup = function(selected) {
1339         var promises = [];
1340         angular.forEach(selected, function(user) {
1341             console.debug('removing user ' + user.id + ' from group');
1342
1343             promises.push(
1344                 egCore.net.request(
1345                     'open-ils.actor',
1346                     'open-ils.actor.usergroup.new',
1347                     egCore.auth.token(), user.id, true
1348                 )
1349             );
1350         });
1351
1352         $q.all(promises).then(function() {grid.refresh()});
1353     }
1354
1355     function addUserToGroup(user) {
1356         user.usrgroup(patronSvc.current.usrgroup());
1357         user.ischanged(true);
1358         egCore.net.request(
1359             'open-ils.actor',
1360             'open-ils.actor.patron.update',
1361             egCore.auth.token(), user
1362
1363         ).then(function() {grid.refresh()});
1364     }
1365
1366     // fetch each user ("selected" has flattened users)
1367     // update the usrgroup, then update the user object
1368     // After all updates are complete, refresh the grid.
1369     function moveUsersToGroup(target_user, selected) {
1370         var promises = [];
1371
1372         angular.forEach(selected, function(user) {
1373             promises.push(
1374                 egCore.pcrud.retrieve('au', user.id)
1375                 .then(function(u) {
1376                     u.usrgroup(target_user.usrgroup());
1377                     u.ischanged(true);
1378                     return egCore.net.request(
1379                         'open-ils.actor',
1380                         'open-ils.actor.patron.update',
1381                         egCore.auth.token(), u
1382                     );
1383                 })
1384             );
1385         });
1386
1387         $q.all(promises).then(function() {grid.refresh()});
1388     }
1389
1390     function showMoveToGroupConfirm(barcode, selected) {
1391
1392         // find the user
1393         egCore.pcrud.search('ac', {barcode : barcode})
1394
1395         // fetch the fleshed user
1396         .then(function(card) {
1397
1398             if (!card) return; // TODO: warn user
1399
1400             egCore.pcrud.retrieve('au', card.usr())
1401             .then(function(user) {
1402                 user.card(card);
1403                 $modal.open({
1404                     templateUrl: './circ/patron/t_move_to_group_dialog',
1405                     controller: [
1406                                 '$scope','$modalInstance',
1407                         function($scope , $modalInstance) {
1408                             $scope.user = user;
1409                             $scope.outbound = Boolean(selected);
1410                             $scope.ok = 
1411                                 function(count) { $modalInstance.close() }
1412                             $scope.cancel = 
1413                                 function () { $modalInstance.dismiss() }
1414                         }
1415                     ]
1416                 }).result.then(function() {
1417                     if (selected) {
1418                         moveUsersToGroup(user, selected);
1419                     } else {
1420                         addUserToGroup(user);
1421                     }
1422                 });
1423             });
1424         });
1425     }
1426
1427     // selected == move selected patrons to another patron's group
1428     // !selected == patron from a different group moves into our group
1429     function moveToGroup(selected) {
1430         egPromptDialog.open(
1431             egCore.strings.GROUP_ADD_USER, '',
1432             {ok : function(value) {
1433                 if (value) 
1434                     showMoveToGroupConfirm(value, selected);
1435             }}
1436         );
1437     }
1438
1439     $scope.moveToGroup = function() { moveToGroup() };
1440     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected) };
1441
1442     $scope.cloneUser = function(selected) {
1443         if (!selected.length) return;
1444         var url = $location.absUrl().replace(
1445             /\/patron\/.*/, 
1446             '/patron/register/clone/' + selected[0].id);
1447         $window.open(url, '_blank').focus();
1448     }
1449
1450     $scope.retrieveSelected = function(selected) {
1451         if (!selected.length) return;
1452         var url = $location.absUrl().replace(
1453             /\/patron\/.*/, 
1454             '/patron/' + selected[0].id + '/checkout');
1455         $window.open(url, '_blank').focus();
1456     }
1457
1458 }])
1459
1460 .controller('PatronStatCatsCtrl',
1461        ['$scope','$routeParams','$q','egCore','patronSvc',
1462 function($scope,  $routeParams , $q , egCore , patronSvc) {
1463     $scope.initTab('other', $routeParams.id)
1464     .then(function(redirect) {
1465         // Entries for org-visible stat cats are fleshed.  Any others
1466         // have to be fleshed within.
1467
1468         var to_flesh = {};
1469         angular.forEach(patronSvc.current.stat_cat_entries(), 
1470             function(entry) {
1471                 if (!angular.isObject(entry.stat_cat())) {
1472                     to_flesh[entry.stat_cat()] = entry;
1473                 }
1474             }
1475         );
1476
1477         if (!Object.keys(to_flesh).length) return;
1478
1479         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1480         .then(null, null, function(cat) { // stream
1481             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1482             to_flesh[cat.id()].stat_cat(cat);
1483         });
1484     });
1485 }])
1486
1487 .controller('PatronFetchLastCtrl',
1488        ['$scope','$location','egCore',
1489 function($scope , $location , egCore) {
1490
1491     var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1492     if (id) return $location.path('/circ/patron/' + id + '/checkout');
1493
1494     $scope.no_last = true;
1495 }])
1496
1497 .controller('PatronTriggeredEventsCtrl',
1498        ['$scope','$routeParams','$location','egCore','patronSvc',
1499 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1500     $scope.initTab('other', $routeParams.id);
1501
1502     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1503     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1504
1505     $scope.triggered_events_url = url;
1506     $scope.funcs = {};
1507 }])
1508
1509 .controller('PatronPermsCtrl',
1510        ['$scope','$routeParams','$window','$location','egCore',
1511 function($scope , $routeParams , $window , $location , egCore) {
1512     $scope.initTab('other', $routeParams.id);
1513
1514     var url = $location.absUrl().replace(
1515         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1516
1517     url += '?usr=' + encodeURIComponent($routeParams.id);
1518
1519     // user_edit does not load the session via cookie.  It uses URL 
1520     // params or xulG instead.  Pass via xulG.
1521     $scope.funcs = {
1522         ses : egCore.auth.token(),
1523         on_patron_save : function() {
1524             $scope.funcs.reload();
1525         }
1526     }
1527
1528     $scope.user_perms_url = url;
1529 }])
1530