]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
LP#1452950 required/suggested/all fields selectors
[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: 'PatronRegCtrl',
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     $scope.is_patron_edit = function() {
561         return Boolean($location.path().match(/patron\/\d+\/edit$/));
562     }
563
564     // To support the fixed position patron edit actions bar,
565     // its markup has to live outside the scope of the patron 
566     // edit controller.  Insert a scope blob here that can be
567     // modifed from within the patron edit controller.
568     $scope.edit_passthru = {};
569
570     // returns true if a redirect occurs
571     function redirectToAlertPanel() {
572
573         $scope.alert_penalties = 
574             function() {return patronSvc.alert_penalties}
575
576         if (patronSvc.alertsShown) return false;
577         patronSvc.alertsShown = true;
578
579         // if the patron has any unshown alerts, show them now
580         if (patronSvc.hasAlerts && 
581             !$location.path().match(/alerts$/)) {
582
583             $location
584                 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
585                 .search('card', null);
586             return true;
587         }
588
589         // no alert required.  If the patron has fines and the show-bills
590         // OUS is applied, direct to the bills page.
591         if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
592             && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
593             && !$location.path().match(/bills$/)) {
594
595             $scope.tab = 'bills';
596             $location
597                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
598                 .search('card', null);
599
600             return true;
601         }
602
603         return false;
604     }
605
606     // called after each route-specified controller is instantiated.
607     // this doubles as a way to inform the top-level controller that
608     // egStartup.go() has completed, which means we are clear to 
609     // fetch the patron, etc.
610     $scope.initTab = function(tab, patron_id) {
611         console.log('init tab ' + tab);
612         $scope.tab = tab;
613         $scope.aous = egCore.env.aous;
614
615         if (patron_id) {
616             $scope.patron_id = patron_id;
617             return patronSvc.setPrimary($scope.patron_id)
618             .then(function() {return patronSvc.checkAlerts()})
619             .then(redirectToAlertPanel);
620         }
621         return $q.when();
622     }
623
624     $scope._show_dob = {};
625     $scope.show_dob = function (val) {
626         if ($scope.patron()) {
627             if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
628             return $scope._show_dob[$scope.patron().id()];
629         }
630         return !egCore.env.aous['circ.obscure_dob'];
631     }
632         
633     $scope.obscure_dob = function() { 
634         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
635     }
636     $scope.now_show_dob = function() { 
637         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
638             $scope.show_dob() : true; 
639     }
640
641     $scope.patron = function() { return patronSvc.current }
642     $scope.patron_stats = function() { return patronSvc.patron_stats }
643     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
644
645     $scope.print_address = function(addr) {
646         egCore.print.print({
647             context : 'default', 
648             template : 'patron_address', 
649             scope : {
650                 patron : egCore.idl.toHash(patronSvc.current),
651                 address : egCore.idl.toHash(addr)
652             }
653         });
654     }
655
656     $scope.toggle_expand_summary = function() {
657         if ($scope.collapsePatronSummary) {
658             $scope.collapsePatronSummary = false;
659             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
660         } else {
661             $scope.collapsePatronSummary = true;
662             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
663         }
664     }
665     
666     // always expand the patron summary in the search UI, regardless
667     // of stored preference.
668     $scope.collapse_summary = function() {
669         return $scope.tab != 'search' && $scope.collapsePatronSummary;
670     }
671
672     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
673     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
674 }])
675
676 .controller('PatronBarcodeSearchCtrl',
677        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
678 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
679     $scope.selectMe = true; // focus text input
680     patronSvc.clearPrimary(); // clear the default user
681
682     // jump to the patron checkout UI
683     function loadPatron(user_id) {
684         $location
685         .path('/circ/patron/' + user_id + '/checkout')
686         .search('card', $scope.args.barcode);
687     }
688
689     // create an opt-in=yes response for the loaded user
690     function createOptIn(user_id) {
691         egCore.net.request(
692             'open-ils.actor',
693             'open-ils.actor.user.org_unit_opt_in.create',
694             egCore.auth.token(), user_id).then(function(resp) {
695                 if (evt = egCore.evt.parse(resp)) return alert(evt);
696                 loadPatron(user_id);
697             }
698         );
699     }
700
701     $scope.submitBarcode = function(args) {
702         $scope.bcNotFound = null;
703         if (!args.barcode) return;
704
705         // blur so next time it's set to true it will re-apply select()
706         $scope.selectMe = false;
707
708         var user_id;
709
710         // lookup barcode
711         egCore.net.request(
712             'open-ils.actor',
713             'open-ils.actor.get_barcodes',
714             egCore.auth.token(), egCore.auth.user().ws_ou(), 
715             'actor', args.barcode)
716
717         .then(function(resp) { // get_barcodes
718
719             if (evt = egCore.evt.parse(resp)) {
720                 alert(evt); // FIXME
721                 return;
722             }
723
724             if (!resp || !resp[0]) {
725                 $scope.bcNotFound = args.barcode;
726                 $scope.selectMe = true;
727                 return;
728             }
729
730             // see if an opt-in request is needed
731             user_id = resp[0].id;
732             return egCore.net.request(
733                 'open-ils.actor',
734                 'open-ils.actor.user.org_unit_opt_in.check',
735                 egCore.auth.token(), user_id);
736
737         }).then(function(optInResp) { // opt_in_check
738
739             if (evt = egCore.evt.parse(optInResp)) {
740                 alert(evt); // FIXME
741                 return;
742             }
743            
744             if (optInResp == 1) {
745                 // opt-in handled or not needed
746                 return loadPatron(user_id);
747             }
748
749             // opt-in needed, show the opt-in dialog
750             egUser.get(user_id, {useFields : []})
751
752             .then(function(user) { // retrieve user
753                 egConfirmDialog.open(
754                     egCore.strings.OPT_IN_DIALOG, '',
755                     {   org : egCore.org.get(user.home_ou()),
756                         user : user,
757                         ok : function() { createOptIn(user.id()) },
758                         cancel : function() {}
759                     }
760                 );
761             })
762         });
763     }
764 }])
765
766
767 /**
768  * Manages patron search
769  */
770 .controller('PatronSearchCtrl',
771        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore',
772        '$filter','egUser', 'patronSvc','egGridDataProvider','$document',
773 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore,
774         $filter,  egUser,  patronSvc , egGridDataProvider , $document) {
775
776     $scope.initTab('search');
777     $scope.focusMe = true;
778     $scope.searchArgs = {
779         // default to searching globally
780         home_ou : egCore.org.tree()
781     };
782
783     // last used patron search form element
784     var lastFormElement;
785
786     $scope.gridControls = {
787         activateItem : function(item) {
788             $location.path('/circ/patron/' + item.id() + '/checkout');
789         },
790         selectedItems : function() {return []}
791     }
792
793     // Handle URL-encoded searches
794     if ($location.search().search) {
795         patronSvc.urlSearch = {search : JSON2js($location.search().search)};
796
797         // why the double-JSON encoded sort?
798         patronSvc.urlSearch.sort = 
799             JSON2js(patronSvc.urlSearch.search.search_sort);
800         delete patronSvc.urlSearch.search.search_sort;
801     }
802
803     var propagate;
804     if (patronSvc.lastSearch) {
805         propagate = patronSvc.lastSearch.search;
806     } else if (patronSvc.urlSearch) {
807         propagate = patronSvc.urlSearch.search;
808     }
809
810     if (egCore.env.pgt) {
811         $scope.profiles = egCore.env.pgt.list;
812     } else {
813         egCore.pcrud.search('pgt', {parent : null}, 
814             {flesh : -1, flesh_fields : {pgt : ['children']}}
815         ).then(
816             function(tree) {
817                 egCore.env.absorbTree(tree, 'pgt')
818                 $scope.profiles = egCore.env.pgt.list;
819             }
820         );
821     }
822
823     if (propagate) {
824         // populate the search form with our cached / preexisting search info
825         angular.forEach(propagate, function(val, key) {
826             if (key == 'profile')
827                 val.value = $scope.profiles.filter(function(p) { p.id() == val.value })[0];
828             if (key == 'home_ou')
829                 val.value = egCore.org.get(val.value);
830             $scope.searchArgs[key] = val.value;
831         });
832     }
833
834     var provider = egGridDataProvider.instance({});
835
836     $scope.$watch(
837         function() {return $scope.gridControls.selectedItems()},
838         function(list) {
839             if (list[0]) 
840                 patronSvc.setPrimary(null, list[0]);
841         },
842         true
843     );
844         
845     provider.get = function(offset, count) {
846         var deferred = $q.defer();
847
848         var fullSearch;
849         if (patronSvc.urlSearch) {
850             fullSearch = patronSvc.urlSearch;
851             // enusre the urlSearch only runs once.
852             delete patronSvc.urlSearch;
853
854         } else {
855
856             var search = compileSearch($scope.searchArgs);
857             if (Object.keys(search) == 0) return $q.when();
858
859             var home_ou = search.home_ou;
860             delete search.home_ou;
861             var inactive = search.inactive;
862             delete search.inactive;
863
864             fullSearch = {
865                 search : search,
866                 sort : compileSort(),
867                 inactive : inactive,
868                 home_ou : home_ou,
869             };
870         }
871
872         fullSearch.count = count;
873         fullSearch.offset = offset;
874
875         if (patronSvc.lastSearch) {
876             // search repeated, return the cached results
877             if (angular.equals(fullSearch, patronSvc.lastSearch)) {
878                 console.log('patron search returning ' + 
879                     patronSvc.patrons.length + ' cached results');
880                 
881                 // notify has to happen after returning the promise
882                 $timeout(
883                     function() {
884                         angular.forEach(patronSvc.patrons, function(user) {
885                             deferred.notify(user);
886                         });
887                         deferred.resolve();
888                     }
889                 );
890                 return deferred.promise;
891             }
892         }
893
894         patronSvc.lastSearch = fullSearch;
895
896         if (fullSearch.search.id) {
897             // search by user id performs a direct ID lookup
898             var userId = fullSearch.search.id.value;
899             $timeout(
900                 function() {
901                     egUser.get(userId).then(function(user) {
902                         patronSvc.localFlesh(user);
903                         patronSvc.patrons = [user];
904                         deferred.notify(user);
905                         deferred.resolve();
906                     });
907                 }
908             );
909             return deferred.promise;
910         }
911
912         patronSvc.patrons = [];
913         egCore.net.request(
914             'open-ils.actor',
915             'open-ils.actor.patron.search.advanced.fleshed',
916             egCore.auth.token(), 
917             fullSearch.search, 
918             fullSearch.count,
919             fullSearch.sort,
920             fullSearch.inactive,
921             fullSearch.home_ou,
922             egUser.defaultFleshFields,
923             fullSearch.offset
924
925         ).then(
926             function() { deferred.resolve() },
927             null, // onerror
928             function(user) {
929                 patronSvc.localFlesh(user); // inline
930                 patronSvc.patrons.push(user);
931                 deferred.notify(user);
932             }
933         );
934
935         return deferred.promise;
936     };
937
938     $scope.patronSearchGridProvider = provider;
939
940     // determine the tree depth of the profile group
941     $scope.pgt_depth = function(grp) {
942         var d = 0;
943         while (grp = egCore.env.pgt.map[grp.parent()]) d++;
944         return d;
945     }
946
947     $scope.clearForm = function () {
948         $scope.searchArgs={};
949         if (lastFormElement) lastFormElement.focus();
950     }
951
952     $scope.applyShowExtras = function($event, bool) {
953         if (bool) {
954             $scope.showExtras = true;
955             egCore.hatch.setItem('eg.circ.patron.search.show_extras', true);
956         } else {
957             $scope.showExtras = false;
958             egCore.hatch.removeItem('eg.circ.patron.search.show_extras');
959         }
960         if (lastFormElement) lastFormElement.focus();
961         $event.preventDefault();
962     }
963
964     egCore.hatch.getItem('eg.circ.patron.search.show_extras')
965     .then(function(val) {$scope.showExtras = val});
966
967     // map form arguments into search params
968     function compileSearch(args) {
969         var search = {};
970         angular.forEach(args, function(val, key) {
971             if (!val) return;
972             if (key == 'profile' && args.profile) {
973                 search.profile = {value : args.profile.id(), group : 0};
974             } else if (key == 'home_ou' && args.home_ou) {
975                 search.home_ou = args.home_ou.id(); // passed separately
976             } else if (key == 'inactive') {
977                 search.inactive = val;
978             } else {
979                 search[key] = {value : val, group : 0};
980             }
981             if (key.match(/phone|ident/)) {
982                 search[key].group = 2;
983             } else {
984                 if (key.match(/street|city|state|post_code/)) {
985                     search[key].group = 1;
986                 } else if (key == 'card') {
987                     search[key].group = 3
988                 }
989             }
990         });
991
992         return search;
993     }
994
995     function compileSort() {
996
997         if (!provider.sort.length) {
998             return [ // default
999                 "family_name ASC",
1000                 "first_given_name ASC",
1001                 "second_given_name ASC",
1002                 "dob DESC"
1003             ];
1004         }
1005
1006         var sort = [];
1007         angular.forEach(
1008             provider.sort,
1009             function(sortdef) {
1010                 if (angular.isObject(sortdef)) {
1011                     var name = Object.keys(sortdef)[0];
1012                     var dir = sortdef[name];
1013                     sort.push(name + ' ' + dir);
1014                 } else {
1015                     sort.push(sortdef);
1016                 }
1017             }
1018         );
1019
1020         return sort;
1021     }
1022
1023     $scope.setLastFormElement = function() {
1024         lastFormElement = $document[0].activeElement;
1025     }
1026
1027     // search form submit action; tells the results grid to
1028     // refresh itself.
1029     $scope.search = function(args) { // args === $scope.searchArgs
1030         if (args && Object.keys(args).length) 
1031             $scope.gridControls.refresh();
1032         if (lastFormElement) lastFormElement.focus();
1033     }
1034
1035     // TODO: move this into the (forthcoming) grid row activate action
1036     $scope.onPatronDblClick = function($event, user) {
1037         $location.path('/circ/patron/' + user.id() + '/checkout');
1038     }
1039
1040     if (patronSvc.urlSearch) {
1041         // force the grid to load the url-based search on page load
1042         provider.refresh();
1043     }
1044    
1045 }])
1046
1047 /**
1048  * Manages messages
1049  */
1050 .controller('PatronMessagesCtrl',
1051        ['$scope','$q','$routeParams','egCore','$modal','patronSvc','egCirc',
1052 function($scope , $q , $routeParams,  egCore , $modal , patronSvc , egCirc) {
1053     $scope.initTab('messages', $routeParams.id);
1054     var usr_id = $routeParams.id;
1055
1056     // setup date filters
1057     var start = new Date(); // now - 1 year
1058     start.setFullYear(start.getFullYear() - 1),
1059     $scope.dates = {
1060         start_date : start,
1061         end_date : new Date()
1062     }
1063
1064     function date_range() {
1065         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
1066         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
1067         var today = new Date().toISOString().replace(/T.*/,'');
1068         if (end == today) end = 'now';
1069         return [start, end];
1070     }
1071
1072     // grid queries
1073    
1074     var activeGrid = $scope.activeGridControls = {
1075         setSort : function() {
1076             return ['set_date'];
1077         },
1078         setQuery : function() {
1079             return {
1080                 usr : usr_id,
1081                 '-or' : [
1082                     {stop_date : null},
1083                     {stop_date : {'>' : 'now'}}
1084                 ]
1085             }
1086         }
1087     }
1088
1089     var archiveGrid = $scope.archiveGridControls = {
1090         setSort : function() {
1091             return ['set_date'];
1092         },
1093         setQuery : function() {
1094             return {
1095                 usr : usr_id, 
1096                 stop_date : {'<=' : 'now'},
1097                 set_date : {between : date_range()}
1098             };
1099         }
1100     };
1101
1102     $scope.removePenalty = function(selected) {
1103         // the grid stores flattened penalties.  Fetch penalty objects first
1104
1105         var ids = selected.map(function(s){ return s.id });
1106         egCore.pcrud.search('ausp', 
1107             {id : ids}, {}, 
1108             {atomic : true, authoritative : true}
1109
1110         // then delete them
1111         ).then(function(penalties) {
1112             return egCore.pcrud.remove(penalties);
1113
1114         // then refresh the grid
1115         }).then(function() {
1116             activeGrid.refresh();
1117         });
1118     }
1119
1120     $scope.archivePenalty = function(selected) {
1121         // the grid stores flattened penalties.  Fetch penalty objects first
1122
1123         var ids = selected.map(function(s){ return s.id });
1124         egCore.pcrud.search('ausp', 
1125             {id : ids}, {}, 
1126             {atomic : true, authoritative : true}
1127
1128         // then delete them
1129         ).then(function(penalties) {
1130             angular.forEach(penalties, function(p){ p.stop_date('now') });
1131             return egCore.pcrud.update(penalties);
1132
1133         // then refresh the grid
1134         }).then(function() {
1135             activeGrid.refresh();
1136             archiveGrid.refresh();
1137         });
1138     }
1139
1140     // leverage egEnv for caching
1141     function fetchPenaltyTypes() {
1142         if (egCore.env.csp) 
1143             return $q.when(egCore.env.csp.list);
1144         return egCore.pcrud.search(
1145             // id <= 100 are reserved for system use
1146             'csp', {id : {'>': 100}}, {}, {atomic : true})
1147         .then(function(penalties) {
1148             egCore.env.absorbList(penalties, 'csp');
1149             return penalties;
1150         });
1151     }
1152
1153     $scope.createPenalty = function() {
1154         egCirc.create_penalty(usr_id).then(function() {
1155             activeGrid.refresh();
1156             // force a refresh of the user, since they may now
1157             // have blocking penalties, etc.
1158             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1159         });
1160     }
1161
1162     $scope.editPenalty = function(selected) {
1163         if (selected.length == 0) return;
1164
1165         // grab the penalty from the user object
1166         var penalty = patronSvc.current.standing_penalties().filter(
1167             function(p) {return p.id() == selected[0].id})[0];
1168
1169         egCirc.edit_penalty(penalty).then(function() {
1170             activeGrid.refresh();
1171             // force a refresh of the user, since they may now
1172             // have blocking penalties, etc.
1173             patronSvc.setPrimary(patronSvc.current.id(), null, true);
1174         });
1175     }
1176 }])
1177
1178
1179 /**
1180  * Credentials tester
1181  */
1182 .controller('PatronVerifyCredentialsCtrl',
1183        ['$scope','$routeParams','$location','egCore',
1184 function($scope,  $routeParams , $location , egCore) {
1185     $scope.verified = null;
1186     $scope.focusMe = true;
1187
1188     // called with a patron, pre-populate the form args
1189     $scope.initTab('other', $routeParams.id).then(
1190         function() {
1191             if ($routeParams.id && $scope.patron()) {
1192                 $scope.prepop = true;
1193                 $scope.username = $scope.patron().usrname();
1194                 $scope.barcode = $scope.patron().card().barcode();
1195             } else {
1196                 $scope.username = '';
1197                 $scope.barcode = '';
1198                 $scope.password = '';
1199             }
1200         }
1201     );
1202
1203     // verify login credentials
1204     $scope.verify = function() {
1205         $scope.verified = null;
1206         $scope.notFound = false;
1207
1208         egCore.net.request(
1209             'open-ils.actor',
1210             'open-ils.actor.verify_user_password',
1211             egCore.auth.token(), $scope.barcode,
1212             $scope.username, hex_md5($scope.password || '')
1213
1214         ).then(function(resp) {
1215             $scope.focusMe = true;
1216             if (evt = egCore.evt.parse(resp)) {
1217                 alert(evt);
1218             } else if (resp == 1) {
1219                 $scope.verified = true;
1220             } else {
1221                 $scope.verified = false;
1222             }
1223         });
1224     }
1225
1226     // load the main patron UI for the provided username or barcode
1227     $scope.load = function($event) {
1228         $scope.notFound = false;
1229         $scope.verified = null;
1230
1231         egCore.net.request(
1232             'open-ils.actor',
1233             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1234             egCore.auth.token(), $scope.barcode, $scope.username
1235
1236         ).then(function(resp) {
1237
1238             if (Number(resp)) {
1239                 $location.path('/circ/patron/' + resp + '/checkout');
1240                 return;
1241             }
1242
1243             // something went wrong...
1244             $scope.focusMe = true;
1245             if (evt = egCore.evt.parse(resp)) {
1246                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1247                     $scope.notFound = true;
1248                     return;
1249                 }
1250                 return alert(evt);
1251             } else {
1252                 alert(resp);
1253             }
1254         });
1255
1256         // load() button sits within the verify form.  
1257         // avoid submitting the verify() form action on load()
1258         $event.preventDefault();
1259     }
1260 }])
1261
1262 .controller('PatronAlertsCtrl',
1263        ['$scope','$routeParams','$location','egCore','patronSvc',
1264 function($scope,  $routeParams , $location , egCore , patronSvc) {
1265
1266     $scope.initTab('other', $routeParams.id)
1267     .then(function() {
1268         $scope.patronExpired = patronSvc.patronExpired;
1269         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1270         $scope.retrievedWithInactive = patronSvc.retrievedWithInactive;
1271         $scope.invalidAddresses = patronSvc.invalidAddresses;
1272     });
1273
1274 }])
1275
1276 .controller('PatronNotesCtrl',
1277        ['$scope','$routeParams','$location','egCore','patronSvc','$modal',
1278 function($scope,  $routeParams , $location , egCore , patronSvc , $modal) {
1279     $scope.initTab('other', $routeParams.id);
1280     var usr_id = $routeParams.id;
1281
1282     // fetch the notes
1283     function refreshPage() {
1284         $scope.notes = [];
1285         egCore.pcrud.search('aun', 
1286             {usr : usr_id}, 
1287             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
1288             {authoritative : true})
1289         .then(null, null, function(note) {
1290             $scope.notes.push(note);
1291         });
1292     }
1293
1294     // open the new-note dialog and create the note
1295     $scope.newNote = function() {
1296         $modal.open({
1297             templateUrl: './circ/patron/t_new_note_dialog',
1298             controller: 
1299                 ['$scope', '$modalInstance',
1300             function($scope, $modalInstance) {
1301                 $scope.focusNote = true;
1302                 $scope.args = {};
1303                 $scope.ok = function(count) { $modalInstance.close($scope.args) }
1304                 $scope.cancel = function () { $modalInstance.dismiss() }
1305             }],
1306         }).result.then(
1307             function(args) {
1308                 if (!args.value) return;
1309                 var note = new egCore.idl.aun();
1310                 note.usr(usr_id);
1311                 note.title(args.title);
1312                 note.value(args.value);
1313                 note.pub(args.pub ? 't' : 'f');
1314                 note.creator(egCore.auth.user().id());
1315                 egCore.pcrud.create(note).then(function() {refreshPage()});
1316             }
1317         );
1318     }
1319
1320     // delete the selected note
1321     $scope.deleteNote = function(note) {
1322         egCore.pcrud.remove(note).then(function() {refreshPage()});
1323     }
1324
1325     // print the selected note
1326     $scope.printNote = function(note) {
1327         var hash = egCore.idl.toHash(note);
1328         hash.usr = egCore.idl.toHash($scope.patron());
1329         egCore.print.print({
1330             context : 'default', 
1331             template : 'patron_note', 
1332             scope : {note : hash}
1333         });
1334     }
1335
1336     // perform the initial note fetch
1337     refreshPage();
1338 }])
1339
1340 .controller('PatronGroupCtrl',
1341        ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1342         'patronSvc','$modal','egPromptDialog','egConfirmDialog',
1343 function($scope,  $routeParams , $q , $window , $timeout,  $location , egCore ,
1344          patronSvc , $modal , egPromptDialog , egConfirmDialog) {
1345
1346     var usr_id = $routeParams.id;
1347
1348     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1349
1350     var grid = $scope.gridControls = {
1351         activateItem : function(item) {
1352             $location.path('/circ/patron/' + item.id + '/checkout');
1353         },
1354         itemRetrieved : function(item) {
1355
1356             if (item.id == patronSvc.current.id()) {
1357                 item.stats = patronSvc.patron_stats;
1358
1359             } else {
1360                 // flesh stats for other group members
1361                 patronSvc.getUserStats(item.id).then(function(stats) {
1362                     item.stats = stats;
1363                     $scope.totals.total_out += stats.checkouts.total_out; 
1364                     $scope.totals.overdue += stats.checkouts.overdue; 
1365                 });
1366             }
1367         },
1368         setSort : function() {
1369             return ['create_date'];
1370         }
1371     }
1372
1373     $scope.initTab('other', $routeParams.id)
1374     .then(function(redirect) {
1375         // if we are redirecting to the alerts page, avoid updating the
1376         // grid query.
1377         if (redirect) return;
1378         // let initTab() fetch the user first so we can know the usrgroup
1379
1380         grid.setQuery({
1381             usrgroup : patronSvc.current.usrgroup(),
1382             deleted : 'f'
1383         });
1384         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1385     });
1386
1387     $scope.removeFromGroup = function(selected) {
1388         var promises = [];
1389         angular.forEach(selected, function(user) {
1390             console.debug('removing user ' + user.id + ' from group');
1391
1392             promises.push(
1393                 egCore.net.request(
1394                     'open-ils.actor',
1395                     'open-ils.actor.usergroup.new',
1396                     egCore.auth.token(), user.id, true
1397                 )
1398             );
1399         });
1400
1401         $q.all(promises).then(function() {grid.refresh()});
1402     }
1403
1404     function addUserToGroup(user) {
1405         user.usrgroup(patronSvc.current.usrgroup());
1406         user.ischanged(true);
1407         egCore.net.request(
1408             'open-ils.actor',
1409             'open-ils.actor.patron.update',
1410             egCore.auth.token(), user
1411
1412         ).then(function() {grid.refresh()});
1413     }
1414
1415     // fetch each user ("selected" has flattened users)
1416     // update the usrgroup, then update the user object
1417     // After all updates are complete, refresh the grid.
1418     function moveUsersToGroup(target_user, selected) {
1419         var promises = [];
1420
1421         angular.forEach(selected, function(user) {
1422             promises.push(
1423                 egCore.pcrud.retrieve('au', user.id)
1424                 .then(function(u) {
1425                     u.usrgroup(target_user.usrgroup());
1426                     u.ischanged(true);
1427                     return egCore.net.request(
1428                         'open-ils.actor',
1429                         'open-ils.actor.patron.update',
1430                         egCore.auth.token(), u
1431                     );
1432                 })
1433             );
1434         });
1435
1436         $q.all(promises).then(function() {grid.refresh()});
1437     }
1438
1439     function showMoveToGroupConfirm(barcode, selected, outbound) {
1440
1441         // find the user
1442         egCore.pcrud.search('ac', {barcode : barcode})
1443
1444         // fetch the fleshed user
1445         .then(function(card) {
1446
1447             if (!card) return; // TODO: warn user
1448
1449             egCore.pcrud.retrieve('au', card.usr())
1450             .then(function(user) {
1451                 user.card(card);
1452                 $modal.open({
1453                     templateUrl: './circ/patron/t_move_to_group_dialog',
1454                     controller: [
1455                                 '$scope','$modalInstance',
1456                         function($scope , $modalInstance) {
1457                             $scope.user = user;
1458                             $scope.selected = selected;
1459                             $scope.outbound = outbound;
1460                             $scope.ok = 
1461                                 function(count) { $modalInstance.close() }
1462                             $scope.cancel = 
1463                                 function () { $modalInstance.dismiss() }
1464                         }
1465                     ]
1466                 }).result.then(function() {
1467                     if (outbound) {
1468                         moveUsersToGroup(user, selected);
1469                     } else {
1470                         addUserToGroup(user);
1471                     }
1472                 });
1473             });
1474         });
1475     }
1476
1477     // selected == move selected patrons to another patron's group
1478     // !selected == patron from a different group moves into our group
1479     function moveToGroup(selected, outbound) {
1480         egPromptDialog.open(
1481             egCore.strings.GROUP_ADD_USER, '',
1482             {ok : function(value) {
1483                 if (value) 
1484                     showMoveToGroupConfirm(value, selected, outbound);
1485             }}
1486         );
1487     }
1488
1489     $scope.moveToGroup = function() { moveToGroup([], false) };
1490     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1491
1492     $scope.cloneUser = function(selected) {
1493         if (!selected.length) return;
1494         var url = $location.absUrl().replace(
1495             /\/patron\/.*/, 
1496             '/patron/register/clone/' + selected[0].id);
1497         $window.open(url, '_blank').focus();
1498     }
1499
1500     $scope.retrieveSelected = function(selected) {
1501         if (!selected.length) return;
1502         angular.forEach(selected, function(usr) {
1503             $timeout(function() {
1504                 var url = $location.absUrl().replace(
1505                     /\/patron\/.*/,
1506                     '/patron/' + usr.id + '/checkout');
1507                 $window.open(url, '_blank')
1508             });
1509         });
1510     }
1511
1512 }])
1513
1514 .controller('PatronStatCatsCtrl',
1515        ['$scope','$routeParams','$q','egCore','patronSvc',
1516 function($scope,  $routeParams , $q , egCore , patronSvc) {
1517     $scope.initTab('other', $routeParams.id)
1518     .then(function(redirect) {
1519         // Entries for org-visible stat cats are fleshed.  Any others
1520         // have to be fleshed within.
1521
1522         var to_flesh = {};
1523         angular.forEach(patronSvc.current.stat_cat_entries(), 
1524             function(entry) {
1525                 if (!angular.isObject(entry.stat_cat())) {
1526                     to_flesh[entry.stat_cat()] = entry;
1527                 }
1528             }
1529         );
1530
1531         if (!Object.keys(to_flesh).length) return;
1532
1533         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1534         .then(null, null, function(cat) { // stream
1535             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1536             to_flesh[cat.id()].stat_cat(cat);
1537         });
1538     });
1539 }])
1540
1541 .controller('PatronFetchLastCtrl',
1542        ['$scope','$location','egCore',
1543 function($scope , $location , egCore) {
1544
1545     var id = egCore.hatch.getLocalItem('eg.circ.last_patron');
1546     if (id) return $location.path('/circ/patron/' + id + '/checkout');
1547
1548     $scope.no_last = true;
1549 }])
1550
1551 .controller('PatronTriggeredEventsCtrl',
1552        ['$scope','$routeParams','$location','egCore','patronSvc',
1553 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1554     $scope.initTab('other', $routeParams.id);
1555
1556     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1557     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1558
1559     $scope.triggered_events_url = url;
1560     $scope.funcs = {};
1561 }])
1562
1563 .controller('PatronPermsCtrl',
1564        ['$scope','$routeParams','$window','$location','egCore',
1565 function($scope , $routeParams , $window , $location , egCore) {
1566     $scope.initTab('other', $routeParams.id);
1567
1568     var url = $location.absUrl().replace(
1569         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1570
1571     url += '?usr=' + encodeURIComponent($routeParams.id);
1572
1573     // user_edit does not load the session via cookie.  It uses URL 
1574     // params or xulG instead.  Pass via xulG.
1575     $scope.funcs = {
1576         ses : egCore.auth.token(),
1577         on_patron_save : function() {
1578             $scope.funcs.reload();
1579         }
1580     }
1581
1582     $scope.user_perms_url = url;
1583 }])
1584