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