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