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