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