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