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