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