]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
LP1956970 Sort Patron Notes - Most Recent First
[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', 'egUserBucketMod', 
8     'egCoreMod', 'egUiMod', 'egGridMod', 'egUserMod', 'ngToast',
9     'egPatronSearchMod'])
10
11 .config(['ngToastProvider', function(ngToastProvider) {
12     ngToastProvider.configure({
13         verticalPosition: 'bottom',
14         animation: 'fade'
15     });
16 }])
17
18 .factory("hasPermAt",function(){
19     return {};
20 })
21
22 .config(function($routeProvider, $locationProvider, $compileProvider) {
23     $locationProvider.html5Mode(true);
24     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); // grid export
25         
26     // data loaded at startup which only requires an authtoken goes
27     // here. this allows the requests to be run in parallel instead of
28     // waiting until startup has completed.
29     var resolver = {delay : ['egCore','egUser','hasPermAt', function(egCore , egUser , hasPermAt) {
30
31         // fetch the org settings we care about during egStartup
32         // and toss them into egCore.env as egCore.env.aous[name] = value.
33         // note: only load settings here needed by all tabs; load tab-
34         // specific settings from within their respective controllers
35         egCore.env.classLoaders.aous = function() {
36             return egCore.org.settings([
37                 'ui.staff.require_initials.patron_info_notes',
38                 'circ.do_not_tally_claims_returned',
39                 'circ.tally_lost',
40                 'circ.obscure_dob',
41                 'ui.circ.show_billing_tab_on_bills',
42                 'circ.patron_expires_soon_warning',
43                 'ui.circ.items_out.lost',
44                 'ui.circ.items_out.longoverdue',
45                 'ui.circ.items_out.claimsreturned'
46             ]).then(function(settings) { 
47                 // local settings are cached within egOrg.  Caching them
48                 // again in egEnv just simplifies the syntax for access.
49                 egCore.env.aous = settings;
50             });
51         }
52
53         egCore.env.loadClasses.push('aous');
54
55         // app-globally modify the default flesh fields for 
56         // fleshed user retrieval.
57         if (egUser.defaultFleshFields.indexOf('profile') == -1) {
58             egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
59                 'profile',
60                 'net_access_level',
61                 'ident_type',
62                 'ident_type2',
63                 'cards',
64                 'groups'
65             ]);
66         }
67
68         return egCore.startup.go().then(function(go_promise) {
69             // FIXME: the following is really just for PatronMessagesCtrl
70             // and PatronCtrl, so we could refactor to avoid calling it
71             // for every controller
72             return egCore.perm.hasPermFullPathAt('VIEW_USER')
73             .then(function(orgList) {
74                 hasPermAt['VIEW_USER'] = orgList;
75                 return go_promise;
76             });
77         });
78     }]};
79
80     $routeProvider.when('/circ/patron/search', {
81         templateUrl: './circ/patron/t_search',
82         controller: 'PatronSearchCtrl',
83         resolve : resolver
84     });
85
86     $routeProvider.when('/circ/patron/bcsearch', {
87         templateUrl: './circ/patron/t_bcsearch',
88         controller: 'PatronBarcodeSearchCtrl',
89         resolve : resolver
90     });
91
92     $routeProvider.when('/circ/patron/credentials', {
93         templateUrl: './circ/patron/t_credentials',
94         controller: 'PatronVerifyCredentialsCtrl',
95         resolve : resolver
96     });
97
98     $routeProvider.when('/circ/patron/last', {
99         templateUrl: './circ/patron/t_last_patron',
100         controller: 'PatronFetchLastCtrl',
101         resolve : resolver
102     });
103
104     // the following require a patron ID
105
106     $routeProvider.when('/circ/patron/:id/alerts', {
107         templateUrl: './circ/patron/t_alerts',
108         controller: 'PatronAlertsCtrl',
109         resolve : resolver
110     });
111
112     $routeProvider.when('/circ/patron/:id/checkout', {
113         templateUrl: './circ/patron/t_checkout',
114         controller: 'PatronCheckoutCtrl',
115         resolve : resolver
116     });
117
118     $routeProvider.when('/circ/patron/:id/items_out', {
119         templateUrl: './circ/patron/t_items_out',
120         controller: 'PatronItemsOutCtrl',
121         resolve : resolver
122     });
123
124     $routeProvider.when('/circ/patron/:id/holds', {
125         templateUrl: './circ/patron/t_holds',
126         controller: 'PatronHoldsCtrl',
127         resolve : resolver
128     });
129
130     $routeProvider.when('/circ/patron/:id/holds/create', {
131         templateUrl: './circ/patron/t_holds_create',
132         controller: 'PatronHoldsCreateCtrl',
133         resolve : resolver
134     });
135
136     $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
137         templateUrl: './circ/patron/t_holds',
138         controller: 'PatronHoldsCtrl',
139         resolve : resolver
140     });
141
142     $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
143         templateUrl: './circ/patron/t_hold_details',
144         controller: 'PatronHoldDetailsCtrl',
145         resolve : resolver
146     });
147
148     $routeProvider.when('/circ/patron/:id/bills', {
149         templateUrl: './circ/patron/t_bills',
150         controller: 'PatronBillsCtrl',
151         resolve : resolver
152     });
153
154     $routeProvider.when('/circ/patron/:id/bill/:xact_id/:xact_tab', {
155         templateUrl: './circ/patron/t_xact_details',
156         controller: 'XactDetailsCtrl',
157         resolve : resolver
158     });
159
160     $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
161         templateUrl: './circ/patron/t_bill_history',
162         controller: 'BillHistoryCtrl',
163         resolve : resolver
164     });
165
166     $routeProvider.when('/circ/patron/:id/messages', {
167         templateUrl: './circ/patron/t_messages',
168         controller: 'PatronMessagesCtrl',
169         resolve : resolver
170     });
171
172     $routeProvider.when('/circ/patron/:id/edit', {
173         templateUrl: './circ/patron/t_edit',
174         controller: 'PatronRegCtrl',
175         resolve : resolver
176     });
177
178     $routeProvider.when('/circ/patron/:id/credentials', {
179         templateUrl: './circ/patron/t_credentials',
180         controller: 'PatronVerifyCredentialsCtrl',
181         resolve : resolver
182     });
183
184     $routeProvider.when('/circ/patron/:id/triggered_events', {
185         templateUrl: './circ/patron/t_triggered_events',
186         controller: 'PatronTriggeredEventsCtrl',
187         resolve : resolver
188     });
189
190     $routeProvider.when('/circ/patron/:id/message_center', {
191         templateUrl: './circ/patron/t_message_center',
192         controller: 'PatronMessageCenterCtrl',
193         resolve : resolver
194     });
195
196     $routeProvider.when('/circ/patron/:id/edit_perms', {
197         templateUrl: './circ/patron/t_edit_perms',
198         controller: 'PatronPermsCtrl',
199         resolve : resolver
200     });
201
202     $routeProvider.when('/circ/patron/:id/group', {
203         templateUrl: './circ/patron/t_group',
204         controller: 'PatronGroupCtrl',
205         resolve : resolver
206     });
207
208     $routeProvider.when('/circ/patron/:id/stat_cats', {
209         templateUrl: './circ/patron/t_stat_cats',
210         controller: 'PatronStatCatsCtrl',
211         resolve : resolver
212     });
213
214     $routeProvider.when('/circ/patron/:id/surveys', {
215         templateUrl: './circ/patron/t_surveys',
216         controller: 'PatronSurveyCtrl',
217         resolve : resolver
218     });
219
220     $routeProvider.when('/circ/patron/:id/hold_subscriptions', {
221         templateUrl: './circ/patron/t_hold_subscriptions',
222         controller: 'HoldSubscriptionsCtrl',
223         resolve : resolver
224     });
225
226     $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
227 })
228
229 /**
230  * Manages tabbed patron view.
231  * This is the parent scope of all patron tab scopes.
232  *
233  * */
234 .controller('PatronCtrl',
235        ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc','egCirc','hasPermAt',
236 function($scope,  $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc , egCirc , hasPermAt) {
237
238     $scope.is_patron_edit = function() {
239         return Boolean($location.path().match(/patron\/\d+\/edit$/));
240     }
241
242     // To support the fixed position patron edit actions bar,
243     // its markup has to live outside the scope of the patron 
244     // edit controller.  Insert a scope blob here that can be
245     // modifed from within the patron edit controller.
246     $scope.edit_passthru = {};
247
248     // returns true if a redirect occurs
249     function redirectToAlertPanel() {
250
251         $scope.alert_penalties = 
252             function() {return patronSvc.alert_penalties}
253
254         if (patronSvc.alertsShown()) return false;
255
256         // if the patron has any unshown alerts, show them now
257         if (patronSvc.hasAlerts && 
258             !$location.path().match(/alerts$/)) {
259
260             $location
261                 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
262                 .search('card', null);
263             return true;
264         }
265
266         // no alert required.  If the patron has fines and the show-bills
267         // OUS is applied, direct to the bills page.
268         if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
269             && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
270             && !$location.path().match(/bills$/)) {
271
272             $scope.tab = 'bills';
273             $location
274                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
275                 .search('card', null);
276
277             return true;
278         }
279
280         return false;
281     }
282
283     // called after each route-specified controller is instantiated.
284     // this doubles as a way to inform the top-level controller that
285     // egStartup.go() has completed, which means we are clear to 
286     // fetch the patron, etc.
287     $scope.initTab = function(tab, patron_id) {
288         console.log('init tab ' + tab);
289         $scope.tab = tab;
290         $scope.aous = egCore.env.aous;
291         $scope.auth_user_id = egCore.auth.user().id();
292
293         if (tab == 'search') {
294             egCirc.reset(); // clear out auto-override and auto-skip selections when switching patrons
295         }
296
297         if (patron_id) {
298             $scope.patron_id = patron_id;
299             return patronSvc.setPrimary($scope.patron_id)
300             .then(function() {
301                 // the page title context label comes from the tab.
302                 egCore.strings.setPageTitle(
303                     egCore.strings.PAGE_TITLE_PATRON_NAME, 
304                     egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
305                     {   lname : patronSvc.current.family_name(),
306                         fname : patronSvc.current.first_given_name(),
307                         mname : patronSvc.current.second_given_name()
308                     }
309                 );
310             })
311             .then(function() {return patronSvc.checkAlerts()})
312             .then(redirectToAlertPanel)
313             .then(function(){
314                 $scope.ident_type_name = $scope.patron().ident_type().name()
315                 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
316             });
317         } else {
318             // No patron, use the tab name as the page title.
319             egCore.strings.setPageTitle(
320                 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
321         }
322         return $q.when();
323     }
324
325     $scope._show_dob = {};
326     $scope.show_dob = function (val) {
327         if ($scope.patron()) {
328             if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
329             return $scope._show_dob[$scope.patron().id()];
330         }
331         return !egCore.env.aous['circ.obscure_dob'];
332     }
333         
334     $scope.obscure_dob = function() { 
335         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
336     }
337     $scope.now_show_dob = function() { 
338         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
339             $scope.show_dob() : true; 
340     }
341
342     $scope.patron = function() { return patronSvc.current }
343     $scope.visible_notes = function() {
344         var p = patronSvc.current;
345         if (p) {
346             var org_ids = hasPermAt['VIEW_USER'];
347             var filtered_notes = p.notes().filter(function(n) { return org_ids.indexOf(n.org_unit()) > -1; });
348             return filtered_notes;
349         }
350         return [];
351     }
352     $scope.patron_stats = function() { return patronSvc.patron_stats }
353     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
354     $scope.hasAlerts = function() { return patronSvc.hasAlerts }
355     $scope.isPatronExpired = function() { return patronSvc.patronExpired }
356     $scope.doesPatronExpireSoon = function() { return patronSvc.patronExpiresSoon }
357
358     $scope.print_address = function(addr) {
359         egCore.print.print({
360             context : 'default', 
361             template : 'patron_address', 
362             scope : {
363                 patron : egCore.idl.toHash(patronSvc.current),
364                 address : egCore.idl.toHash(addr)
365             }
366         });
367     }
368
369     $scope.copy_address = function(addr) {
370         // Alas, navigator.clipboard is not yet supported in FF and others.
371         var lNode = document.querySelector('#patron-address-copy-' + addr.id());
372
373         // Un-hide the textarea just long enough to copy its data.
374         // Using node.style instead of ng-show/ng-hide in hopes it 
375         // will be quicker, so the user never sees the textarea.
376         lNode.style.visibility = 'visible';
377         lNode.focus();
378         lNode.select();
379
380         if (!document.execCommand('copy')) {
381             console.error('Copy command failed');
382         }
383
384         lNode.style.visibility = 'hidden';
385     }
386
387     $scope.toggle_expand_summary = function() {
388         if ($scope.collapsePatronSummary) {
389             $scope.collapsePatronSummary = false;
390             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
391         } else {
392             $scope.collapsePatronSummary = true;
393             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
394         }
395     }
396     
397     // always expand the patron summary in the search UI, regardless
398     // of stored preference.
399     $scope.collapse_summary = function() {
400         return $scope.tab != 'search' && $scope.collapsePatronSummary;
401     }
402
403     function _purge_account(dest_usr,override) {
404         egNet.request(
405             'open-ils.actor',
406             'open-ils.actor.user.delete' + (override ? '.override' : ''),
407             egCore.auth.token(),
408             $scope.patron().id(),
409             dest_usr
410         ).then(function(resp){
411             if (evt = egCore.evt.parse(resp)) {
412                 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
413                     egConfirmDialog.open(
414                         egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
415                         {ok : function() {
416                             _purge_account(dest_usr,true);
417                         }}
418                     );
419                 } else {
420                     alert(js2JSON(evt));
421                 }
422             } else {
423                 location.href = egCore.env.basePath + '/circ/patron/search';
424             }
425         });
426     }
427
428     function _purge_account_with_destination(dest_barcode) {
429         egCore.pcrud.search('ac', {barcode : dest_barcode})
430         .then(function(card) {
431             if (!card) {
432                 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
433             } else {
434                 _purge_account(card.usr());
435             }
436         });
437     }
438
439     $scope.purge_account = function() {
440         egConfirmDialog.open(
441             egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
442             {ok : function() {
443                 egConfirmDialog.open(
444                     egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
445                     {ok : function() {
446                         egNet.request(
447                             'open-ils.actor',
448                             'open-ils.actor.user.has_work_perm_at',
449                             egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
450                         ).then(function(resp) {
451                             var is_staff = resp.length > 0;
452                             if (is_staff) {
453                                 egPromptDialog.open(
454                                     egCore.strings.PATRON_PURGE_STAFF_PROMPT,
455                                     null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
456                                     {ok : function(barcode) {_purge_account_with_destination(barcode)}}
457                                 );
458                             } else {
459                                 _purge_account();
460                             }
461                         });
462                     }
463                 });
464             }
465         });
466     }
467
468     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
469     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
470 }])
471
472 .controller('PatronBarcodeSearchCtrl',
473        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc','$uibModal','$q',
474 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc , $uibModal , $q) {
475     $scope.selectMe = true; // focus text input
476     patronSvc.clearPrimary(); // clear the default user
477
478     // jump to the patron checkout UI
479     function loadPatron(user_id) {
480         egCore.audio.play('success.patron.by_barcode');
481         $location
482         .path('/circ/patron/' + user_id + '/checkout')
483         .search('card', $scope.args.barcode);
484         patronSvc.search_barcode = $scope.args.barcode;
485     }
486
487     // create an opt-in=yes response for the loaded user
488     function createOptIn(user_id) {
489         egCore.net.request(
490             'open-ils.actor',
491             'open-ils.actor.user.org_unit_opt_in.create',
492             egCore.auth.token(), user_id).then(function(resp) {
493                 if (evt = egCore.evt.parse(resp)) return alert(evt);
494                 loadPatron(user_id);
495             }
496         );
497     }
498
499     $scope.submitBarcode = function(args) {
500         $scope.bcNotFound = null;
501         $scope.optInRestricted = false;
502         if (!args.barcode) return;
503         args.barcode = args.barcode.replace(/^\s/g,'');
504         args.barcode = args.barcode.replace(/\s$/g,'');
505         // blur so next time it's set to true it will re-apply select()
506         $scope.selectMe = false;
507
508         var user_id;
509
510         // given a scanned barcode, this function finds any matching users
511         // and handles multiple matches due to barcode completion
512         function handleBarcodeCompletion(scanned_barcode) {
513             var deferred = $q.defer();
514
515             egCore.net.request(
516                 'open-ils.actor',
517                 'open-ils.actor.get_barcodes',
518                 egCore.auth.token(), egCore.auth.user().ws_ou(), 
519                 'actor', scanned_barcode)
520
521             .then(function(resp) { // get_barcodes
522
523                 if (evt = egCore.evt.parse(resp)) {
524                     alert(evt); // FIXME
525                     deferred.reject();
526                     return;
527                 }
528
529                 if (!resp || !resp[0]) {
530                     $scope.bcNotFound = args.barcode;
531                     $scope.selectMe = true;
532                     egCore.audio.play('warning.patron.not_found');
533                     deferred.reject();
534                     return;
535                 }
536
537                 if (resp.length == 1) {
538                     // exactly one matching barcode: return it
539                     deferred.resolve();
540                     user_id = resp[0].id;
541                 } else {
542                     // multiple matching barcodes: let the user pick one 
543                     var barcode_map = {};
544                     var matches = [];
545                     var promises = [];
546                     var selected_barcode;
547                     angular.forEach(resp, function(match) {
548                         promises.push(
549                             egUser.get(match.id, {useFields : ['home_ou']}).then(function(user) {
550                                 barcode_map[match.barcode] = user.id();
551                                 matches.push( {
552                                     barcode: match.barcode,
553                                     title: user.first_given_name() + ' ' + user.family_name(),
554                                     org_name: user.home_ou().name(),
555                                     org_shortname: user.home_ou().shortname()
556                                 });
557                             })
558                         );
559                     });
560                     return $q.all(promises)
561                     .then(function() {
562                         $uibModal.open({
563                             templateUrl: './circ/share/t_barcode_choice_dialog',
564                             controller:
565                                 ['$scope', '$uibModalInstance',
566                                 function($scope, $uibModalInstance) {
567                                 $scope.matches = matches;
568                                 $scope.ok = function(barcode) {
569                                     $uibModalInstance.close();
570                                     selected_barcode = barcode;
571                                 }
572                                 $scope.cancel = function() {$uibModalInstance.dismiss()}
573                             }],
574                         }).result.then(function() {
575                             deferred.resolve();
576                             user_id = barcode_map[selected_barcode];
577                         });
578                     });
579                 }
580             });
581             return deferred.promise;
582         }
583
584         // call our function to lookup matching users for the scanned barcode
585         handleBarcodeCompletion(args.barcode).then(function() {
586
587             // see if an opt-in request is needed
588             return egCore.net.request(
589                 'open-ils.actor',
590                 'open-ils.actor.user.org_unit_opt_in.check',
591                 egCore.auth.token(), user_id
592             ).then(function(optInResp) { // opt_in_check
593
594                 if (evt = egCore.evt.parse(optInResp)) {
595                     alert(evt); // FIXME
596                     return;
597                 }
598
599                 if (optInResp == 2) {
600                     // opt-in disallowed at this location by patron's home library
601                     $scope.optInRestricted = true;
602                     $scope.selectMe = true;
603                     egCore.audio.play('warning.patron.opt_in_restricted');
604                     return;
605                 }
606             
607                 if (optInResp == 1) {
608                     // opt-in handled or not needed
609                     return loadPatron(user_id);
610                 }
611
612                 // opt-in needed, show the opt-in dialog
613                 egUser.get(user_id, {useFields : []})
614
615                 .then(function(user) { // retrieve user
616                     var org = egCore.org.get(user.home_ou());
617                     egConfirmDialog.open(
618                         egCore.strings.OPT_IN_DIALOG_TITLE,
619                         egCore.strings.OPT_IN_DIALOG,
620                         {   family_name : user.family_name(),
621                             first_given_name : user.first_given_name(),
622                             org_name : org.name(),
623                             org_shortname : org.shortname(),
624                             ok : function() { createOptIn(user.id()) },
625                             cancel : function() {}
626                         }
627                     );
628                 })
629             })
630         })
631     }
632 }])
633
634
635 /**
636  * Manages patron search
637  */
638 .controller('PatronSearchCtrl',
639        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
640        '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
641        'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
642 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore , ngToast,
643          $filter,  egUser,  patronSvc , egGridDataProvider , $document , bucketSvc,
644         egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
645
646     angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
647     $scope.initTab('search');
648
649     $scope.gridControls = {
650         activateItem : function(item) {
651             $location.path('/circ/patron/' + item.id() + '/checkout');
652         },
653         selectedItems : function() { return [] }
654     }
655
656     $scope.bucketSvc = bucketSvc;
657     $scope.bucketSvc.fetchUserBuckets();
658     $scope.bucketSvc.fetchUserSubscriptions();
659     $scope.addToBucket = function(item, data, recs) {
660         if (recs.length == 0) return;
661         var added_count = 0;
662         var failed_count = 0;
663         var promise = $q.when();
664         angular.forEach(recs,
665             function(rec) {
666                 var item = new egCore.idl.cubi();
667                 item.bucket(data.id());
668                 item.target_user(rec.id());
669                 promise = promise.then(function() {
670                     return egCore.net.request(
671                         'open-ils.actor',
672                         'open-ils.actor.container.item.create',
673                         egCore.auth.token(), 'user', item, 1
674                     );
675                 }).then(
676                     function(){ added_count++ },
677                     function(){ failed_count++ }
678                 );
679             }
680         );
681
682         promise.then( function () {
683             if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
684             if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
685         });
686     }
687
688     var temp_scope = $scope;
689     $scope.openCreateBucketDialog = function() {
690         $uibModal.open({
691             templateUrl: './circ/patron/bucket/t_bucket_create',
692             backdrop: 'static',
693             controller:
694                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
695                 $scope.focusMe = true;
696                 $scope.ok = function(args) { $uibModalInstance.close(args) }
697                 $scope.cancel = function () { $uibModalInstance.dismiss() }
698             }]
699         }).result.then(function (args) {
700             if (!args || !args.name) return;
701             bucketSvc.createBucket(args.name, args.desc).then(
702                 function(id) {
703                     if (id) {
704                         $scope.bucketSvc.fetchBucket(id).then(function (b) {
705                             $scope.addToBucket(
706                                 null,
707                                 b,
708                                 $scope.gridControls.selectedItems()
709                             );
710                             $scope.bucketSvc.fetchUserBuckets(true);
711                         });
712                     }
713                 }
714             );
715         });
716     }
717
718     $scope.$watch(
719         function() {return $scope.gridControls.selectedItems()},
720         function(list) {
721             if (list[0]) 
722                 patronSvc.setPrimary(null, list[0]);
723         },
724         true
725     );
726
727     $scope.need_one_selected = function() {
728         var items = $scope.gridControls.selectedItems();
729         return (items.length > 0) ? false : true;
730     }
731     $scope.need_two_selected = function() {
732         var items = $scope.gridControls.selectedItems();
733         return (items.length == 2) ? false : true;
734     }
735     $scope.merge_patrons = function() {
736         var items = $scope.gridControls.selectedItems();
737         if (items.length != 2) return false;
738
739         var patron_ids = [];
740         angular.forEach(items, function(i) {
741             patron_ids.push(i.id());
742         });
743         egPatronMerge.do_merge(patron_ids).then(
744             function() {
745                 // ensure that we're not drawing from cached
746                 // resuts, as a successful merge just deleted a
747                 // record
748                 delete patronSvc.lastSearch;
749                 $scope.gridControls.refresh();
750             },
751             function(evt) {
752                 if (evt && evt.textcode == 'MERGE_SELF_NOT_ALLOWED') {
753                     ngToast.warning(egCore.strings.MERGE_SELF_NOT_ALLOWED);
754                 }
755             }
756         );
757     }
758    
759 }])
760
761 /**
762  * Manages messages
763  */
764 .controller('PatronMessagesCtrl',
765        ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc','hasPermAt',
766 function($scope , $q , $routeParams,  egCore , $uibModal , patronSvc , egCirc , hasPermAt ) {
767     $scope.initTab('messages', $routeParams.id);
768     var usr_id = $routeParams.id;
769     var org_ids = hasPermAt.VIEW_USER;
770
771     // setup date filters
772     var start = new Date(); // now - 1 year
773     start.setFullYear(start.getFullYear() - 1),
774     $scope.dates = {
775         start_date : start,
776         end_date : new Date()
777     }
778
779     function date_range() {
780         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
781         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
782         var today = new Date().toISOString().replace(/T.*/,'');
783         if (end == today) end = 'now';
784         return [start, end];
785     }
786
787     // grid queries
788    
789     var activeGrid = $scope.activeGridControls = {
790         setSort : function() {
791             return [{'create_date' : 'DESC'}];
792         },
793         setQuery : function() {
794             return {
795                 usr : usr_id,
796                 org_unit : org_ids,
797                 '-or' : [
798                     {stop_date : null},
799                     {stop_date : {'>' : 'now'}}
800                 ]
801             }
802         }
803     }
804
805     var archiveGrid = $scope.archiveGridControls = {
806         setSort : function() {
807             return [{'create_date' : 'DESC'}];
808         },
809         watchQuery : function() {
810             return {
811                 usr : usr_id, 
812                 org_unit : org_ids,
813                 stop_date : {'<=' : 'now'},
814                 create_date : {between : date_range()}
815             };
816         }
817     };
818
819     $scope.test_for_disable_remove_penalty = function() {
820         var selected = $scope.activeGridControls.selectedItems();
821         var found_pub_and_read_and_not_deleted = false;
822         angular.forEach(selected, function(s) {
823             if (Boolean(s.pub == 't') && Boolean(s.read_date) && !Boolean(s.deleted == 't')) {
824                 found_pub_and_read_and_not_deleted = true;
825             }
826         });
827         return found_pub_and_read_and_not_deleted;
828     }
829
830     $scope.removePenalty = function(selected) {
831         if (selected.length == 0) return;
832
833         // TODO: need confirmation dialog
834
835         var promises = [];
836         // figure out the view components
837         var aum_ids = [];
838         var ausp_ids = [];
839         angular.forEach(selected, function(s) {
840             if (s.aum_id) { aum_ids.push(s.aum_id); }
841             if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
842         });
843
844         // fetch all of them since trying to pull them
845         // off of patronSvc.current isn't reliable
846         if (ausp_ids.length > 0) {
847             promises.push(
848                 egCore.pcrud.search('ausp',
849                     {id : ausp_ids}, {},
850                     {atomic : true, authoritative : true}
851                 ).then(function(penalties) {
852                     return egCore.pcrud.remove(penalties);
853                 })
854             );
855         }
856         if (aum_ids.length > 0) {
857             promises.push(
858                 egCore.pcrud.search('aum',
859                     {id : aum_ids}, {},
860                     {atomic : true, authoritative : true}
861                 ).then(function(messages) {
862                     return egCore.pcrud.remove(messages);
863                 })
864             );
865         }
866         $q.all(promises).then(function() {
867             activeGrid.refresh();
868             archiveGrid.refresh();
869             // force a refresh of the user
870             patronSvc.setPrimary(patronSvc.current.id(), null, true);
871         });
872     }
873
874     $scope.archivePenalty = function(selected) {
875         if (selected.length == 0) return;
876
877         // TODO: need confirmation dialog
878
879         var promises = [];
880         // figure out the view components
881         var aum_ids = [];
882         var ausp_ids = [];
883         angular.forEach(selected, function(s) {
884             if (s.aum_id) { aum_ids.push(s.aum_id); }
885             if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
886         });
887
888         // fetch all of them since trying to pull them
889         // off of patronSvc.current isn't reliable
890         if (ausp_ids.length > 0) {
891             promises.push(
892                 egCore.pcrud.search('ausp',
893                     {id : ausp_ids}, {},
894                     {atomic : true, authoritative : true}
895                 ).then(function(penalties) {
896                     angular.forEach(penalties, function(p) {
897                         p.stop_date('now');
898                     });
899                     return egCore.pcrud.update(penalties);
900                 })
901             );
902         }
903         if (aum_ids.length > 0) {
904             promises.push(
905                 egCore.pcrud.search('aum',
906                     {id : aum_ids}, {},
907                     {atomic : true, authoritative : true}
908                 ).then(function(messages) {
909                     angular.forEach(messages, function(m) {
910                         m.stop_date('now');
911                     });
912                     return egCore.pcrud.update(messages);
913                 })
914             );
915         }
916         $q.all(promises).then(function() {
917             activeGrid.refresh();
918             archiveGrid.refresh();
919             // force a refresh of the user
920             patronSvc.setPrimary(patronSvc.current.id(), null, true);
921         });
922     }
923
924     // leverage egEnv for caching
925     function fetchPenaltyTypes() {
926         if (egCore.env.csp) 
927             return $q.when(egCore.env.csp.list);
928         return egCore.pcrud.search(
929             // id <= 100 are reserved for system use
930             'csp', {id : {'>': 100}}, {}, {atomic : true})
931         .then(function(penalties) {
932             egCore.env.absorbList(penalties, 'csp');
933             return penalties;
934         });
935     }
936
937     $scope.createPenalty = function() {
938         egCirc.create_penalty(usr_id).then(function() {
939             activeGrid.refresh();
940             // force a refresh of the user, since they may now
941             // have blocking penalties, etc.
942             patronSvc.setPrimary(patronSvc.current.id(), null, true);
943         });
944     }
945
946     $scope.editPenalty = function(selected) {
947         if (selected.length == 0) return;
948
949         var promises = [];
950         // figure out the view components
951         var aum_ids = []; var aum_objs = {};
952         var ausp_ids = []; var ausp_objs = {};
953         var pairs = [];
954         angular.forEach(selected, function(s) {
955             if (s.aum_id) { aum_ids.push(s.aum_id); }
956             if (s.ausp_id) { ausp_ids.push(s.ausp_id); }
957             pairs.push( { aum_id : s.aum_id, ausp_id : s.ausp_id } );
958         });
959
960         // fetch all of them since trying to pull them
961         // off of patronSvc.current isn't reliable
962         // (we want deleted user messages too)
963         if (ausp_ids.length > 0) {
964             promises.push(
965                 egCore.pcrud.search('ausp',
966                     {id : ausp_ids}, {},
967                     {atomic : true, authoritative : true}
968                 ).then(function(penalties) {
969                     angular.forEach(penalties, function(p) {
970                         ausp_objs[p.id()] = p;
971                     });
972                     return $q.when();
973                 })
974             );
975         }
976         if (aum_ids.length > 0) {
977             promises.push(
978                 egCore.pcrud.search('aum',
979                     {id : aum_ids}, {
980                         flesh : 1,
981                         flesh_fields : {
982                             aum : ['editor']
983                         }
984                     },
985                     {atomic : true, authoritative : true}
986                 ).then(function(messages) {
987                     angular.forEach(messages, function(m) {
988                         aum_objs[m.id()] = m;
989                     });
990                     return $q.when();
991                 })
992             );
993         }
994         $q.all(promises).then(function() {
995             angular.forEach(pairs, function(pair) {
996                 egCirc.edit_penalty(ausp_objs[pair.ausp_id],aum_objs[pair.aum_id]).then(function() {
997                     activeGrid.refresh();
998                     // force a refresh of the user, since they may now
999                     // have blocking penalties, etc.
1000                     patronSvc.setPrimary(patronSvc.current.id(), null, true);
1001                 });
1002             });
1003         });
1004     }
1005 }])
1006
1007
1008 /**
1009  * Credentials tester
1010  */
1011 .controller('PatronVerifyCredentialsCtrl',
1012        ['$scope','$routeParams','$location','egCore',
1013 function($scope,  $routeParams , $location , egCore) {
1014     $scope.verified = null;
1015     $scope.focusMe = true;
1016
1017     // called with a patron, pre-populate the form args
1018     $scope.initTab('other', $routeParams.id).then(
1019         function() {
1020             if ($routeParams.id && $scope.patron()) {
1021                 $scope.prepop = true;
1022                 $scope.username = $scope.patron().usrname();
1023                 $scope.barcode = $scope.patron().card().barcode();
1024             } else {
1025                 $scope.username = '';
1026                 $scope.barcode = '';
1027                 $scope.password = '';
1028             }
1029         }
1030     );
1031
1032     // verify login credentials
1033     $scope.verify = function() {
1034         $scope.verified = null;
1035         $scope.notFound = false;
1036
1037         egCore.net.request(
1038             'open-ils.actor',
1039             'open-ils.actor.verify_user_password',
1040             egCore.auth.token(), $scope.barcode,
1041             $scope.username, hex_md5($scope.password || '')
1042
1043         ).then(function(resp) {
1044             $scope.focusMe = true;
1045             if (evt = egCore.evt.parse(resp)) {
1046                 alert(evt);
1047             } else if (resp == 1) {
1048                 $scope.verified = true;
1049             } else {
1050                 $scope.verified = false;
1051             }
1052         });
1053     }
1054
1055     // load the main patron UI for the provided username or barcode
1056     $scope.load = function($event) {
1057         $scope.notFound = false;
1058         $scope.verified = null;
1059
1060         egCore.net.request(
1061             'open-ils.actor',
1062             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
1063             egCore.auth.token(), $scope.barcode, $scope.username
1064
1065         ).then(function(resp) {
1066
1067             if (Number(resp)) {
1068                 $location.path('/circ/patron/' + resp + '/checkout');
1069                 return;
1070             }
1071
1072             // something went wrong...
1073             $scope.focusMe = true;
1074             if (evt = egCore.evt.parse(resp)) {
1075                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
1076                     $scope.notFound = true;
1077                     return;
1078                 }
1079                 return alert(evt);
1080             } else {
1081                 alert(resp);
1082             }
1083         });
1084
1085         // load() button sits within the verify form.  
1086         // avoid submitting the verify() form action on load()
1087         $event.preventDefault();
1088     }
1089 }])
1090
1091 .controller('PatronAlertsCtrl',
1092        ['$scope','$routeParams','$location','egCore','patronSvc',
1093 function($scope,  $routeParams , $location , egCore , patronSvc) {
1094
1095     $scope.initTab('other', $routeParams.id)
1096     .then(function() {
1097         $scope.patronExpired = patronSvc.patronExpired;
1098         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
1099         $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
1100         $scope.invalidAddresses = patronSvc.invalidAddresses;
1101     });
1102
1103 }])
1104
1105 .controller('HoldSubscriptionsCtrl',
1106        ['$scope','$q','$routeParams','$location','egCore','patronSvc','bucketSvc','egGridDataProvider','egConfirmDialog','$timeout','$window',
1107 function($scope,  $q , $routeParams , $location , egCore , patronSvc,  bucketSvc,  egGridDataProvider,  egConfirmDialog,  $timeout,  $window) {
1108
1109     $scope.initTab('other', $routeParams.id);
1110
1111     $scope.bucket_ids = [];
1112     $scope.bucket_items = [];
1113     $scope.buckets = [];
1114
1115     $scope.gridControls = {
1116         activateItem : function (item) {
1117             var url = $location.absUrl().replace(
1118                 /\/circ\/patron\/.*/, 
1119                 '/cat/bucket/batch_hold/view/' + item.id());
1120             $window.open(url, '_blank').focus();
1121         }
1122     };
1123
1124     $scope.gridDataProvider = egGridDataProvider.instance({
1125         get : function(offset, count) {
1126             return this.arrayNotifier($scope.buckets, offset, count);
1127         }
1128     });
1129
1130     function fetchSubscriptions() {
1131         $scope.bucket_ids = [];
1132         $scope.bucket_items = [];
1133         $scope.buckets = [];
1134         egCore.pcrud.search('cubi',
1135             { target_user : $routeParams.id }
1136         ).then(
1137             function() {
1138                 if ($scope.bucket_ids.length > 0) {
1139                     egCore.pcrud.search('cub',
1140                         { id : $scope.bucket_ids, btype : 'hold_subscription' }
1141                     ).then(
1142                         function() { $scope.gridControls.refresh() },
1143                         null,
1144                         function(b) {
1145                             $scope.buckets.push(b);
1146                             b.items( $scope.bucket_items.filter(i => i.bucket() == b.id()) );
1147                         }
1148                     );
1149                 } else {
1150                     $scope.gridControls.refresh();
1151                 }
1152             },
1153             null,
1154             function(i) {
1155                 $scope.bucket_ids.push(i.bucket());
1156                 $scope.bucket_items.push(i);
1157             }
1158         )
1159     }
1160
1161     $scope.removeSubscriptions = function (buckets) {
1162         return egConfirmDialog.open(
1163             egCore.strings.REMOVE_HOLD_SUBSCRIPTIONS,'',{}
1164         ).result.then(function() {
1165             var promises = [];
1166
1167             angular.forEach(buckets, function(b) {
1168                 angular.forEach(b.items(), function (i) {
1169                     promises.push(bucketSvc.detachUser(i.id()));
1170                 })
1171             });
1172
1173             $q.all(promises).then(fetchSubscriptions);
1174         });
1175     }
1176
1177     $timeout(fetchSubscriptions);
1178
1179 }])
1180
1181 .controller('PatronGroupCtrl',
1182        ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
1183         'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
1184 function($scope,  $routeParams , $q , $window , $timeout,  $location , egCore ,
1185          patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
1186
1187     var usr_id = $routeParams.id;
1188
1189     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
1190
1191     var grid = $scope.gridControls = {
1192         activateItem : function(item) {
1193             $location.path('/circ/patron/' + item.id + '/checkout');
1194         },
1195         itemRetrieved : function(item) {
1196
1197             if (item.id == patronSvc.current.id()) {
1198                 item.stats = patronSvc.patron_stats;
1199
1200             } else {
1201                 // flesh stats for other group members
1202                 patronSvc.getUserStats(item.id).then(function(stats) {
1203                     item.stats = stats;
1204                     $scope.totals.total_out += stats.checkouts.total_out; 
1205                     $scope.totals.overdue += stats.checkouts.overdue; 
1206                 });
1207             }
1208         },
1209         setSort : function() {
1210             return ['create_date'];
1211         },
1212         watchQuery: function() {
1213             if (patronSvc.current) {
1214                 return {
1215                     usrgroup : patronSvc.current.usrgroup(),
1216                     deleted : 'f'
1217                 };
1218             }
1219             return null;
1220         }
1221     }
1222
1223     $scope.initTab('other', $routeParams.id)
1224     .then(function(redirect) {
1225         // if we are redirecting to the alerts page, avoid updating the
1226         // grid query.
1227         if (redirect) return;
1228         // let initTab() fetch the user first so we can know the usrgroup
1229         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1230     });
1231
1232     $scope.removeFromGroup = function(selected) {
1233         var promises = [];
1234         angular.forEach(selected, function(user) {
1235             console.debug('removing user ' + user.id + ' from group');
1236
1237             promises.push(
1238                 egCore.net.request(
1239                     'open-ils.actor',
1240                     'open-ils.actor.usergroup.new',
1241                     egCore.auth.token(), user.id, true
1242                 )
1243             );
1244         });
1245
1246         $q.all(promises).then(function() {grid.refresh()});
1247     }
1248
1249     function addUserToGroup(user) {
1250         user.usrgroup(patronSvc.current.usrgroup());
1251         user.ischanged(true);
1252         egCore.net.request(
1253             'open-ils.actor',
1254             'open-ils.actor.patron.update',
1255             egCore.auth.token(), user
1256
1257         ).then(function() {grid.refresh()});
1258     }
1259
1260     // fetch each user ("selected" has flattened users)
1261     // update the usrgroup, then update the user object
1262     // After all updates are complete, refresh the grid.
1263     function moveUsersToGroup(target_user, selected) {
1264         var promises = [];
1265
1266         angular.forEach(selected, function(user) {
1267             promises.push(
1268                 egCore.pcrud.retrieve('au', user.id)
1269                 .then(function(u) {
1270                     u.usrgroup(target_user.usrgroup());
1271                     u.ischanged(true);
1272                     return egCore.net.request(
1273                         'open-ils.actor',
1274                         'open-ils.actor.patron.update',
1275                         egCore.auth.token(), u
1276                     );
1277                 })
1278             );
1279         });
1280
1281         $q.all(promises).then(function() {grid.refresh()});
1282     }
1283
1284     function showMoveToGroupConfirm(barcode, selected, outbound) {
1285
1286         // find the user
1287         egCore.pcrud.search('ac', {barcode : barcode})
1288
1289         // fetch the fleshed user
1290         .then(function(card) {
1291
1292             if (!card) return; // TODO: warn user
1293
1294             egCore.pcrud.retrieve('au', card.usr())
1295             .then(function(user) {
1296                 user.card(card);
1297                 $uibModal.open({
1298                     templateUrl: './circ/patron/t_move_to_group_dialog',
1299                     backdrop: 'static',
1300                     controller: [
1301                                 '$scope','$uibModalInstance',
1302                         function($scope , $uibModalInstance) {
1303                             $scope.user = user;
1304                             $scope.selected = selected;
1305                             $scope.outbound = outbound;
1306                             $scope.ok = 
1307                                 function(count) { $uibModalInstance.close() }
1308                             $scope.cancel = 
1309                                 function () { $uibModalInstance.dismiss() }
1310                         }
1311                     ]
1312                 }).result.then(function() {
1313                     if (outbound) {
1314                         moveUsersToGroup(user, selected);
1315                     } else {
1316                         addUserToGroup(user);
1317                     }
1318                 });
1319             });
1320         });
1321     }
1322
1323     // selected == move selected patrons to another patron's group
1324     // !selected == patron from a different group moves into our group
1325     function moveToGroup(selected, outbound) {
1326         egPromptDialog.open(
1327             egCore.strings.GROUP_ADD_USER, '',
1328             {ok : function(value) {
1329                 if (value) 
1330                     showMoveToGroupConfirm(value, selected, outbound);
1331             }}
1332         );
1333     }
1334
1335     $scope.moveToGroup = function() { moveToGroup([], false) };
1336     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1337
1338     $scope.cloneUser = function(selected) {
1339         if (!selected.length) return;
1340         var url = $location.absUrl().replace(
1341             /\/patron\/.*/, 
1342             '/patron/register/clone/' + selected[0].id);
1343         $window.open(url, '_blank').focus();
1344     }
1345
1346     $scope.retrieveSelected = function(selected) {
1347         if (!selected.length) return;
1348         angular.forEach(selected, function(usr) {
1349             $timeout(function() {
1350                 var url = $location.absUrl().replace(
1351                     /\/patron\/.*/,
1352                     '/patron/' + usr.id + '/checkout');
1353                 $window.open(url, '_blank')
1354             });
1355         });
1356     }
1357
1358 }])
1359
1360 .controller('PatronStatCatsCtrl',
1361        ['$scope','$routeParams','$q','egCore','patronSvc',
1362 function($scope,  $routeParams , $q , egCore , patronSvc) {
1363     $scope.initTab('other', $routeParams.id)
1364     .then(function(redirect) {
1365         // Entries for org-visible stat cats are fleshed.  Any others
1366         // have to be fleshed within.
1367
1368         var to_flesh = {};
1369         angular.forEach(patronSvc.current.stat_cat_entries(), 
1370             function(entry) {
1371                 if (!angular.isObject(entry.stat_cat())) {
1372                     to_flesh[entry.stat_cat()] = entry;
1373                 }
1374             }
1375         );
1376
1377         if (!Object.keys(to_flesh).length) return;
1378
1379         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1380         .then(null, null, function(cat) { // stream
1381             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1382             to_flesh[cat.id()].stat_cat(cat);
1383         });
1384     });
1385 }])
1386
1387 .controller('PatronSurveyCtrl',
1388        ['$scope','$routeParams','$location','egCore','patronSvc',
1389 function($scope,  $routeParams , $location , egCore , patronSvc) {
1390     $scope.initTab('other', $routeParams.id);
1391     var usr_id = $routeParams.id;
1392     var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1393
1394     $scope.surveys = [];
1395     var svr_responses = {};
1396
1397     // fetch all survey responses for this user.
1398     egCore.pcrud.search('asvr',
1399         {usr : usr_id},
1400         {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1401     ).then(
1402         function() {
1403             // All responses collected and deduplicated.
1404             // Create one collection of responses per survey.
1405
1406             angular.forEach(svr_responses, function(questions, survey_id) {
1407                 var collection = {responses : []};
1408                 angular.forEach(questions, function(response) {
1409                     collection.survey = response.survey(); // same for one.
1410                     collection.responses.push(response);
1411                 });
1412                 $scope.surveys.push(collection);
1413             });
1414         },
1415         null, 
1416         function(response) {
1417
1418             // Discard responses for out-of-scope surveys.
1419             if (org_ids.indexOf(response.survey().owner()) < 0) 
1420                 return;
1421
1422             // survey_id => question_id => response
1423             var svr_id = response.survey().id();
1424             var qst_id = response.question().id();
1425
1426             if (!svr_responses[svr_id]) 
1427                 svr_responses[svr_id] = [];
1428
1429             if (!svr_responses[svr_id][qst_id]) {
1430                 svr_responses[svr_id][qst_id] = response;
1431
1432             } else {
1433                 // We have multiple responses for the same question.
1434                 // For this UI we only care about the most recent response.
1435                 if (response.effective_date() > 
1436                     svr_responses[svr_id][qst_id].effective_date())
1437                     svr_responses[svr_id][qst_id] = response;
1438             }
1439         }
1440     );
1441 }])
1442
1443 .controller('PatronFetchLastCtrl',
1444        ['$scope','$location','egCore',
1445 function($scope , $location , egCore) {
1446
1447     var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1448     if (ids.length) 
1449         return $location.path('/circ/patron/' + ids[0] + '/checkout');
1450
1451     $scope.no_last = true;
1452 }])
1453
1454 .controller('PatronTriggeredEventsCtrl',
1455        ['$scope','$routeParams','$location','egCore','patronSvc',
1456 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1457     $scope.initTab('other', $routeParams.id);
1458
1459     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1460     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1461
1462     $scope.triggered_events_url = url;
1463     $scope.funcs = {};
1464 }])
1465
1466 .controller('PatronMessageCenterCtrl',
1467        ['$scope','$routeParams','$location','egCore','patronSvc',
1468 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1469     $scope.initTab('other', $routeParams.id);
1470
1471     var url = $location.protocol() + '://' + $location.host()
1472         + egCore.env.basePath.replace(/\/staff.*/,  '/actor/user/message');
1473     url += '/' + encodeURIComponent($routeParams.id);
1474
1475     $scope.message_center_url = url;
1476     $scope.funcs = {};
1477 }])
1478
1479 .controller('PatronPermsCtrl',
1480        ['$scope','$routeParams','$window','$location','egCore',
1481 function($scope , $routeParams , $window , $location , egCore) {
1482     $scope.initTab('other', $routeParams.id);
1483
1484     var url = $location.absUrl().replace(
1485         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1486
1487     url += '?usr=' + encodeURIComponent($routeParams.id);
1488
1489     // user_edit does not load the session via cookie.  It uses URL 
1490     // params or xulG instead.  Pass via xulG.
1491     $scope.funcs = {
1492         ses : egCore.auth.token(),
1493         on_patron_save : function() {
1494             $scope.funcs.reload();
1495         }
1496     }
1497
1498     $scope.user_perms_url = url;
1499 }])
1500