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