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