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