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