]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/admin/workstation/app.js
LP#1776020 Patron preferred name & name keywords
[Evergreen.git] / Open-ILS / web / js / ui / default / staff / admin / workstation / app.js
1 /**
2  * App to drive the base page. 
3  * Login Form
4  * Splash Page
5  */
6
7 angular.module('egWorkstationAdmin', 
8     ['ngRoute', 'ui.bootstrap', 'egCoreMod', 'egUiMod'])
9
10 .config(['$routeProvider','$locationProvider','$compileProvider', 
11  function($routeProvider , $locationProvider , $compileProvider) {
12
13     $locationProvider.html5Mode(true);
14     $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|mailto|blob):/); 
15     var resolver = {delay : function(egStartup) {return egStartup.go()}};
16
17     $routeProvider.when('/admin/workstation/workstations', {
18         templateUrl: './admin/workstation/t_workstations',
19         controller: 'WSRegCtrl',
20         resolve : resolver
21     });
22
23     $routeProvider.when('/admin/workstation/print/config', {
24         templateUrl: './admin/workstation/t_print_config',
25         controller: 'PrintConfigCtrl',
26         resolve : resolver
27     });
28
29     $routeProvider.when('/admin/workstation/print/templates', {
30         templateUrl: './admin/workstation/t_print_templates',
31         controller: 'PrintTemplatesCtrl',
32         resolve : resolver
33     });
34
35     $routeProvider.when('/admin/workstation/stored_prefs', {
36         templateUrl: './admin/workstation/t_stored_prefs',
37         controller: 'StoredPrefsCtrl',
38         resolve : resolver
39     });
40
41     $routeProvider.when('/admin/workstation/hatch', {
42         templateUrl: './admin/workstation/t_hatch',
43         controller: 'HatchCtrl',
44         resolve : resolver
45     });
46
47     $routeProvider.when('/admin/workstation/tests', {
48         templateUrl: './admin/workstation/t_tests',
49         controller: 'testsCtrl',
50         resolve : resolver
51     });
52     
53     // default page 
54     $routeProvider.otherwise({
55         templateUrl : './admin/workstation/t_splash',
56         controller : 'SplashCtrl',
57         resolve : resolver
58     });
59 }])
60
61 .config(['ngToastProvider', function(ngToastProvider) {
62   ngToastProvider.configure({
63     verticalPosition: 'bottom',
64     animation: 'fade'
65   });
66 }])
67
68 .factory('workstationSvc',
69        ['$q','$timeout','$location','egCore','egConfirmDialog',
70 function($q , $timeout , $location , egCore , egConfirmDialog) {
71     
72     var service = {};
73
74     service.get_all = function() {
75         return egCore.hatch.getItem('eg.workstation.all')
76         .then(function(all) { return all || [] });
77     }
78
79     service.get_default = function() {
80         return egCore.hatch.getItem('eg.workstation.default');
81     }
82
83     service.set_default = function(name) {
84         return egCore.hatch.setItem('eg.workstation.default', name);
85     }
86
87     service.register_workstation = function(base_name, name, org_id) {
88         return service.register_ws_api(base_name, name, org_id)
89         .then(function(ws_id) {
90             return service.track_new_ws(ws_id, name, org_id);
91         });
92     };
93
94     service.register_ws_api = 
95         function(base_name, name, org_id, override, deferred) {
96         if (!deferred) deferred = $q.defer();
97
98         var method = 'open-ils.actor.workstation.register';
99         if (override) method += '.override';
100
101         egCore.net.request(
102             'open-ils.actor', method, egCore.auth.token(), name, org_id)
103
104         .then(function(resp) {
105
106             if (evt = egCore.evt.parse(resp)) {
107                 console.log('register returned ' + evt.toString());
108
109                 if (evt.textcode == 'WORKSTATION_NAME_EXISTS' && !override) {
110
111                     egConfirmDialog.open(
112                         egCore.strings.WS_EXISTS, base_name, {  
113                             ok : function() {
114                                 service.register_ws_api(
115                                     base_name, name, org_id, true, deferred)
116                             },
117                             cancel : function() {
118                                 deferred.reject();
119                             }
120                         }
121                     );
122
123                 } else {
124                     alert(evt.toString());
125                     deferred.reject();
126                 }
127             } else if (resp) {
128                 console.log('Resolving register promise with: ' + resp);
129                 deferred.resolve(resp);
130             }
131         });
132
133         return deferred.promise;
134     }
135
136     service.track_new_ws = function(ws_id, ws_name, owning_lib) {
137         console.log('Tracking newly created WS with ID ' + ws_id);
138         var new_ws = {id : ws_id, name : ws_name, owning_lib : owning_lib};
139
140         return service.get_all()
141         .then(function(all) {
142             all.push(new_ws);
143             return egCore.hatch.setItem('eg.workstation.all', all)
144             .then(function() { return new_ws });
145         });
146     }
147
148     // Remove all traces of the workstation locally.
149     // This does not remove the WS from the server.
150     service.remove_workstation = function(name) {
151         console.debug('Removing workstation: ' + name);
152
153         return egCore.hatch.getItem('eg.workstation.all')
154
155         // remove from list of all workstations
156         .then(function(all) {
157             if (!all) all = [];
158             var keep = all.filter(function(ws) {return ws.name != name});
159             return egCore.hatch.setItem('eg.workstation.all', keep)
160
161         }).then(function() { 
162
163             return service.get_default()
164
165         }).then(function(def) {
166             if (def == name) {
167                 console.debug('Removing default workstation: ' + name);
168                 return egCore.hatch.removeItem('eg.workstation.default');
169             }
170         });
171     }
172
173     return service;
174 }])
175
176
177 .controller('SplashCtrl',
178        ['$scope','$window','$location','egCore','egConfirmDialog',
179 function($scope , $window , $location , egCore , egConfirmDialog) {
180
181     egCore.hatch.getItem('eg.audio.disable').then(function(val) {
182         $scope.disable_sound = val;
183     });
184
185     egCore.hatch.getItem('eg.search.search_lib').then(function(val) {
186         $scope.search_lib = egCore.org.get(val);
187     });
188     $scope.handle_search_lib_changed = function(org) {
189         egCore.hatch.setItem('eg.search.search_lib', org.id());
190     };
191
192     egCore.hatch.getItem('eg.search.pref_lib').then(function(val) {
193         $scope.pref_lib = egCore.org.get(val);
194     });
195     $scope.handle_pref_lib_changed = function(org) {
196         egCore.hatch.setItem('eg.search.pref_lib', org.id());
197     };
198
199     $scope.adv_pane = 'advanced'; // default value if not explicitly set
200     egCore.hatch.getItem('eg.search.adv_pane').then(function(val) {
201         $scope.adv_pane = val;
202     });
203     $scope.$watch('adv_pane', function(newVal, oldVal) {
204         if (typeof newVal != 'undefined' && newVal != oldVal) {
205             egCore.hatch.setItem('eg.search.adv_pane', newVal);
206         }
207     });
208
209     $scope.apply_sound = function() {
210         if ($scope.disable_sound) {
211             egCore.hatch.setItem('eg.audio.disable', true);
212         } else {
213             egCore.hatch.removeItem('eg.audio.disable');
214         }
215     }
216
217     $scope.test_audio = function(sound) {
218         egCore.audio.play(sound);
219     }
220
221 }])
222
223 .controller('PrintConfigCtrl',
224        ['$scope','egCore',
225 function($scope , egCore) {
226
227     $scope.printConfig = {};
228     $scope.setContext = function(ctx) { 
229         $scope.context = ctx; 
230         $scope.isTestView = false;
231     }
232     $scope.setContext('default');
233
234     $scope.setContentType = function(type) { $scope.contentType = type }
235     $scope.setContentType('text/plain');
236
237     $scope.useHatchPrinting = function() {
238         return egCore.hatch.usePrinting();
239     }
240
241     $scope.hatchIsOpen = function() {
242         return egCore.hatch.hatchAvailable;
243     }
244
245     $scope.getPrinterByAttr = function(attr, value) {
246         var printer;
247         angular.forEach($scope.printers, function(p) {
248             if (p[attr] == value) printer = p;
249         });
250         return printer;
251     }
252
253     $scope.resetPrinterSettings = function(context) {
254         $scope.printConfig[context] = {
255             context : context,
256             printer : $scope.defaultPrinter ? $scope.defaultPrinter.name : null,
257             autoMargins : true, 
258             allPages : true,
259             pageRanges : []
260         };
261     }
262
263     $scope.savePrinterSettings = function(context) {
264         return egCore.hatch.setPrintConfig(
265             context, $scope.printConfig[context]);
266     }
267
268     $scope.printerConfString = function() {
269         if ($scope.printConfigError) return $scope.printConfigError;
270         if (!$scope.printConfig) return;
271         if (!$scope.printConfig[$scope.context]) return;
272         return JSON.stringify(
273             $scope.printConfig[$scope.context], undefined, 2);
274     }
275
276     function loadPrinterOptions(name) {
277         egCore.hatch.getPrinterOptions(name).then(
278             function(options) {$scope.printerOptions = options});
279     }
280
281     $scope.setPrinter = function(name) {
282         $scope.printConfig[$scope.context].printer = name;
283         loadPrinterOptions(name);
284     }
285
286     $scope.testPrint = function(withDialog) {
287         if ($scope.contentType == 'text/plain') {
288             egCore.print.print({
289                 context : $scope.context, 
290                 content_type : $scope.contentType, 
291                 content : $scope.textPrintContent,
292                 show_dialog : withDialog
293             });
294         } else {
295             egCore.print.print({
296                 context : $scope.context,
297                 content_type : $scope.contentType, 
298                 content : $scope.htmlPrintContent, 
299                 scope : {
300                     value1 : 'Value One', 
301                     value2 : 'Value Two',
302                     date_value : '2015-02-04T14:04:34-0400'
303                 },
304                 show_dialog : withDialog
305             });
306         }
307     }
308
309     // Load startup data....
310     // Don't bother talking to Hatch if it's not there.
311     if (!egCore.hatch.hatchAvailable) return;
312
313     // fetch info on all remote printers
314     egCore.hatch.getPrinters()
315     .then(function(printers) { 
316         $scope.printers = printers;
317
318         var def = $scope.getPrinterByAttr('is-default', true);
319         if (!def && printers.length) def = printers[0];
320
321         if (def) {
322             $scope.defaultPrinter = def;
323             loadPrinterOptions(def.name);
324         }
325     }).then(function() {
326         angular.forEach(
327             ['default','receipt','label','mail','offline'],
328             function(ctx) {
329                 egCore.hatch.getPrintConfig(ctx).then(function(conf) {
330                     if (conf) {
331                         $scope.printConfig[ctx] = conf;
332                     } else {
333                         $scope.resetPrinterSettings(ctx);
334                     }
335                 });
336             }
337         );
338     });
339
340 }])
341
342 .controller('PrintTemplatesCtrl',
343        ['$scope','$q','egCore','ngToast',
344 function($scope , $q , egCore , ngToast) {
345
346     $scope.print = {
347         template_name : 'bills_current',
348         template_output : '',
349         template_context : 'default'
350     };
351
352     // print preview scope data
353     // TODO: consider moving the template-specific bits directly
354     // into the templates or storing template- specific script files
355     // alongside the templates.
356     // NOTE: A lot of this data can be shared across templates.
357     var seed_user = {
358         prefix : 'Mr',
359         first_given_name : 'Joseph',
360         second_given_name : 'Martin',
361         family_name : 'Jones',
362         suffix : 'III',
363         pref_first_given_name : 'Martin',
364         pref_second_given_name : 'Joe',
365         pref_family_name : 'Smith',
366         card : {
367             barcode : '30393830393'
368         },
369         money_summary : {
370             balance_owed : 4, // This is currently how these values are returned to the client
371             total_billed : '5.00',
372             total_paid : '1.00'
373         },
374         expire_date : '2020-12-31',
375         alias : 'Joey J.',
376         has_email : true,
377         has_phone : false,
378         dob : '1980-01-01T00:00:00-8:00',
379         juvenile : 'f',
380         usrname : '30393830393',
381         day_phone : '111-222-3333',
382         evening_phone : '222-333-1111',
383         other_phone : '333-111-2222',
384         email : 'user@example.com',
385         home_ou : {name: function() {return 'BR1'}},
386         profile : {name: function() {return 'Patrons'}},
387         net_access_level : {name: function() {return 'Filtered'}},
388         active : 't',
389         barred : 'f',
390         master_account : 'f',
391         claims_returned_count : '0',
392         claims_never_checked_out_count : '0',
393         alert_message : 'Coat is in the lost-and-found behind the circ desk',
394         ident_type: {name: function() {return 'Drivers License'}},
395         ident_value: '11332445',
396         ident_type2: {name: function() {return 'Other'}},
397         ident_value2 : '55442211',
398         addresses : [],
399         stat_cat_entries : [
400             {
401                 stat_cat : {'name' : 'Favorite Donut'},
402                 'stat_cat_entry' : 'Maple'
403             }, {
404                 stat_cat : {'name' : 'Favorite Book'},
405                 'stat_cat_entry' : 'Beasts Made of Night'
406             }
407         ]
408     }
409
410     var seed_addr = {
411         address_type : 'MAILING',
412         street1 : '123 Apple Rd',
413         street2 : 'Suite B',
414         city : 'Anywhere',
415         county : 'Great County',
416         state : 'XX',
417         country : 'US',
418         post_code : '12345',
419         valid : 't',
420         within_city_limits: 't'
421     }
422
423     seed_user.addresses.push(seed_addr);
424
425     var seed_record = {
426         title : 'Traveling Pants!!',
427         author : 'Jane Jones',
428         isbn : '1231312123'
429     };
430
431     var seed_copy = {
432         barcode : '33434322323',
433         call_number : {
434             label : '636.8 JON',
435             record : {
436                 simple_record : {
437                     'title' : 'Test Title'
438                 }
439             }
440         },
441         location : {
442             name : 'General Collection'
443         },
444         // flattened versions for item status template
445         // TODO - make this go away
446         'call_number.label' : '636.8 JON',
447         'call_number.record.simple_record.title' : 'Test Title',
448         'location.name' : 'General Colleciton'
449     }
450
451     var one_hold = {
452         behind_desk : 'f',
453         phone_notify : '111-222-3333',
454         sms_notify : '111-222-3333',
455         email_notify : 'user@example.org',
456         request_time : new Date().toISOString(),
457         hold_type : 'T',
458         shelf_expire_time : new Date().toISOString()
459     }
460
461     var seed_transit = {
462         source : {
463             name : 'Library Y',
464             shortname : 'LY',
465             holds_address : seed_addr
466         },
467         dest : {
468             name : 'Library X',
469             shortname : 'LX',
470             holds_address : seed_addr
471         },
472         source_send_time : new Date().toISOString(),
473         target_copy : seed_copy
474     }
475
476     $scope.preview_scope = {
477         //bills
478         transactions : [
479             {
480                 id : 1,
481                 xact_start : new Date().toISOString(),
482                 xact_finish : new Date().toISOString(),
483                 summary : {
484                     xact_type : 'circulation',
485                     last_billing_type : 'Overdue materials',
486                     total_owed : 1.50,
487                     last_payment_note : 'Test Note 1',
488                     last_payment_type : 'cash_payment',
489                     last_payment_ts : new Date().toISOString(),
490                     total_paid : 0.50,
491                     balance_owed : 1.00
492                 }
493             }, {
494                 id : 2,
495                 xact_start : new Date().toISOString(),
496                 xact_finish : new Date().toISOString(),
497                 summary : {
498                     xact_type : 'circulation',
499                     last_billing_type : 'Overdue materials',
500                     total_owed : 2.50,
501                     last_payment_note : 'Test Note 2',
502                     last_payment_type : 'credit_payment',
503                     last_payment_ts : new Date().toISOString(),
504                     total_paid : 0.50,
505                     balance_owed : 2.00
506                 }
507             }
508         ],
509
510         copy : seed_copy,
511         copies : [ seed_copy ],
512
513         checkins : [
514             {
515                 due_date : new Date().toISOString(),
516                 circ_lib : 1,
517                 duration : '7 days',
518                 target_copy : seed_copy,
519                 copy_barcode : seed_copy.barcode,
520                 call_number : seed_copy.call_number,
521                 title : seed_record.title
522             },
523         ],
524
525         circulations : [
526             {
527                 circ : {
528                     due_date : new Date().toISOString(),
529                     circ_lib : 1,
530                     duration : '7 days'
531                 },
532                 copy : seed_copy,
533                 title : seed_record.title,
534                 author : seed_record.author
535             },
536         ],
537
538         patron_money : {
539             balance_owed : 5.01,
540             total_owed : 10.12,
541             total_paid : 5.11
542         },
543
544         in_house_uses : [
545             {
546                 num_uses : 3,
547                 copy : seed_copy,
548                 title : seed_record.title
549             }
550         ],
551
552         previous_balance : 8.45,
553         payment_total : 2.00,
554         payment_applied : 2.00,
555         new_balance : 6.45,
556         amount_voided : 0,
557         change_given : 0,
558         payment_type : 'cash_payment',
559         payment_note : 'Here is a payment note',
560         note : {
561             create_date : new Date().toISOString(), 
562             title : 'Test Note Title',
563             usr : seed_user,
564             value : 'This patron is super nice!'
565         },
566
567         transit : seed_transit,
568         transits : [ seed_transit ],
569         title : seed_record.title,
570         author : seed_record.author,
571         patron : seed_user,
572         address : seed_addr,
573         dest_location : egCore.idl.toHash(egCore.org.get(egCore.auth.user().ws_ou())),
574         dest_courier_code : 'ABC 123',
575         dest_address : seed_addr,
576         hold : one_hold,
577         holds : [
578             {
579                 hold : one_hold, title : 'Some Title 1', author : 'Some Author 1',
580                 volume : { label : '646.4 SOM' }, copy : seed_copy,
581                 part : { label : 'v. 1' },
582                 patron_barcode : 'S52802662',
583                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane',
584                 status_string : 'Ready for Pickup'
585             },
586             {
587                 hold : one_hold, title : 'Some Title 2', author : 'Some Author 2',
588                 volume : { label : '646.4 SOM' }, copy : seed_copy,
589                 part : { label : 'v. 1' },
590                 patron_barcode : 'S52802662',
591                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane',
592                 status_string : 'Ready for Pickup'
593             },
594             {
595                 hold : one_hold, title : 'Some Title 3', author : 'Some Author 3',
596                 volume : { label : '646.4 SOM' }, copy : seed_copy,
597                 part : { label : 'v. 1' },
598                 patron_barcode : 'S52802662',
599                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane',
600                 status_string : 'Canceled'
601             }
602         ]
603     }
604
605     $scope.preview_scope.payments = [
606         {amount : 1.00, xact : $scope.preview_scope.transactions[0]}, 
607         {amount : 1.00, xact : $scope.preview_scope.transactions[1]}
608     ]
609     $scope.preview_scope.payments[0].xact.title = 'Hali Bote Azikaban de tao fan';
610     $scope.preview_scope.payments[0].xact.copy_barcode = '334343434';
611     $scope.preview_scope.payments[1].xact.title = seed_record.title;
612     $scope.preview_scope.payments[1].xact.copy_barcode = seed_copy.barcode;
613
614     // today, staff, current_location, etc.
615     egCore.print.fleshPrintScope($scope.preview_scope);
616
617     $scope.template_changed = function() {
618         $scope.print.load_failed = false;
619         egCore.print.getPrintTemplate($scope.print.template_name)
620         .then(
621             function(html) { 
622                 $scope.print.template_content = html;
623                 console.log('set template content');
624             },
625             function() {
626                 $scope.print.template_content = '';
627                 $scope.print.load_failed = true;
628             }
629         );
630         egCore.print.getPrintTemplateContext($scope.print.template_name)
631         .then(function(template_context) {
632             $scope.print.template_context = template_context;
633         });
634     }
635
636     $scope.reset_to_default = function() {
637         egCore.print.removePrintTemplate(
638             $scope.print.template_name
639         );
640         egCore.print.removePrintTemplateContext(
641             $scope.print.template_name
642         );
643         $scope.template_changed();
644     }
645
646     $scope.save_locally = function() {
647         egCore.print.storePrintTemplate(
648             $scope.print.template_name,
649             $scope.print.template_content
650         );
651         egCore.print.storePrintTemplateContext(
652             $scope.print.template_name,
653             $scope.print.template_context
654         );
655     }
656
657     $scope.exportable_templates = function() {
658         var templates = {};
659         var contexts = {};
660         var deferred = $q.defer();
661         var promises = [];
662         egCore.hatch.getKeys('eg.print.template').then(function(keys) {
663             angular.forEach(keys, function(key) {
664                 if (key.match(/^eg\.print\.template\./)) {
665                     promises.push(egCore.hatch.getItem(key).then(function(value) {
666                         templates[key.replace('eg.print.template.', '')] = value;
667                     }));
668                 } else {
669                     promises.push(egCore.hatch.getItem(key).then(function(value) {
670                         contexts[key.replace('eg.print.template_context.', '')] = value;
671                     }));
672                 }
673             });
674             $q.all(promises).then(function() {
675                 if (Object.keys(templates).length) {
676                     deferred.resolve({
677                         templates: templates,
678                         contexts: contexts
679                     });
680                 } else {
681                     ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_EXPORT);
682                     deferred.reject();
683                 }
684             });
685         });
686         return deferred.promise;
687     }
688
689     $scope.imported_print_templates = { data : '' };
690     $scope.$watch('imported_print_templates.data', function(newVal, oldVal) {
691         if (newVal && newVal != oldVal) {
692             try {
693                 var data = JSON.parse(newVal);
694                 angular.forEach(data.templates, function(template_content, template_name) {
695                     egCore.print.storePrintTemplate(template_name, template_content);
696                 });
697                 angular.forEach(data.contexts, function(template_context, template_name) {
698                     egCore.print.storePrintTemplateContext(template_name, template_context);
699                 });
700                 $scope.template_changed(); // refresh
701                 ngToast.create(egCore.strings.PRINT_TEMPLATES_SUCCESS_IMPORT);
702             } catch (E) {
703                 ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_IMPORT);
704             }
705         }
706     });
707
708     $scope.template_changed(); // load the default
709 }])
710
711 // 
712 .directive('egPrintTemplateOutput', ['$compile',function($compile) {
713     return function(scope, element, attrs) {
714         scope.$watch(
715             function(scope) {
716                 return scope.$eval(attrs.content);
717             },
718             function(value) {
719                 // create an isolate scope and copy the print context
720                 // data into the new scope.
721                 // TODO: see also print security concerns in egHatch
722                 var result = element.html(value);
723                 var context = scope.$eval(attrs.context);
724                 var print_scope = scope.$new(true);
725                 angular.forEach(context, function(val, key) {
726                     print_scope[key] = val;
727                 })
728                 $compile(element.contents())(print_scope);
729             }
730         );
731     };
732 }])
733
734 .controller('StoredPrefsCtrl',
735        ['$scope','$q','egCore','egConfirmDialog',
736 function($scope , $q , egCore , egConfirmDialog) {
737     console.log('StoredPrefsCtrl');
738
739     $scope.setContext = function(ctx) {
740         $scope.context = ctx;
741     }
742     $scope.setContext('local');
743
744     // grab the edit perm
745     $scope.userHasDeletePerm = false;
746     egCore.perm.hasPermHere('ADMIN_WORKSTATION')
747     .then(function(bool) { $scope.userHasDeletePerm = bool });
748
749     // fetch the keys
750
751     function refreshKeys() {
752         $scope.keys = {local : [], remote : [], server_workstation: []};
753
754         if (egCore.hatch.hatchAvailable) {
755             egCore.hatch.getRemoteKeys().then(
756                 function(keys) { $scope.keys.remote = keys.sort() })
757         }
758     
759         // local calls are non-async
760         $scope.keys.local = egCore.hatch.getLocalKeys();
761
762         egCore.hatch.getServerKeys(null, {workstation_only: true}).then(
763             function(keys) {$scope.keys.server_workstation = keys});
764     }
765     refreshKeys();
766
767     $scope.selectKey = function(key) {
768         $scope.currentKey = key;
769         $scope.currentKeyContent = null;
770
771         if ($scope.context == 'local') {
772             $scope.currentKeyContent = egCore.hatch.getLocalItem(key);
773         } else if ($scope.context == 'remote') {
774             egCore.hatch.getRemoteItem(key)
775             .then(function(content) {
776                 $scope.currentKeyContent = content
777             });
778         } else if ($scope.context == 'server_workstation') {
779             egCore.hatch.getServerItem(key).then(function(content) {
780                 $scope.currentKeyContent = content;
781             });
782         }
783     }
784
785     $scope.getCurrentKeyContent = function() {
786         return JSON.stringify($scope.currentKeyContent, null, 2);
787     }
788
789     $scope.removeKey = function(key) {
790         egConfirmDialog.open(
791             egCore.strings.PREFS_REMOVE_KEY_CONFIRM, '',
792             {   deleteKey : key,
793                 ok : function() {
794                     if ($scope.context == 'local') {
795                         egCore.hatch.removeLocalItem(key);
796                         refreshKeys();
797                     } else if ($scope.context == 'remote') {
798                         // Honor requests to remove items from Hatch even
799                         // when Hatch is configured for data storage.
800                         egCore.hatch.removeRemoteItem(key)
801                         .then(function() { refreshKeys() });
802                     } else if ($scope.context == 'server_workstation') {
803                         egCore.hatch.removeServerItem(key)
804                         .then(function() { refreshKeys() });
805                     }
806                 },
807                 cancel : function() {} // user canceled, nothing to do
808             }
809         );
810     }
811 }])
812
813 .controller('WSRegCtrl',
814        ['$scope','$q','$window','$location','egCore','egAlertDialog','workstationSvc',
815 function($scope , $q , $window , $location , egCore , egAlertDialog , workstationSvc) {
816
817     var all_workstations = [];
818     var reg_perm_orgs = [];
819
820     $scope.page_loaded = false;
821     $scope.contextOrg = egCore.org.get(egCore.auth.user().ws_ou());
822     $scope.wsOrgChanged = function(org) { $scope.contextOrg = org; }
823
824     console.log('set context org to ' + $scope.contextOrg);
825
826     // fetch workstation reg perms
827     egCore.perm.hasPermAt('REGISTER_WORKSTATION', true)
828     .then(function(orgList) { 
829         reg_perm_orgs = orgList;
830
831         // hide orgs in the context org selector where this login
832         // does not have the reg_ws perm or the org can't have users
833         $scope.wsOrgHidden = function(id) {
834             return reg_perm_orgs.indexOf(id) == -1
835                 || $scope.cant_have_users(id);
836         }
837
838     // fetch the locally stored workstation data
839     }).then(function() {
840         return workstationSvc.get_all()
841         
842     }).then(function(all) {
843         all_workstations = all || [];
844         $scope.workstations = 
845             all_workstations.map(function(w) { return w.name });
846         return workstationSvc.get_default()
847
848     // fetch the default workstation
849     }).then(function(def) { 
850         $scope.defaultWS = def;
851         $scope.activeWS = $scope.selectedWS = egCore.auth.workstation() || def;
852
853     // Handle any URL commands.
854     }).then(function() {
855         var remove = $location.search().remove;
856          if (remove) {
857             console.log('Removing WS via URL request: ' + remove);
858             return $scope.remove_ws(remove).then(
859                 function() { $scope.page_loaded = true; });
860         }
861         $scope.page_loaded = true;
862     });
863
864     $scope.get_ws_label = function(ws) {
865         return ws == $scope.defaultWS ? 
866             egCore.strings.$replace(egCore.strings.DEFAULT_WS_LABEL, {ws:ws}) : ws;
867     }
868
869     $scope.set_default_ws = function(name) {
870         delete $scope.removing_ws;
871         $scope.defaultWS = name;
872         workstationSvc.set_default(name);
873     }
874
875     $scope.cant_have_users = 
876         function (id) { return !egCore.org.CanHaveUsers(id); };
877     $scope.cant_have_volumes = 
878         function (id) { return !egCore.org.CanHaveVolumes(id); };
879
880     // Log out and return to login page with selected WS 
881     $scope.use_now = function() {
882         egCore.auth.logout();
883         $window.location.href = $location
884             .path('/login')
885             .search({ws : $scope.selectedWS})
886             .absUrl();
887     }
888
889     $scope.can_delete_ws = function(name) {
890         var ws = all_workstations.filter(
891             function(ws) { return ws.name == name })[0];
892         return ws && reg_perm_orgs.indexOf(ws.owning_lib) != -1;
893     }
894
895     $scope.remove_ws = function(remove_me) {
896         $scope.removing_ws = remove_me;
897
898         // Perm is used to disable Remove button in UI, but have to check
899         // again here in case we're removing a WS based on URL params.
900         if (!$scope.can_delete_ws(remove_me)) return $q.when();
901
902         $scope.is_removing = true;
903         return workstationSvc.remove_workstation(remove_me)
904         .then(function() {
905
906             all_workstations = all_workstations.filter(
907                 function(ws) { return ws.name != remove_me });
908
909             $scope.workstations = $scope.workstations.filter(
910                 function(ws) { return ws != remove_me });
911
912             if ($scope.selectedWS == remove_me) 
913                 $scope.selectedWS = $scope.workstations[0];
914
915             if ($scope.defaultWS == remove_me) 
916                 $scope.defaultWS = '';
917
918             $scope.is_removing = false;
919         });
920     }
921
922     $scope.register_ws = function() {
923         delete $scope.removing_ws;
924
925         var full_name = 
926             $scope.contextOrg.shortname() + '-' + $scope.newWSName;
927
928         if ($scope.workstations.indexOf(full_name) > -1) {
929             // avoid duplicate local registrations
930             return egAlertDialog.open(egCore.strings.WS_USED);
931         }
932
933         $scope.is_registering = true;
934         workstationSvc.register_workstation(
935             $scope.newWSName, full_name,
936             $scope.contextOrg.id()
937
938         ).then(function(new_ws) {
939             $scope.workstations.push(new_ws.name);
940             all_workstations.push(new_ws);  
941             $scope.is_registering = false;
942
943             if (!$scope.selectedWS) {
944                 $scope.selectedWS = new_ws.name;
945             }
946             if (!$scope.defaultWS) {
947                 return $scope.set_default_ws(new_ws.name);
948             }
949             $scope.newWSName = '';
950         }, function(err) {
951             $scope.is_registering = false;
952         });
953     }
954 }])
955
956 .controller('HatchCtrl',
957        ['$scope','egCore','ngToast',
958 function($scope , egCore , ngToast) {
959     var hatch = egCore.hatch;  // convenience
960
961     $scope.hatch_available = hatch.hatchAvailable;
962     $scope.hatch_printing = hatch.usePrinting();
963     $scope.hatch_settings = hatch.useSettings();
964     $scope.hatch_offline  = hatch.useOffline();
965
966     // Apply Hatch settings as changes occur in the UI.
967     
968     $scope.$watch('hatch_printing', function(newval) {
969         if (typeof newval != 'boolean') return;
970         hatch.setLocalItem('eg.hatch.enable.printing', newval);
971     });
972
973     $scope.$watch('hatch_settings', function(newval) {
974         if (typeof newval != 'boolean') return;
975         hatch.setLocalItem('eg.hatch.enable.settings', newval);
976     });
977
978     $scope.$watch('hatch_offline', function(newval) {
979         if (typeof newval != 'boolean') return;
980         hatch.setLocalItem('eg.hatch.enable.offline', newval);
981     });
982
983     $scope.copy_to_hatch = function() {
984         hatch.copySettingsToHatch().then(
985             function() {
986                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
987             function() {
988                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
989         );
990     }
991
992     $scope.copy_to_local = function() {
993         hatch.copySettingsToLocal().then(
994             function() {
995                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
996             function() {
997                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
998         );
999     }
1000
1001 }])
1002
1003 /*
1004  * Home of the Latency tester
1005  * */
1006 .controller('testsCtrl', ['$scope', '$location', 'egCore', function($scope, $location, egCore) {
1007     $scope.hostname = $location.host();
1008
1009     $scope.tests = [];
1010     $scope.clearTestData = function(){
1011         $scope.tests = [];
1012         numPings = 0;
1013     }
1014
1015     $scope.isTesting = false;
1016     $scope.avrg = 0; // avrg latency
1017     $scope.canCopyCommand = document.queryCommandSupported('copy');
1018     var numPings = 0;
1019     // initially fetch first 10 (gets a decent average)
1020
1021     function calcAverage(){
1022
1023         if ($scope.tests.length == 0) return 0;
1024
1025         if ($scope.tests.length == 1) return $scope.tests[0].l;
1026
1027         var sum = 0;
1028         angular.forEach($scope.tests, function(t){
1029             sum += t.l;
1030         });
1031
1032         return sum / $scope.tests.length;
1033     }
1034
1035     function ping(){
1036         $scope.isTesting = true;
1037         var t = Date.now();
1038         return egCore.net.request(
1039             "open-ils.pcrud", "opensrf.system.echo", "ping"
1040         ).then(function(resp){
1041             var t2 = Date.now();
1042             var latency = t2 - t;
1043             $scope.tests.push({t: new Date(t), l: latency});
1044             console.log("Start: " + t + " and end: " + t2);
1045             console.log("Latency: " + latency);
1046             console.log(resp);
1047         }).then(function(){
1048             $scope.avrg = calcAverage();
1049             numPings++;
1050             $scope.isTesting = false;
1051         });
1052     }
1053
1054     $scope.testLatency = function(){
1055
1056         if (numPings >= 10){
1057             ping(); // just ping once after the initial ten
1058         } else {
1059             ping()
1060                 .then($scope.testLatency)
1061                 .then(function(){
1062                     if (numPings == 9){
1063                         $scope.tests.shift(); // toss first result
1064                         $scope.avrg = calcAverage();
1065                     }
1066                 });
1067         }
1068     }
1069
1070     $scope.copyTests = function(){
1071
1072         var lNode = document.querySelector('#pingData');
1073         var r = document.createRange();
1074         r.selectNode(lNode);
1075         var sel = window.getSelection();
1076         sel.removeAllRanges();
1077         sel.addRange(r);
1078         document.execCommand('copy');
1079     }
1080
1081 }])
1082
1083