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