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