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