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