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