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