f92eac10961ee0ed7bb572df46adf46de8c7f1e6
[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() {
295                 // the page title context label comes from the tab.
296                 egCore.strings.setPageTitle(
297                     egCore.strings.PAGE_TITLE_PATRON_NAME, 
298                     egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()],
299                     {   lname : patronSvc.current.family_name(),
300                         fname : patronSvc.current.first_given_name(),
301                         mname : patronSvc.current.second_given_name()
302                     }
303                 );
304             })
305             .then(function() {return patronSvc.checkAlerts()})
306             .then(redirectToAlertPanel)
307             .then(function(){
308                 $scope.ident_type_name = $scope.patron().ident_type().name()
309                 $scope.hasIdentTypeName = $scope.ident_type_name.length > 0;
310             });
311         } else {
312             // No patron, use the tab name as the page title.
313             egCore.strings.setPageTitle(
314                 egCore.strings['PAGE_TITLE_PATRON_' + tab.toUpperCase()]);
315         }
316         return $q.when();
317     }
318
319     $scope._show_dob = {};
320     $scope.show_dob = function (val) {
321         if ($scope.patron()) {
322             if (typeof val != 'undefined') $scope._show_dob[$scope.patron().id()] = val;
323             return $scope._show_dob[$scope.patron().id()];
324         }
325         return !egCore.env.aous['circ.obscure_dob'];
326     }
327         
328     $scope.obscure_dob = function() { 
329         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'];
330     }
331     $scope.now_show_dob = function() { 
332         return egCore.env.aous && egCore.env.aous['circ.obscure_dob'] ?
333             $scope.show_dob() : true; 
334     }
335
336     $scope.patron = function() { return patronSvc.current }
337     $scope.patron_stats = function() { return patronSvc.patron_stats }
338     $scope.summary_stat_cats = function() { return patronSvc.summary_stat_cats }
339     $scope.hasAlerts = function() { return patronSvc.hasAlerts }
340     $scope.isPatronExpired = function() { return patronSvc.patronExpired }
341
342     $scope.print_address = function(addr) {
343         egCore.print.print({
344             context : 'default', 
345             template : 'patron_address', 
346             scope : {
347                 patron : egCore.idl.toHash(patronSvc.current),
348                 address : egCore.idl.toHash(addr)
349             }
350         });
351     }
352
353     $scope.toggle_expand_summary = function() {
354         if ($scope.collapsePatronSummary) {
355             $scope.collapsePatronSummary = false;
356             egCore.hatch.removeItem('eg.circ.patron.summary.collapse');
357         } else {
358             $scope.collapsePatronSummary = true;
359             egCore.hatch.setItem('eg.circ.patron.summary.collapse', true);
360         }
361     }
362     
363     // always expand the patron summary in the search UI, regardless
364     // of stored preference.
365     $scope.collapse_summary = function() {
366         return $scope.tab != 'search' && $scope.collapsePatronSummary;
367     }
368
369     function _purge_account(dest_usr,override) {
370         egNet.request(
371             'open-ils.actor',
372             'open-ils.actor.user.delete' + (override ? '.override' : ''),
373             egCore.auth.token(),
374             $scope.patron().id(),
375             dest_usr
376         ).then(function(resp){
377             if (evt = egCore.evt.parse(resp)) {
378                 if (evt.code == '2004' /* ACTOR_USER_DELETE_OPEN_XACTS */) {
379                     egConfirmDialog.open(
380                         egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_OVERRIDE_PROMPT,
381                         {ok : function() {
382                             _purge_account(dest_usr,true);
383                         }}
384                     );
385                 } else {
386                     alert(js2JSON(evt));
387                 }
388             } else {
389                 location.href = egCore.env.basePath + '/circ/patron/search';
390             }
391         });
392     }
393
394     function _purge_account_with_destination(dest_barcode) {
395         egCore.pcrud.search('ac', {barcode : dest_barcode})
396         .then(function(card) {
397             if (!card) {
398                 egAlertDialog.open(egCore.strings.PATRON_PURGE_STAFF_BAD_BARCODE);
399             } else {
400                 _purge_account(card.usr());
401             }
402         });
403     }
404
405     $scope.purge_account = function() {
406         egConfirmDialog.open(
407             egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_CONFIRM,
408             {ok : function() {
409                 egConfirmDialog.open(
410                     egCore.strings.PATRON_PURGE_CONFIRM_TITLE, egCore.strings.PATRON_PURGE_LAST_CHANCE,
411                     {ok : function() {
412                         egNet.request(
413                             'open-ils.actor',
414                             'open-ils.actor.user.has_work_perm_at',
415                             egCore.auth.token(), 'STAFF_LOGIN', $scope.patron().id()
416                         ).then(function(resp) {
417                             var is_staff = resp.length > 0;
418                             if (is_staff) {
419                                 egPromptDialog.open(
420                                     egCore.strings.PATRON_PURGE_STAFF_PROMPT,
421                                     null, // TODO: this would be cool if it worked: egCore.auth.user().card().barcode(),
422                                     {ok : function(barcode) {_purge_account_with_destination(barcode)}}
423                                 );
424                             } else {
425                                 _purge_account();
426                             }
427                         });
428                     }
429                 });
430             }
431         });
432     }
433
434     egCore.hatch.getItem('eg.circ.patron.summary.collapse')
435     .then(function(val) {$scope.collapsePatronSummary = Boolean(val)});
436 }])
437
438 .controller('PatronBarcodeSearchCtrl',
439        ['$scope','$location','egCore','egConfirmDialog','egUser','patronSvc',
440 function($scope , $location , egCore , egConfirmDialog , egUser , patronSvc) {
441     $scope.selectMe = true; // focus text input
442     patronSvc.clearPrimary(); // clear the default user
443
444     // jump to the patron checkout UI
445     function loadPatron(user_id) {
446         egCore.audio.play('success.patron.by_barcode');
447         $location
448         .path('/circ/patron/' + user_id + '/checkout')
449         .search('card', $scope.args.barcode);
450         patronSvc.search_barcode = $scope.args.barcode;
451     }
452
453     // create an opt-in=yes response for the loaded user
454     function createOptIn(user_id) {
455         egCore.net.request(
456             'open-ils.actor',
457             'open-ils.actor.user.org_unit_opt_in.create',
458             egCore.auth.token(), user_id).then(function(resp) {
459                 if (evt = egCore.evt.parse(resp)) return alert(evt);
460                 loadPatron(user_id);
461             }
462         );
463     }
464
465     $scope.submitBarcode = function(args) {
466         $scope.bcNotFound = null;
467         $scope.optInRestricted = false;
468         if (!args.barcode) return;
469         args.barcode = args.barcode.replace(/\s/g,'');
470         // blur so next time it's set to true it will re-apply select()
471         $scope.selectMe = false;
472
473         var user_id;
474
475         // lookup barcode
476         egCore.net.request(
477             'open-ils.actor',
478             'open-ils.actor.get_barcodes',
479             egCore.auth.token(), egCore.auth.user().ws_ou(), 
480             'actor', args.barcode)
481
482         .then(function(resp) { // get_barcodes
483
484             if (evt = egCore.evt.parse(resp)) {
485                 alert(evt); // FIXME
486                 return;
487             }
488
489             if (!resp || !resp[0]) {
490                 $scope.bcNotFound = args.barcode;
491                 $scope.selectMe = true;
492                 egCore.audio.play('warning.patron.not_found');
493                 return;
494             }
495
496             // see if an opt-in request is needed
497             user_id = resp[0].id;
498             return egCore.net.request(
499                 'open-ils.actor',
500                 'open-ils.actor.user.org_unit_opt_in.check',
501                 egCore.auth.token(), user_id);
502
503         }).then(function(optInResp) { // opt_in_check
504
505             if (evt = egCore.evt.parse(optInResp)) {
506                 alert(evt); // FIXME
507                 return;
508             }
509
510             if (optInResp == 2) {
511                 // opt-in disallowed at this location by patron's home library
512                 $scope.optInRestricted = true;
513                 $scope.selectMe = true;
514                 egCore.audio.play('warning.patron.opt_in_restricted');
515                 return;
516             }
517            
518             if (optInResp == 1) {
519                 // opt-in handled or not needed
520                 return loadPatron(user_id);
521             }
522
523             // opt-in needed, show the opt-in dialog
524             egUser.get(user_id, {useFields : []})
525
526             .then(function(user) { // retrieve user
527                 var org = egCore.org.get(user.home_ou());
528                 egConfirmDialog.open(
529                     egCore.strings.OPT_IN_DIALOG_TITLE,
530                     egCore.strings.OPT_IN_DIALOG,
531                     {   family_name : user.family_name(),
532                         first_given_name : user.first_given_name(),
533                         org_name : org.name(),
534                         org_shortname : org.shortname(),
535                         ok : function() { createOptIn(user.id()) },
536                         cancel : function() {}
537                     }
538                 );
539             })
540         });
541     }
542 }])
543
544
545 /**
546  * Manages patron search
547  */
548 .controller('PatronSearchCtrl',
549        ['$scope','$q','$routeParams','$timeout','$window','$location','egCore','ngToast',
550        '$filter','egUser', 'patronSvc','egGridDataProvider','$document','bucketSvc',
551        'egPatronMerge','egProgressDialog','$controller','$interpolate','$uibModal',
552 function($scope,  $q,  $routeParams,  $timeout,  $window,  $location,  egCore , ngToast,
553          $filter,  egUser,  patronSvc , egGridDataProvider , $document , bucketSvc,
554         egPatronMerge , egProgressDialog , $controller , $interpolate , $uibModal) {
555
556     angular.extend(this, $controller('BasePatronSearchCtrl', {$scope : $scope}));
557     $scope.initTab('search');
558
559     $scope.gridControls = {
560         activateItem : function(item) {
561             $location.path('/circ/patron/' + item.id() + '/checkout');
562         },
563         selectedItems : function() { return [] }
564     }
565
566     $scope.bucketSvc = bucketSvc;
567     $scope.bucketSvc.fetchUserBuckets();
568     $scope.addToBucket = function(item, data, recs) {
569         if (recs.length == 0) return;
570         var added_count = 0;
571         var failed_count = 0;
572         var p = [];
573         angular.forEach(recs,
574             function(rec) {
575                 var item = new egCore.idl.cubi();
576                 item.bucket(data.id());
577                 item.target_user(rec.id());
578                 p.push(egCore.net.request(
579                     'open-ils.actor',
580                     'open-ils.actor.container.item.create',
581                     egCore.auth.token(), 'user', item
582                 ).then(
583                     function(){ added_count++ },
584                     function(){ failed_count++ }
585                 ));
586             }
587         );
588
589         $q.all(p).then( function () {
590             if (added_count) ngToast.create($interpolate(egCore.strings.BUCKET_ADD_SUCCESS)({ count: ''+added_count, name: data.name()} ));
591             if (failed_count) ngToast.warning($interpolate(egCore.strings.BUCKET_ADD_FAIL)({ count: ''+failed_count, name: data.name() } ));
592         });
593     }
594
595     var temp_scope = $scope;
596     $scope.openCreateBucketDialog = function() {
597         $uibModal.open({
598             templateUrl: './circ/patron/bucket/t_bucket_create',
599             backdrop: 'static',
600             controller:
601                 ['$scope', '$uibModalInstance', function($scope, $uibModalInstance) {
602                 $scope.focusMe = true;
603                 $scope.ok = function(args) { $uibModalInstance.close(args) }
604                 $scope.cancel = function () { $uibModalInstance.dismiss() }
605             }]
606         }).result.then(function (args) {
607             if (!args || !args.name) return;
608             bucketSvc.createBucket(args.name, args.desc).then(
609                 function(id) {
610                     if (id) {
611                         $scope.bucketSvc.fetchBucket(id).then(function (b) {
612                             $scope.addToBucket(
613                                 null,
614                                 b,
615                                 $scope.gridControls.selectedItems()
616                             );
617                             $scope.bucketSvc.fetchUserBuckets(true);
618                         });
619                     }
620                 }
621             );
622         });
623     }
624
625     $scope.$watch(
626         function() {return $scope.gridControls.selectedItems()},
627         function(list) {
628             if (list[0]) 
629                 patronSvc.setPrimary(null, list[0]);
630         },
631         true
632     );
633
634     $scope.need_one_selected = function() {
635         var items = $scope.gridControls.selectedItems();
636         return (items.length > 0) ? false : true;
637     }
638     $scope.need_two_selected = function() {
639         var items = $scope.gridControls.selectedItems();
640         return (items.length == 2) ? false : true;
641     }
642     $scope.merge_patrons = function() {
643         var items = $scope.gridControls.selectedItems();
644         if (items.length != 2) return false;
645
646         var patron_ids = [];
647         angular.forEach(items, function(i) {
648             patron_ids.push(i.id());
649         });
650         egPatronMerge.do_merge(patron_ids).then(function() {
651             // ensure that we're not drawing from cached
652             // resuts, as a successful merge just deleted a
653             // record
654             delete patronSvc.lastSearch;
655             $scope.gridControls.refresh();
656         });
657     }
658    
659 }])
660
661 /**
662  * Manages messages
663  */
664 .controller('PatronMessagesCtrl',
665        ['$scope','$q','$routeParams','egCore','$uibModal','patronSvc','egCirc',
666 function($scope , $q , $routeParams,  egCore , $uibModal , patronSvc , egCirc) {
667     $scope.initTab('messages', $routeParams.id);
668     var usr_id = $routeParams.id;
669
670     // setup date filters
671     var start = new Date(); // now - 1 year
672     start.setFullYear(start.getFullYear() - 1),
673     $scope.dates = {
674         start_date : start,
675         end_date : new Date()
676     }
677
678     function date_range() {
679         var start = $scope.dates.start_date.toISOString().replace(/T.*/,'');
680         var end = $scope.dates.end_date.toISOString().replace(/T.*/,'');
681         var today = new Date().toISOString().replace(/T.*/,'');
682         if (end == today) end = 'now';
683         return [start, end];
684     }
685
686     // grid queries
687    
688     var activeGrid = $scope.activeGridControls = {
689         setSort : function() {
690             return ['set_date'];
691         },
692         setQuery : function() {
693             return {
694                 usr : usr_id,
695                 '-or' : [
696                     {stop_date : null},
697                     {stop_date : {'>' : 'now'}}
698                 ]
699             }
700         }
701     }
702
703     var archiveGrid = $scope.archiveGridControls = {
704         setSort : function() {
705             return ['set_date'];
706         },
707         setQuery : function() {
708             return {
709                 usr : usr_id, 
710                 stop_date : {'<=' : 'now'},
711                 set_date : {between : date_range()}
712             };
713         }
714     };
715
716     $scope.removePenalty = function(selected) {
717         // the grid stores flattened penalties.  Fetch penalty objects first
718
719         var ids = selected.map(function(s){ return s.id });
720         egCore.pcrud.search('ausp', 
721             {id : ids}, {}, 
722             {atomic : true, authoritative : true}
723
724         // then delete them
725         ).then(function(penalties) {
726             return egCore.pcrud.remove(penalties);
727
728         // then refresh the grid
729         }).then(function() {
730             activeGrid.refresh();
731         });
732     }
733
734     $scope.archivePenalty = function(selected) {
735         // the grid stores flattened penalties.  Fetch penalty objects first
736
737         var ids = selected.map(function(s){ return s.id });
738         egCore.pcrud.search('ausp', 
739             {id : ids}, {}, 
740             {atomic : true, authoritative : true}
741
742         // then delete them
743         ).then(function(penalties) {
744             angular.forEach(penalties, function(p){ p.stop_date('now') });
745             return egCore.pcrud.update(penalties);
746
747         // then refresh the grid
748         }).then(function() {
749             activeGrid.refresh();
750             archiveGrid.refresh();
751         });
752     }
753
754     // leverage egEnv for caching
755     function fetchPenaltyTypes() {
756         if (egCore.env.csp) 
757             return $q.when(egCore.env.csp.list);
758         return egCore.pcrud.search(
759             // id <= 100 are reserved for system use
760             'csp', {id : {'>': 100}}, {}, {atomic : true})
761         .then(function(penalties) {
762             egCore.env.absorbList(penalties, 'csp');
763             return penalties;
764         });
765     }
766
767     $scope.createPenalty = function() {
768         egCirc.create_penalty(usr_id).then(function() {
769             activeGrid.refresh();
770             // force a refresh of the user, since they may now
771             // have blocking penalties, etc.
772             patronSvc.setPrimary(patronSvc.current.id(), null, true);
773         });
774     }
775
776     $scope.editPenalty = function(selected) {
777         if (selected.length == 0) return;
778
779         // grab the penalty from the user object
780         var penalty = patronSvc.current.standing_penalties().filter(
781             function(p) {return p.id() == selected[0].id})[0];
782
783         egCirc.edit_penalty(penalty).then(function() {
784             activeGrid.refresh();
785             // force a refresh of the user, since they may now
786             // have blocking penalties, etc.
787             patronSvc.setPrimary(patronSvc.current.id(), null, true);
788         });
789     }
790 }])
791
792
793 /**
794  * Credentials tester
795  */
796 .controller('PatronVerifyCredentialsCtrl',
797        ['$scope','$routeParams','$location','egCore',
798 function($scope,  $routeParams , $location , egCore) {
799     $scope.verified = null;
800     $scope.focusMe = true;
801
802     // called with a patron, pre-populate the form args
803     $scope.initTab('other', $routeParams.id).then(
804         function() {
805             if ($routeParams.id && $scope.patron()) {
806                 $scope.prepop = true;
807                 $scope.username = $scope.patron().usrname();
808                 $scope.barcode = $scope.patron().card().barcode();
809             } else {
810                 $scope.username = '';
811                 $scope.barcode = '';
812                 $scope.password = '';
813             }
814         }
815     );
816
817     // verify login credentials
818     $scope.verify = function() {
819         $scope.verified = null;
820         $scope.notFound = false;
821
822         egCore.net.request(
823             'open-ils.actor',
824             'open-ils.actor.verify_user_password',
825             egCore.auth.token(), $scope.barcode,
826             $scope.username, hex_md5($scope.password || '')
827
828         ).then(function(resp) {
829             $scope.focusMe = true;
830             if (evt = egCore.evt.parse(resp)) {
831                 alert(evt);
832             } else if (resp == 1) {
833                 $scope.verified = true;
834             } else {
835                 $scope.verified = false;
836             }
837         });
838     }
839
840     // load the main patron UI for the provided username or barcode
841     $scope.load = function($event) {
842         $scope.notFound = false;
843         $scope.verified = null;
844
845         egCore.net.request(
846             'open-ils.actor',
847             'open-ils.actor.user.retrieve_id_by_barcode_or_username',
848             egCore.auth.token(), $scope.barcode, $scope.username
849
850         ).then(function(resp) {
851
852             if (Number(resp)) {
853                 $location.path('/circ/patron/' + resp + '/checkout');
854                 return;
855             }
856
857             // something went wrong...
858             $scope.focusMe = true;
859             if (evt = egCore.evt.parse(resp)) {
860                 if (evt.textcode == 'ACTOR_USR_NOT_FOUND') {
861                     $scope.notFound = true;
862                     return;
863                 }
864                 return alert(evt);
865             } else {
866                 alert(resp);
867             }
868         });
869
870         // load() button sits within the verify form.  
871         // avoid submitting the verify() form action on load()
872         $event.preventDefault();
873     }
874 }])
875
876 .controller('PatronAlertsCtrl',
877        ['$scope','$routeParams','$location','egCore','patronSvc',
878 function($scope,  $routeParams , $location , egCore , patronSvc) {
879
880     $scope.initTab('other', $routeParams.id)
881     .then(function() {
882         $scope.patronExpired = patronSvc.patronExpired;
883         $scope.patronExpiresSoon = patronSvc.patronExpiresSoon;
884         $scope.retrievedWithInactive = patronSvc.fetchedWithInactiveCard();
885         $scope.invalidAddresses = patronSvc.invalidAddresses;
886     });
887
888 }])
889
890 .controller('PatronNotesCtrl',
891        ['$scope','$filter','$routeParams','$location','egCore','patronSvc','$uibModal',
892         'egConfirmDialog',
893 function($scope,  $filter , $routeParams , $location , egCore , patronSvc , $uibModal,
894          egConfirmDialog) {
895     $scope.initTab('other', $routeParams.id);
896     var usr_id = $routeParams.id;
897
898     // fetch the notes
899     function refreshPage() {
900         $scope.notes = [];
901         egCore.pcrud.search('aun', 
902             {usr : usr_id}, 
903             {flesh : 1, flesh_fields : {aun : ['creator']}}, 
904             {authoritative : true})
905         .then(null, null, function(note) {
906             $scope.notes.push(note);
907         });
908     }
909
910     // open the new-note dialog and create the note
911     $scope.newNote = function() {
912         $uibModal.open({
913             templateUrl: './circ/patron/t_new_note_dialog',
914             backdrop: 'static',
915             controller: 
916                 ['$scope', '$uibModalInstance',
917             function($scope, $uibModalInstance) {
918                 $scope.focusNote = true;
919                 $scope.args = {};
920                 $scope.require_initials = egCore.env.aous['ui.staff.require_initials.patron_info_notes'];
921                 $scope.ok = function(count) { $uibModalInstance.close($scope.args) }
922                 $scope.cancel = function () { $uibModalInstance.dismiss() }
923             }],
924         }).result.then(
925             function(args) {
926                 if (!args.value) return;
927                 var note = new egCore.idl.aun();
928                 note.usr(usr_id);
929                 note.title(args.title);
930                 note.value(args.value);
931                 note.pub(args.pub ? 't' : 'f');
932                 note.creator(egCore.auth.user().id());
933                 if (args.initials) 
934                     note.value(note.value() + ' [' + args.initials + ']');
935                 egCore.pcrud.create(note).then(function() {refreshPage()});
936             }
937         );
938     }
939
940     // delete the selected note
941     $scope.deleteNote = function(note) {
942         egConfirmDialog.open(
943             egCore.strings.PATRON_NOTE_DELETE_CONFIRM_TITLE, egCore.strings.PATRON_NOTE_DELETE_CONFIRM,
944             {ok : function() {
945                 egCore.pcrud.remove(note).then(function() {refreshPage()});
946             },
947             note_title : note.title(),
948             create_date : note.create_date()
949         });
950     }
951
952     // print the selected note
953     $scope.printNote = function(note) {
954         var hash = egCore.idl.toHash(note);
955         hash.usr = egCore.idl.toHash($scope.patron());
956         egCore.print.print({
957             context : 'default', 
958             template : 'patron_note', 
959             scope : {note : hash}
960         });
961     }
962
963     // perform the initial note fetch
964     refreshPage();
965 }])
966
967 .controller('PatronGroupCtrl',
968        ['$scope','$routeParams','$q','$window','$timeout','$location','egCore',
969         'patronSvc','$uibModal','egPromptDialog','egConfirmDialog',
970 function($scope,  $routeParams , $q , $window , $timeout,  $location , egCore ,
971          patronSvc , $uibModal , egPromptDialog , egConfirmDialog) {
972
973     var usr_id = $routeParams.id;
974
975     $scope.totals = {owed : 0, total_out : 0, overdue : 0}
976
977     var grid = $scope.gridControls = {
978         activateItem : function(item) {
979             $location.path('/circ/patron/' + item.id + '/checkout');
980         },
981         itemRetrieved : function(item) {
982
983             if (item.id == patronSvc.current.id()) {
984                 item.stats = patronSvc.patron_stats;
985
986             } else {
987                 // flesh stats for other group members
988                 patronSvc.getUserStats(item.id).then(function(stats) {
989                     item.stats = stats;
990                     $scope.totals.total_out += stats.checkouts.total_out; 
991                     $scope.totals.overdue += stats.checkouts.overdue; 
992                 });
993             }
994         },
995         setSort : function() {
996             return ['create_date'];
997         }
998     }
999
1000     $scope.initTab('other', $routeParams.id)
1001     .then(function(redirect) {
1002         // if we are redirecting to the alerts page, avoid updating the
1003         // grid query.
1004         if (redirect) return;
1005         // let initTab() fetch the user first so we can know the usrgroup
1006
1007         grid.setQuery({
1008             usrgroup : patronSvc.current.usrgroup(),
1009             deleted : 'f'
1010         });
1011         $scope.totals.owed = patronSvc.patron_stats.fines.group_balance_owed;
1012     });
1013
1014     $scope.removeFromGroup = function(selected) {
1015         var promises = [];
1016         angular.forEach(selected, function(user) {
1017             console.debug('removing user ' + user.id + ' from group');
1018
1019             promises.push(
1020                 egCore.net.request(
1021                     'open-ils.actor',
1022                     'open-ils.actor.usergroup.new',
1023                     egCore.auth.token(), user.id, true
1024                 )
1025             );
1026         });
1027
1028         $q.all(promises).then(function() {grid.refresh()});
1029     }
1030
1031     function addUserToGroup(user) {
1032         user.usrgroup(patronSvc.current.usrgroup());
1033         user.ischanged(true);
1034         egCore.net.request(
1035             'open-ils.actor',
1036             'open-ils.actor.patron.update',
1037             egCore.auth.token(), user
1038
1039         ).then(function() {grid.refresh()});
1040     }
1041
1042     // fetch each user ("selected" has flattened users)
1043     // update the usrgroup, then update the user object
1044     // After all updates are complete, refresh the grid.
1045     function moveUsersToGroup(target_user, selected) {
1046         var promises = [];
1047
1048         angular.forEach(selected, function(user) {
1049             promises.push(
1050                 egCore.pcrud.retrieve('au', user.id)
1051                 .then(function(u) {
1052                     u.usrgroup(target_user.usrgroup());
1053                     u.ischanged(true);
1054                     return egCore.net.request(
1055                         'open-ils.actor',
1056                         'open-ils.actor.patron.update',
1057                         egCore.auth.token(), u
1058                     );
1059                 })
1060             );
1061         });
1062
1063         $q.all(promises).then(function() {grid.refresh()});
1064     }
1065
1066     function showMoveToGroupConfirm(barcode, selected, outbound) {
1067
1068         // find the user
1069         egCore.pcrud.search('ac', {barcode : barcode})
1070
1071         // fetch the fleshed user
1072         .then(function(card) {
1073
1074             if (!card) return; // TODO: warn user
1075
1076             egCore.pcrud.retrieve('au', card.usr())
1077             .then(function(user) {
1078                 user.card(card);
1079                 $uibModal.open({
1080                     templateUrl: './circ/patron/t_move_to_group_dialog',
1081                     backdrop: 'static',
1082                     controller: [
1083                                 '$scope','$uibModalInstance',
1084                         function($scope , $uibModalInstance) {
1085                             $scope.user = user;
1086                             $scope.selected = selected;
1087                             $scope.outbound = outbound;
1088                             $scope.ok = 
1089                                 function(count) { $uibModalInstance.close() }
1090                             $scope.cancel = 
1091                                 function () { $uibModalInstance.dismiss() }
1092                         }
1093                     ]
1094                 }).result.then(function() {
1095                     if (outbound) {
1096                         moveUsersToGroup(user, selected);
1097                     } else {
1098                         addUserToGroup(user);
1099                     }
1100                 });
1101             });
1102         });
1103     }
1104
1105     // selected == move selected patrons to another patron's group
1106     // !selected == patron from a different group moves into our group
1107     function moveToGroup(selected, outbound) {
1108         egPromptDialog.open(
1109             egCore.strings.GROUP_ADD_USER, '',
1110             {ok : function(value) {
1111                 if (value) 
1112                     showMoveToGroupConfirm(value, selected, outbound);
1113             }}
1114         );
1115     }
1116
1117     $scope.moveToGroup = function() { moveToGroup([], false) };
1118     $scope.moveToAnotherGroup = function(selected) { moveToGroup(selected, true) };
1119
1120     $scope.cloneUser = function(selected) {
1121         if (!selected.length) return;
1122         var url = $location.absUrl().replace(
1123             /\/patron\/.*/, 
1124             '/patron/register/clone/' + selected[0].id);
1125         $window.open(url, '_blank').focus();
1126     }
1127
1128     $scope.retrieveSelected = function(selected) {
1129         if (!selected.length) return;
1130         angular.forEach(selected, function(usr) {
1131             $timeout(function() {
1132                 var url = $location.absUrl().replace(
1133                     /\/patron\/.*/,
1134                     '/patron/' + usr.id + '/checkout');
1135                 $window.open(url, '_blank')
1136             });
1137         });
1138     }
1139
1140 }])
1141
1142 .controller('PatronStatCatsCtrl',
1143        ['$scope','$routeParams','$q','egCore','patronSvc',
1144 function($scope,  $routeParams , $q , egCore , patronSvc) {
1145     $scope.initTab('other', $routeParams.id)
1146     .then(function(redirect) {
1147         // Entries for org-visible stat cats are fleshed.  Any others
1148         // have to be fleshed within.
1149
1150         var to_flesh = {};
1151         angular.forEach(patronSvc.current.stat_cat_entries(), 
1152             function(entry) {
1153                 if (!angular.isObject(entry.stat_cat())) {
1154                     to_flesh[entry.stat_cat()] = entry;
1155                 }
1156             }
1157         );
1158
1159         if (!Object.keys(to_flesh).length) return;
1160
1161         egCore.pcrud.search('actsc', {id : Object.keys(to_flesh)})
1162         .then(null, null, function(cat) { // stream
1163             cat.owner(egCore.org.get(cat.owner())); // owner flesh
1164             to_flesh[cat.id()].stat_cat(cat);
1165         });
1166     });
1167 }])
1168
1169 .controller('PatronSurveyCtrl',
1170        ['$scope','$routeParams','$location','egCore','patronSvc',
1171 function($scope,  $routeParams , $location , egCore , patronSvc) {
1172     $scope.initTab('other', $routeParams.id);
1173     var usr_id = $routeParams.id;
1174     var org_ids = egCore.org.fullPath(egCore.auth.user().ws_ou(), true);
1175
1176     $scope.surveys = [];
1177     var svr_responses = {};
1178
1179     // fetch all survey responses for this user.
1180     egCore.pcrud.search('asvr',
1181         {usr : usr_id},
1182         {flesh : 2, flesh_fields : {asvr : ['survey','question','answer']}}
1183     ).then(
1184         function() {
1185             // All responses collected and deduplicated.
1186             // Create one collection of responses per survey.
1187
1188             angular.forEach(svr_responses, function(questions, survey_id) {
1189                 var collection = {responses : []};
1190                 angular.forEach(questions, function(response) {
1191                     collection.survey = response.survey(); // same for one.
1192                     collection.responses.push(response);
1193                 });
1194                 $scope.surveys.push(collection);
1195             });
1196         },
1197         null, 
1198         function(response) {
1199
1200             // Discard responses for out-of-scope surveys.
1201             if (org_ids.indexOf(response.survey().owner()) < 0) 
1202                 return;
1203
1204             // survey_id => question_id => response
1205             var svr_id = response.survey().id();
1206             var qst_id = response.question().id();
1207
1208             if (!svr_responses[svr_id]) 
1209                 svr_responses[svr_id] = [];
1210
1211             if (!svr_responses[svr_id][qst_id]) {
1212                 svr_responses[svr_id][qst_id] = response;
1213
1214             } else {
1215                 // We have multiple responses for the same question.
1216                 // For this UI we only care about the most recent response.
1217                 if (response.effective_date() > 
1218                     svr_responses[svr_id][qst_id].effective_date())
1219                     svr_responses[svr_id][qst_id] = response;
1220             }
1221         }
1222     );
1223 }])
1224
1225 .controller('PatronFetchLastCtrl',
1226        ['$scope','$location','egCore',
1227 function($scope , $location , egCore) {
1228
1229     var ids = egCore.hatch.getLoginSessionItem('eg.circ.recent_patrons') || [];
1230     if (ids.length) 
1231         return $location.path('/circ/patron/' + ids[0] + '/checkout');
1232
1233     $scope.no_last = true;
1234 }])
1235
1236 .controller('PatronTriggeredEventsCtrl',
1237        ['$scope','$routeParams','$location','egCore','patronSvc',
1238 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1239     $scope.initTab('other', $routeParams.id);
1240
1241     var url = $location.absUrl().replace(/\/staff.*/, '/actor/user/event_log');
1242     url += '?patron_id=' + encodeURIComponent($routeParams.id);
1243
1244     $scope.triggered_events_url = url;
1245     $scope.funcs = {};
1246 }])
1247
1248 .controller('PatronMessageCenterCtrl',
1249        ['$scope','$routeParams','$location','egCore','patronSvc',
1250 function($scope,  $routeParams,  $location , egCore , patronSvc) {
1251     $scope.initTab('other', $routeParams.id);
1252
1253     var url = $location.protocol() + '://' + $location.host()
1254         + egCore.env.basePath.replace(/\/staff.*/,  '/actor/user/message');
1255     url += '/' + encodeURIComponent($routeParams.id);
1256
1257     $scope.message_center_url = url;
1258     $scope.funcs = {};
1259 }])
1260
1261 .controller('PatronPermsCtrl',
1262        ['$scope','$routeParams','$window','$location','egCore',
1263 function($scope , $routeParams , $window , $location , egCore) {
1264     $scope.initTab('other', $routeParams.id);
1265
1266     var url = $location.absUrl().replace(
1267         /\/eg\/staff.*/, '/xul/server/patron/user_edit.xhtml');
1268
1269     url += '?usr=' + encodeURIComponent($routeParams.id);
1270
1271     // user_edit does not load the session via cookie.  It uses URL 
1272     // params or xulG instead.  Pass via xulG.
1273     $scope.funcs = {
1274         ses : egCore.auth.token(),
1275         on_patron_save : function() {
1276             $scope.funcs.reload();
1277         }
1278     }
1279
1280     $scope.user_perms_url = url;
1281 }])
1282