]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/circ/patron/app.js
LP#1712637 Patron edit hold pickup location repairs
[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 .config(function($routeProvider, $locationProvider, $compileProvider) {
19     $locationProvider.html5Mode(true);
20     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|blob):/); // grid export
21
22     // data loaded at startup which only requires an authtoken goes
23     // here. this allows the requests to be run in parallel instead of
24     // waiting until startup has completed.
25     var resolver = {delay : ['egCore','egUser', function(egCore , egUser) {
26
27         // fetch the org settings we care about during egStartup
28         // and toss them into egCore.env as egCore.env.aous[name] = value.
29         // note: only load settings here needed by all tabs; load tab-
30         // specific settings from within their respective controllers
31         egCore.env.classLoaders.aous = function() {
32             return egCore.org.settings([
33                 'ui.staff.require_initials.patron_info_notes',
34                 'circ.do_not_tally_claims_returned',
35                 'circ.tally_lost',
36                 'circ.obscure_dob',
37                 'ui.circ.show_billing_tab_on_bills',
38                 'circ.patron_expires_soon_warning',
39                 'ui.circ.items_out.lost',
40                 'ui.circ.items_out.longoverdue',
41                 'ui.circ.items_out.claimsreturned'
42             ]).then(function(settings) { 
43                 // local settings are cached within egOrg.  Caching them
44                 // again in egEnv just simplifies the syntax for access.
45                 egCore.env.aous = settings;
46             });
47         }
48
49         egCore.env.loadClasses.push('aous');
50
51         // app-globally modify the default flesh fields for 
52         // fleshed user retrieval.
53         if (egUser.defaultFleshFields.indexOf('profile') == -1) {
54             egUser.defaultFleshFields = egUser.defaultFleshFields.concat([
55                 'profile',
56                 'net_access_level',
57                 'ident_type',
58                 'ident_type2',
59                 'cards',
60                 'groups'
61             ]);
62         }
63
64         return egCore.startup.go().then(function() {
65
66             // This call requires orgs to be loaded, because it
67             // calls egCore.org.ancestors(), so call it after startup
68             return egCore.pcrud.search('actsc', 
69                 {owner : egCore.org.ancestors(
70                     egCore.auth.user().ws_ou(), true)},
71                 {}, {atomic : true}
72             ).then(function(cats) {
73                 egCore.env.absorbList(cats, 'actsc');
74             });
75         });
76     }]};
77
78     $routeProvider.when('/circ/patron/search', {
79         templateUrl: './circ/patron/t_search',
80         controller: 'PatronSearchCtrl',
81         resolve : resolver
82     });
83
84     $routeProvider.when('/circ/patron/bcsearch', {
85         templateUrl: './circ/patron/t_bcsearch',
86         controller: 'PatronBarcodeSearchCtrl',
87         resolve : resolver
88     });
89
90     $routeProvider.when('/circ/patron/credentials', {
91         templateUrl: './circ/patron/t_credentials',
92         controller: 'PatronVerifyCredentialsCtrl',
93         resolve : resolver
94     });
95
96     $routeProvider.when('/circ/patron/last', {
97         templateUrl: './circ/patron/t_last_patron',
98         controller: 'PatronFetchLastCtrl',
99         resolve : resolver
100     });
101
102     // the following require a patron ID
103
104     $routeProvider.when('/circ/patron/:id/alerts', {
105         templateUrl: './circ/patron/t_alerts',
106         controller: 'PatronAlertsCtrl',
107         resolve : resolver
108     });
109
110     $routeProvider.when('/circ/patron/:id/checkout', {
111         templateUrl: './circ/patron/t_checkout',
112         controller: 'PatronCheckoutCtrl',
113         resolve : resolver
114     });
115
116     $routeProvider.when('/circ/patron/:id/items_out', {
117         templateUrl: './circ/patron/t_items_out',
118         controller: 'PatronItemsOutCtrl',
119         resolve : resolver
120     });
121
122     $routeProvider.when('/circ/patron/:id/holds', {
123         templateUrl: './circ/patron/t_holds',
124         controller: 'PatronHoldsCtrl',
125         resolve : resolver
126     });
127
128     $routeProvider.when('/circ/patron/:id/holds/create', {
129         templateUrl: './circ/patron/t_holds_create',
130         controller: 'PatronHoldsCreateCtrl',
131         resolve : resolver
132     });
133
134     $routeProvider.when('/circ/patron/:id/holds/:hold_id', {
135         templateUrl: './circ/patron/t_holds',
136         controller: 'PatronHoldsCtrl',
137         resolve : resolver
138     });
139
140     $routeProvider.when('/circ/patron/:id/hold/:hold_id', {
141         templateUrl: './circ/patron/t_hold_details',
142         controller: 'PatronHoldDetailsCtrl',
143         resolve : resolver
144     });
145
146     $routeProvider.when('/circ/patron/:id/bills', {
147         templateUrl: './circ/patron/t_bills',
148         controller: 'PatronBillsCtrl',
149         resolve : resolver
150     });
151
152     $routeProvider.when('/circ/patron/:id/bill/:xact_id', {
153         templateUrl: './circ/patron/t_xact_details',
154         controller: 'XactDetailsCtrl',
155         resolve : resolver
156     });
157
158     $routeProvider.when('/circ/patron/:id/bill_history/:history_tab', {
159         templateUrl: './circ/patron/t_bill_history',
160         controller: 'BillHistoryCtrl',
161         resolve : resolver
162     });
163
164     $routeProvider.when('/circ/patron/:id/messages', {
165         templateUrl: './circ/patron/t_messages',
166         controller: 'PatronMessagesCtrl',
167         resolve : resolver
168     });
169
170     $routeProvider.when('/circ/patron/:id/edit', {
171         templateUrl: './circ/patron/t_edit',
172         controller: 'PatronRegCtrl',
173         resolve : resolver
174     });
175
176     $routeProvider.when('/circ/patron/:id/credentials', {
177         templateUrl: './circ/patron/t_credentials',
178         controller: 'PatronVerifyCredentialsCtrl',
179         resolve : resolver
180     });
181
182     $routeProvider.when('/circ/patron/:id/notes', {
183         templateUrl: './circ/patron/t_notes',
184         controller: 'PatronNotesCtrl',
185         resolve : resolver
186     });
187
188     $routeProvider.when('/circ/patron/:id/triggered_events', {
189         templateUrl: './circ/patron/t_triggered_events',
190         controller: 'PatronTriggeredEventsCtrl',
191         resolve : resolver
192     });
193
194     $routeProvider.when('/circ/patron/:id/message_center', {
195         templateUrl: './circ/patron/t_message_center',
196         controller: 'PatronMessageCenterCtrl',
197         resolve : resolver
198     });
199
200     $routeProvider.when('/circ/patron/:id/edit_perms', {
201         templateUrl: './circ/patron/t_edit_perms',
202         controller: 'PatronPermsCtrl',
203         resolve : resolver
204     });
205
206     $routeProvider.when('/circ/patron/:id/group', {
207         templateUrl: './circ/patron/t_group',
208         controller: 'PatronGroupCtrl',
209         resolve : resolver
210     });
211
212     $routeProvider.when('/circ/patron/:id/stat_cats', {
213         templateUrl: './circ/patron/t_stat_cats',
214         controller: 'PatronStatCatsCtrl',
215         resolve : resolver
216     });
217
218     $routeProvider.when('/circ/patron/:id/surveys', {
219         templateUrl: './circ/patron/t_surveys',
220         controller: 'PatronSurveyCtrl',
221         resolve : resolver
222     });
223
224     $routeProvider.otherwise({redirectTo : '/circ/patron/search'});
225 })
226
227 /**
228  * Manages tabbed patron view.
229  * This is the parent scope of all patron tab scopes.
230  *
231  * */
232 .controller('PatronCtrl',
233        ['$scope','$q','$location','$filter','egCore','egNet','egUser','egAlertDialog','egConfirmDialog','egPromptDialog','patronSvc',
234 function($scope,  $q , $location , $filter , egCore , egNet , egUser , egAlertDialog , egConfirmDialog , egPromptDialog , patronSvc) {
235
236     $scope.is_patron_edit = function() {
237         return Boolean($location.path().match(/patron\/\d+\/edit$/));
238     }
239
240     // To support the fixed position patron edit actions bar,
241     // its markup has to live outside the scope of the patron 
242     // edit controller.  Insert a scope blob here that can be
243     // modifed from within the patron edit controller.
244     $scope.edit_passthru = {};
245
246     // returns true if a redirect occurs
247     function redirectToAlertPanel() {
248
249         $scope.alert_penalties = 
250             function() {return patronSvc.alert_penalties}
251
252         if (patronSvc.alertsShown()) return false;
253
254         // if the patron has any unshown alerts, show them now
255         if (patronSvc.hasAlerts && 
256             !$location.path().match(/alerts$/)) {
257
258             $location
259                 .path('/circ/patron/' + patronSvc.current.id() + '/alerts')
260                 .search('card', null);
261             return true;
262         }
263
264         // no alert required.  If the patron has fines and the show-bills
265         // OUS is applied, direct to the bills page.
266         if ($scope.patron_stats().fines.balance_owed > 0 // TODO: != 0 ?
267             && egCore.env.aous['ui.circ.show_billing_tab_on_bills']
268             && !$location.path().match(/bills$/)) {
269
270             $scope.tab = 'bills';
271             $location
272                 .path('/circ/patron/' + patronSvc.current.id() + '/bills')
273                 .search('card', null);
274
275             return true;
276         }
277
278         return false;
279     }
280
281     // called after each route-specified controller is instantiated.
282     // this doubles as a way to inform the top-level controller that
283     // egStartup.go() has completed, which means we are clear to 
284     // fetch the patron, etc.
285     $scope.initTab = function(tab, patron_id) {
286         console.log('init tab ' + tab);
287         $scope.tab = tab;
288         $scope.aous = egCore.env.aous;
289         $scope.auth_user_id = egCore.auth.user().id();
290
291         if (patron_id) {
292             $scope.patron_id = patron_id;
293             return patronSvc.setPrimary($scope.patron_id)
294             .then(function() {return patronSvc.checkAlerts()})
295             .then(redirectToAlertPanel);
296         }
297         return $q.when();
298     }
299
300     $scope._show_dob = {};
301     $scope.show_dob = function (val) {
302         if ($scope.patron()) {
303             if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
304             return $scope._show_dob[$scope.patron().id()];
305         }
306         return !egCore.env.aous['circ.obscure_dob'];
307     }
308         
309     $scope.obscure_dob = function() { 
310         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
311     }
312     $scope.now_show_dob = function() { 
313         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
314             $scope.show_dob() : true; 
315     }
316
317     $scope.patron = function() { return patronSvc.current }
318     $scope.patron_stats = function() { return patronSvc.patron_stats }
319     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
320     $scope.hasAlerts = function() { return patronSvc.hasAlerts }
321     $scope.isPatronExpired = function() { return patronSvc.patronExpired }
322
323     $scope.print_address = function(addr) {
324         egCore.print.print({
325             context : 'default', 
326             template : 'patron_address', 
327             scope : {
328                 patron : egCore.idl.toHash(patronSvc.current),
329                 address : egCore.idl.toHash(addr)
330             }
331         });
332     }
333
334     $scope.toggle_expand_summary = function() {
335         if ($scope.collapsePatronSummary) {
336             $scope.collapsePatronSummary = false;
337             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
338         } else {
339             $scope.collapsePatronSummary = true;
340             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
341         }
342     }
343     
344     // always expand the patron summary in the search UI, regardless
345     // of stored preference.
346     $scope.collapse_summary = function() {
347         return $scope.tab != 'search' && $scope.collapsePatronSummary;
348     }
349
350     function _purge_account(dest_usr,override) {
351         egNet.request(
352             'open-ils.actor',
353             'open-ils.actor.user.delete' + (override ? '.override' : ''),
354             egCore.auth.token(),
355             $scope.patron().id(),
356             dest_usr
357         ).then(function(resp){
358             if (evt = egCore.evt.parse(resp)) {
359                 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
360                     egConfirmDialog.open(
361                         egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
362                         {ok : function() {
363                             _purge_account(dest_usr,true);
364                         }}
365                     );
366                 } else {
367                     alert(js2JSON(evt));
368                 }
369             } else {
370                 location.href = egCore.env.basePath + '/circ/patron/search';
371             }
372         });
373     }
374
375     function _purge_account_with_destination(dest_barcode) {
376         egCore.pcrud.search('ac', {barcode : dest_barcode})
377         .then(function(card) {
378             if (!card) {
379                 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
380             } else {
381                 _purge_account(card.usr());
382             }
383         });
384     }
385
386     $scope.purge_account = function() {
387         egConfirmDialog.open(
388             egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
389             {ok : function() {
390                 egConfirmDialog.open(
391                     egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
392                     {ok : function() {
393                         egNet.request(
394                             'open-ils.actor',
395                             'open-ils.actor.user.has_work_perm_at',
396                             egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
397                         ).then(function(resp) {
398                             var is_staff = resp.length > 0;
399                             if (is_staff) {
400                                 egPromptDialog.open(
401                                     egCore.strings.PATRON_PURGE_STAFF_PROMPT,
402                                     null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
403                                     {ok : function(barcode) {_purge_account_with_destination(barcode)}}
404                                 );
405                             } else {
406                                 _purge_account();
407                             }
408                         });
409                     }
410                 });
411             }
412         });
413     }
414
415     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
416     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
417 }])
418
419 .controller('PatronBarcodeSearchCtrl',
420        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
421 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
422     $scope.selectMe = true; // focus text input
423     patronSvc.clearPrimary(); // clear the default user
424
425     // jump to the patron checkout UI
426     function loadPatron(user_id) {
427         egCore.audio.play('success.patron.by_barcode');
428         $location
429         .path('/circ/patron/' + user_id + '/checkout')
430         .search('card', $scope.args.barcode);
431         patronSvc.search_barcode = $scope.args.barcode;
432     }
433
434     // create an opt-in=yes response for the loaded user
435     function createOptIn(user_id) {
436         egCore.net.request(
437             'open-ils.actor',
438             'open-ils.actor.user.org_unit_opt_in.create',
439             egCore.auth.token(), user_id).then(function(resp) {
440                 if (evt = egCore.evt.parse(resp)) return alert(evt);
441                 loadPatron(user_id);
442             }
443         );
444     }
445
446     $scope.submitBarcode = function(args) {
447         $scope.bcNotFound = null;
448         $scope.optInRestricted = false;
449         if (!args.barcode) return;
450         args.barcode = args.barcode.replace(/\s/g,'');
451         // blur so next time it's set to true it will re-apply select()
452         $scope.selectMe = false;
453
454         var user_id;
455
456         // lookup barcode
457         egCore.net.request(
458             'open-ils.actor',
459             'open-ils.actor.get_barcodes',
460             egCore.auth.token(), egCore.auth.user().ws_ou(), 
461             'actor', args.barcode)
462
463         .then(function(resp) { // get_barcodes
464
465             if (evt = egCore.evt.parse(resp)) {
466                 alert(evt); // FIXME
467                 return;
468             }
469
470             if (!resp || !resp[0]) {
471                 $scope.bcNotFound = args.barcode;
472                 $scope.selectMe = true;
473                 egCore.audio.play('warning.patron.not_found');
474                 return;
475             }
476
477             // see if an opt-in request is needed
478             user_id = resp[0].id;
479             return egCore.net.request(
480                 'open-ils.actor',
481                 'open-ils.actor.user.org_unit_opt_in.check',
482                 egCore.auth.token(), user_id);
483
484         }).then(function(optInResp) { // opt_in_check
485
486             if (evt = egCore.evt.parse(optInResp)) {
487                 alert(evt); // FIXME
488                 return;
489             }
490
491             if (optInResp == 2) {
492                 // opt-in disallowed at this location by patron's home library
493                 $scope.optInRestricted = true;
494                 $scope.selectMe = true;
495                 egCore.audio.play('warning.patron.opt_in_restricted');
496                 return;
497             }
498            
499             if (optInResp == 1) {
500                 // opt-in handled or not needed
501                 return loadPatron(user_id);
502             }
503
504             // opt-in needed, show the opt-in dialog
505             egUser.get(user_id, {useFields : []})
506
507             .then(function(user) { // retrieve user
508                 var org = egCore.org.get(user.home_ou());
509                 egConfirmDialog.open(
510                     egCore.strings.OPT_IN_DIALOG_TITLE,
511                     egCore.strings.OPT_IN_DIALOG,
512                     {   family_name : user.family_name(),
513                         first_given_name : user.first_given_name(),
514                         org_name : org.name(),
515                         org_shortname : org.shortname(),
516                         ok : function() { createOptIn(user.id()) },
517                         cancel : function() {}
518                     }
519                 );
520             })
521         });
522     }
523 }])
524
525
526 /**
527  * Manages patron search
528  */
529 .controller('PatronSearchCtrl',
530        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
531        '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
532        'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
533 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore , ngToast,
534          $filter,  egUser,  patronSvc , egGridDataProvider , $document , bucketSvc,
535         egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
536
537     angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
538     $scope.initTab('search');
539
540     $scope.gridControls = {
541         activateItem : function(item) {
542             $location.path('/circ/patron/' + item.id() + '/checkout');
543         },
544         selectedItems : function() { return [] }
545     }
546
547     $scope.bucketSvc = bucketSvc;
548     $scope.bucketSvc.fetchUserBuckets();
549     $scope.addToBucket = function(item, data, recs) {
550         if (recs.length == 0) return;
551         var added_count = 0;
552         var failed_count = 0;
553         var p = [];
554         angular.forEach(recs,
555             function(rec) {
556                 var item = new egCore.idl.cubi();
557                 item.bucket(data.id());
558                 item.target_user(rec.id());
559                 p.push(egCore.net.request(
560                     'open-ils.actor',
561                     'open-ils.actor.container.item.create',
562                     egCore.auth.token(), 'user', item
563                 ).then(
564                     function(){ added_count++ },
565                     function(){ failed_count++ }
566                 ));
567             }
568         );
569
570         $q.all(p).then( function () {
571             if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
572             if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
573         });
574     }
575
576     var temp_scope = $scope;
577     $scope.openCreateBucketDialog = function() {
578         $uibModal.open({
579             templateUrl: './circ/patron/bucket/t_bucket_create',
580             controller:
581                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
582                 $scope.focusMe = true;
583                 $scope.ok = function(args) { $uibModalInstance.close(args) }
584                 $scope.cancel = function () { $uibModalInstance.dismiss() }
585             }]
586         }).result.then(function (args) {
587             if (!args || !args.name) return;
588             bucketSvc.createBucket(args.name, args.desc).then(
589                 function(id) {
590                     if (id) {
591                         $scope.bucketSvc.fetchBucket(id).then(function (b) {
592                             $scope.addToBucket(
593                                 null,
594                                 b,
595                                 $scope.gridControls.selectedItems()
596                             );
597                             $scope.bucketSvc.fetchUserBuckets(true);
598                         });
599                     }
600                 }
601             );
602         });
603     }
604
605     $scope.$watch(
606         function() {return $scope.gridControls.selectedItems()},
607         function(list) {
608             if (list[0]) 
609                 patronSvc.setPrimary(null, list[0]);
610         },
611         true
612     );
613
614     $scope.need_one_selected = function() {
615         var items = $scope.gridControls.selectedItems();
616         return (items.length > 0) ? false : true;
617     }
618     $scope.need_two_selected = function() {
619         var items = $scope.gridControls.selectedItems();
620         return (items.length == 2) ? false : true;
621     }
622     $scope.merge_patrons = function() {
623         var items = $scope.gridControls.selectedItems();
624         if (items.length != 2) return false;
625
626         var patron_ids = [];
627         angular.forEach(items, function(i) {
628             patron_ids.push(i.id());
629         });
630         egPatronMerge.do_merge(patron_ids).then(function() {
631             // ensure that we're not drawing from cached
632             // resuts, as a successful merge just deleted a
633             // record
634             delete patronSvc.lastSearch;
635             $scope.gridControls.refresh();
636         });
637     }
638    
639 }])
640
641 /**
642  * Manages messages
643  */
644 .controller('PatronMessagesCtrl',
645        ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
646 function($scope , $q , $routeParams,  egCore , $uibModal , patronSvc , egCirc) {
647     $scope.initTab('messages', $routeParams.id);
648     var usr_id = $routeParams.id;
649
650     // setup date filters
651     var start = new Date(); // now - 1 year
652     start.setFullYear(start.getFullYear() - 1),
653     $scope.dates = {
654         start_date : start,
655         end_date : new Date()
656     }
657
658     function date_range() {
659         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
660         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
661         var today = new Date().toISOString().replace(/T.*/,'');
662         if (end == today) end = 'now';
663         return [start, end];
664     }
665
666     // grid queries
667    
668     var activeGrid = $scope.activeGridControls = {
669         setSort : function() {
670             return ['set_date'];
671         },
672         setQuery : function() {
673             return {
674                 usr : usr_id,
675                 '-or' : [
676                     {stop_date : null},
677                     {stop_date : {'>' : 'now'}}
678                 ]
679             }
680         }
681     }
682
683     var archiveGrid = $scope.archiveGridControls = {
684         setSort : function() {
685             return ['set_date'];
686         },
687         setQuery : function() {
688             return {
689                 usr : usr_id, 
690                 stop_date : {'<=' : 'now'},
691                 set_date : {between : date_range()}
692             };
693         }
694     };
695
696     $scope.removePenalty = function(selected) {
697         // the grid stores flattened penalties.  Fetch penalty objects first
698
699         var ids = selected.map(function(s){ return s.id });
700         egCore.pcrud.search('ausp', 
701             {id : ids}, {}, 
702             {atomic : true, authoritative : true}
703
704         // then delete them
705         ).then(function(penalties) {
706             return egCore.pcrud.remove(penalties);
707
708         // then refresh the grid
709         }).then(function() {
710             activeGrid.refresh();
711         });
712     }
713
714     $scope.archivePenalty = function(selected) {
715         // the grid stores flattened penalties.  Fetch penalty objects first
716
717         var ids = selected.map(function(s){ return s.id });
718         egCore.pcrud.search('ausp', 
719             {id : ids}, {}, 
720             {atomic : true, authoritative : true}
721
722         // then delete them
723         ).then(function(penalties) {
724             angular.forEach(penalties, function(p){ p.stop_date('now') });
725             return egCore.pcrud.update(penalties);
726
727         // then refresh the grid
728         }).then(function() {
729             activeGrid.refresh();
730             archiveGrid.refresh();
731         });
732     }
733
734     // leverage egEnv for caching
735     function fetchPenaltyTypes() {
736         if (egCore.env.csp) 
737             return $q.when(egCore.env.csp.list);
738         return egCore.pcrud.search(
739             // id <= 100 are reserved for system use
740             'csp', {id : {'>': 100}}, {}, {atomic : true})
741         .then(function(penalties) {
742             egCore.env.absorbList(penalties, 'csp');
743             return penalties;
744         });
745     }
746
747     $scope.createPenalty = function() {
748         egCirc.create_penalty(usr_id).then(function() {
749             activeGrid.refresh();
750             // force a refresh of the user, since they may now
751             // have blocking penalties, etc.
752             patronSvc.setPrimary(patronSvc.current.id(), null, true);
753         });
754     }
755
756     $scope.editPenalty = function(selected) {
757         if (selected.length == 0) return;
758
759         // grab the penalty from the user object
760         var penalty = patronSvc.current.standing_penalties().filter(
761             function(p) {return p.id() == selected[0].id})[0];
762
763         egCirc.edit_penalty(penalty).then(function() {
764             activeGrid.refresh();
765             // force a refresh of the user, since they may now
766             // have blocking penalties, etc.
767             patronSvc.setPrimary(patronSvc.current.id(), null, true);
768         });
769     }
770 }])
771
772
773 /**
774  * Credentials tester
775  */
776 .controller('PatronVerifyCredentialsCtrl',
777        ['$scope','$routeParams','$location','egCore',
778 function($scope,  $routeParams , $location , egCore) {
779     $scope.verified = null;
780     $scope.focusMe = true;
781
782     // called with a patron, pre-populate the form args
783     $scope.initTab('other', $routeParams.id).then(
784         function() {
785             if ($routeParams.id && $scope.patron()) {
786                 $scope.prepop = true;
787                 $scope.username = $scope.patron().usrname();
788                 $scope.barcode = $scope.patron().card().barcode();
789             } else {
790                 $scope.username = '';
791                 $scope.barcode = '';
792                 $scope.password = '';
793             }
794         }
795     );
796
797     // verify login credentials
798     $scope.verify = function() {
799         $scope.verified = null;
800         $scope.notFound = false;
801
802         egCore.net.request(
803             'open-ils.actor',
804             'open-ils.actor.verify_user_password',
805             egCore.auth.token(), $scope.barcode,
806             $scope.username, hex_md5($scope.password || '')
807
808         ).then(function(resp) {
809             $scope.focusMe = true;
810             if (evt = egCore.evt.parse(resp)) {
811                 alert(evt);
812             } else if (resp == 1) {
813                 $scope.verified = true;
814             } else {
815                 $scope.verified = false;
816             }
817         });
818     }
819
820     // load the main patron UI for the provided username or barcode
821     $scope.load = function($event) {
822         $scope.notFound = false;
823         $scope.verified = null;
824
825         egCore.net.request(
826             'open-ils.actor',
827             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
828             egCore.auth.token(), $scope.barcode, $scope.username
829
830         ).then(function(resp) {
831
832             if (Number(resp)) {
833                 $location.path('/circ/patron/' + resp + '/checkout');
834                 return;
835             }
836
837             // something went wrong...
838             $scope.focusMe = true;
839             if (evt = egCore.evt.parse(resp)) {
840                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
841                     $scope.notFound = true;
842                     return;
843                 }
844                 return alert(evt);
845             } else {
846                 alert(resp);
847             }
848         });
849
850         // load() button sits within the verify form.  
851         // avoid submitting the verify() form action on load()
852         $event.preventDefault();
853     }
854 }])
855
856 .controller('PatronAlertsCtrl',
857        ['$scope','$routeParams','$location','egCore','patronSvc',
858 function($scope,  $routeParams , $location , egCore , patronSvc) {
859
860     $scope.initTab('other', $routeParams.id)
861     .then(function() {
862         $scope.patronExpired = patronSvc.patronExpired;
863         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
864         $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
865         $scope.invalidAddresses = patronSvc.invalidAddresses;
866     });
867
868 }])
869
870 .controller('PatronNotesCtrl',
871        ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
872         'egConfirmDialog',
873 function($scope,  $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
874          egConfirmDialog) {
875     $scope.initTab('other', $routeParams.id);
876     var usr_id = $routeParams.id;
877
878     // fetch the notes
879     function refreshPage() {
880         $scope.notes = [];
881         egCore.pcrud.search('aun', 
882             {usr : usr_id}, 
883             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
884             {authoritative : true})
885         .then(null, null, function(note) {
886             $scope.notes.push(note);
887         });
888     }
889
890     // open the new-note dialog and create the note
891     $scope.newNote = function() {
892         $uibModal.open({
893             templateUrl: './circ/patron/t_new_note_dialog',
894             controller: 
895                 ['$scope', '$uibModalInstance',
896             function($scope, $uibModalInstance) {
897                 $scope.focusNote = true;
898                 $scope.args = {};
899                 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
900                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
901                 $scope.cancel = function () { $uibModalInstance.dismiss() }
902             }],
903         }).result.then(
904             function(args) {
905                 if (!args.value) return;
906                 var note = new egCore.idl.aun();
907                 note.usr(usr_id);
908                 note.title(args.title);
909                 note.value(args.value);
910                 note.pub(args.pub ? 't' : 'f');
911                 note.creator(egCore.auth.user().id());
912                 if (args.initials) 
913                     note.value(note.value() + ' [' + args.initials + ']');
914                 egCore.pcrud.create(note).then(function() {refreshPage()});
915             }
916         );
917     }
918
919     // delete the selected note
920     $scope.deleteNote = function(note) {
921         egConfirmDialog.open(
922             egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
923             {ok : function() {
924                 egCore.pcrud.remove(note).then(function() {refreshPage()});
925             },
926             note_title : note.title(),
927             create_date : note.create_date()
928         });
929     }
930
931     // print the selected note
932     $scope.printNote = function(note) {
933         var hash = egCore.idl.toHash(note);
934         hash.usr = egCore.idl.toHash($scope.patron());
935         egCore.print.print({
936             context : 'default', 
937             template : 'patron_note', 
938             scope : {note : hash}
939         });
940     }
941
942     // perform the initial note fetch
943     refreshPage();
944 }])
945
946 .controller('PatronGroupCtrl',
947        ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
948         'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
949 function($scope,  $routeParams , $q , $window , $timeout,  $location , egCore ,
950          patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
951
952     var usr_id = $routeParams.id;
953
954     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
955
956     var grid = $scope.gridControls = {
957         activateItem : function(item) {
958             $location.path('/circ/patron/' + item.id + '/checkout');
959         },
960         itemRetrieved : function(item) {
961
962             if (item.id == patronSvc.current.id()) {
963                 item.stats = patronSvc.patron_stats;
964
965             } else {
966                 // flesh stats for other group members
967                 patronSvc.getUserStats(item.id).then(function(stats) {
968                     item.stats = stats;
969                     $scope.totals.total_out += stats.checkouts.total_out; 
970                     $scope.totals.overdue += stats.checkouts.overdue; 
971                 });
972             }
973         },
974         setSort : function() {
975             return ['create_date'];
976         }
977     }
978
979     $scope.initTab('other', $routeParams.id)
980     .then(function(redirect) {
981         // if we are redirecting to the alerts page, avoid updating the
982         // grid query.
983         if (redirect) return;
984         // let initTab() fetch the user first so we can know the usrgroup
985
986         grid.setQuery({
987             usrgroup : patronSvc.current.usrgroup(),
988             deleted : 'f'
989         });
990         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
991     });
992
993     $scope.removeFromGroup = function(selected) {
994         var promises = [];
995         angular.forEach(selected, function(user) {
996             console.debug('removing user ' + user.id + ' from group');
997
998             promises.push(
999                 egCore.net.request(
1000                     'open-ils.actor',
1001                     'open-ils.actor.usergroup.new',
1002                     egCore.auth.token(), user.id, true
1003                 )
1004             );
1005         });
1006
1007         $q.all(promises).then(function() {grid.refresh()});
1008     }
1009
1010     function addUserToGroup(user) {
1011         user.usrgroup(patronSvc.current.usrgroup());
1012         user.ischanged(true);
1013         egCore.net.request(
1014             'open-ils.actor',
1015             'open-ils.actor.patron.update',
1016             egCore.auth.token(), user
1017
1018         ).then(function() {grid.refresh()});
1019     }
1020
1021     // fetch each user ("selected" has flattened users)
1022     // update the usrgroup, then update the user object
1023     // After all updates are complete, refresh the grid.
1024     function moveUsersToGroup(target_user, selected) {
1025         var promises = [];
1026
1027         angular.forEach(selected, function(user) {
1028             promises.push(
1029                 egCore.pcrud.retrieve('au', user.id)
1030                 .then(function(u) {
1031                     u.usrgroup(target_user.usrgroup());
1032                     u.ischanged(true);
1033                     return egCore.net.request(
1034                         'open-ils.actor',
1035                         'open-ils.actor.patron.update',
1036                         egCore.auth.token(), u
1037                     );
1038                 })
1039             );
1040         });
1041
1042         $q.all(promises).then(function() {grid.refresh()});
1043     }
1044
1045     function showMoveToGroupConfirm(barcode, selected, outbound) {
1046
1047         // find the user
1048         egCore.pcrud.search('ac', {barcode : barcode})
1049
1050         // fetch the fleshed user
1051         .then(function(card) {
1052
1053             if (!card) return; // TODO: warn user
1054
1055             egCore.pcrud.retrieve('au', card.usr())
1056             .then(function(user) {
1057                 user.card(card);
1058                 $uibModal.open({
1059                     templateUrl: './circ/patron/t_move_to_group_dialog',
1060                     controller: [
1061                                 '$scope','$uibModalInstance',
1062                         function($scope , $uibModalInstance) {
1063                             $scope.user = user;
1064                             $scope.selected = selected;
1065                             $scope.outbound = outbound;
1066                             $scope.ok = 
1067                                 function(count) { $uibModalInstance.close() }
1068                             $scope.cancel = 
1069                                 function () { $uibModalInstance.dismiss() }
1070                         }
1071                     ]
1072                 }).result.then(function() {
1073                     if (outbound) {
1074                         moveUsersToGroup(user, selected);
1075                     } else {
1076                         addUserToGroup(user);
1077                     }
1078                 });
1079             });
1080         });
1081     }
1082
1083     // selected == move selected patrons to another patron's group
1084     // !selected == patron from a different group moves into our group
1085     function moveToGroup(selected, outbound) {
1086         egPromptDialog.open(
1087             egCore.strings.GROUP_ADD_USER, '',
1088             {ok : function(value) {
1089                 if (value) 
1090                     showMoveToGroupConfirm(value, selected, outbound);
1091             }}
1092         );
1093     }
1094
1095     $scope.moveToGroup = function() { moveToGroup([], false) };
1096     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1097
1098     $scope.cloneUser = function(selected) {
1099         if (!selected.length) return;
1100         var url = $location.absUrl().replace(
1101             /\/patron\/.*/, 
1102             '/patron/register/clone/' + selected[0].id);
1103         $window.open(url, '_blank').focus();
1104     }
1105
1106     $scope.retrieveSelected = function(selected) {
1107         if (!selected.length) return;
1108         angular.forEach(selected, function(usr) {
1109             $timeout(function() {
1110                 var url = $location.absUrl().replace(
1111                     /\/patron\/.*/,
1112                     '/patron/' + usr.id + '/checkout');
1113                 $window.open(url, '_blank')
1114             });
1115         });
1116     }
1117
1118 }])
1119
1120 .controller('PatronStatCatsCtrl',
1121        ['$scope','$routeParams','$q','egCore','patronSvc',
1122 function($scope,  $routeParams , $q , egCore , patronSvc) {
1123     $scope.initTab('other', $routeParams.id)
1124     .then(function(redirect) {
1125         // Entries for org-visible stat cats are fleshed.  Any others
1126         // have to be fleshed within.
1127
1128         var to_flesh = {};
1129         angular.forEach(patronSvc.current.stat_cat_entries(), 
1130             function(entry) {
1131                 if (!angular.isObject(entry.stat_cat())) {
1132                     to_flesh[entry.stat_cat()] = entry;
1133                 }
1134             }
1135         );
1136
1137         if (!Object.keys(to_flesh).length) return;
1138
1139         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1140         .then(null, null, function(cat) { // stream
1141             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1142             to_flesh[cat.id()].stat_cat(cat);
1143         });
1144     });
1145 }])
1146
1147 .controller('PatronSurveyCtrl',
1148        ['$scope','$routeParams','$location','egCore','patronSvc',
1149 function($scope,  $routeParams , $location , egCore , patronSvc) {
1150     $scope.initTab('other', $routeParams.id);
1151     var usr_id = $routeParams.id;
1152     var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1153     $scope.surveys = [];
1154     // fetch the surveys
1155     egCore.pcrud.search('asvr',
1156         {usr : usr_id},
1157         {flesh : 4, flesh_fields : {
1158             asvr : ['question', 'survey', 'answer'],
1159             asv : ['responses', 'questions'],
1160             asvq : ['responses', 'question']
1161     }},
1162         {authoritative : true})
1163     .then(null, null, function(survey) {
1164         var sameSurveyId = false;
1165         if (survey.survey().id() && $scope.surveys.length > 0) {
1166             for (sid = 0; sid < $scope.surveys.length; sid++) {
1167                 if (survey.survey().id() == $scope.surveys[sid].id()) sameSurveyId = true; 
1168             }
1169         }
1170         if (!sameSurveyId) $scope.surveys.push(survey.survey());
1171     });
1172 }])
1173
1174 .controller('PatronFetchLastCtrl',
1175        ['$scope','$location','egCore',
1176 function($scope , $location , egCore) {
1177
1178     var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1179     if (ids.length) 
1180         return $location.path('/circ/patron/' + ids[0] + '/checkout');
1181
1182     $scope.no_last = true;
1183 }])
1184
1185 .controller('PatronTriggeredEventsCtrl',
1186        ['$scope','$routeParams','$location','egCore','patronSvc',
1187 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1188     $scope.initTab('other', $routeParams.id);
1189
1190     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1191     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1192
1193     $scope.triggered_events_url = url;
1194     $scope.funcs = {};
1195 }])
1196
1197 .controller('PatronMessageCenterCtrl',
1198        ['$scope','$routeParams','$location','egCore','patronSvc',
1199 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1200     $scope.initTab('other', $routeParams.id);
1201
1202     var url = $location.protocol() + '://' + $location.host()
1203         + egCore.env.basePath.replace(/\/staff.*/,  '/actor/user/message');
1204     url += '/' + encodeURIComponent($routeParams.id);
1205
1206     $scope.message_center_url = url;
1207     $scope.funcs = {};
1208 }])
1209
1210 .controller('PatronPermsCtrl',
1211        ['$scope','$routeParams','$window','$location','egCore',
1212 function($scope , $routeParams , $window , $location , egCore) {
1213     $scope.initTab('other', $routeParams.id);
1214
1215     var url = $location.absUrl().replace(
1216         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1217
1218     url += '?usr=' + encodeURIComponent($routeParams.id);
1219
1220     // user_edit does not load the session via cookie.  It uses URL 
1221     // params or xulG instead.  Pass via xulG.
1222     $scope.funcs = {
1223         ses : egCore.auth.token(),
1224         on_patron_save : function() {
1225             $scope.funcs.reload();
1226         }
1227     }
1228
1229     $scope.user_perms_url = url;
1230 }])
1231