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