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