]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/admin/workstation/app.js
LP#1705068 - fix workstation already exists cancel btn freezes UI
[working/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?|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     // default page 
48     $routeProvider.otherwise({
49         templateUrl : './admin/workstation/t_splash',
50         controller : 'SplashCtrl',
51         resolve : resolver
52     });
53 }])
54
55 .config(['ngToastProvider', function(ngToastProvider) {
56   ngToastProvider.configure({
57     verticalPosition: 'bottom',
58     animation: 'fade'
59   });
60 }])
61
62 .factory('workstationSvc',
63        ['$q','$timeout','$location','egCore','egConfirmDialog',
64 function($q , $timeout , $location , egCore , egConfirmDialog) {
65     
66     var service = {};
67
68     service.get_all = function() {
69         return egCore.hatch.getItem('eg.workstation.all')
70         .then(function(all) { return all || [] });
71     }
72
73     service.get_default = function() {
74         return egCore.hatch.getItem('eg.workstation.default');
75     }
76
77     service.set_default = function(name) {
78         return egCore.hatch.setItem('eg.workstation.default', name);
79     }
80
81     service.register_workstation = function(base_name, name, org_id) {
82         return service.register_ws_api(base_name, name, org_id)
83         .then(function(ws_id) {
84             return service.track_new_ws(ws_id, name, org_id);
85         });
86     };
87
88     service.register_ws_api = 
89         function(base_name, name, org_id, override, deferred) {
90         if (!deferred) deferred = $q.defer();
91
92         var method = 'open-ils.actor.workstation.register';
93         if (override) method += '.override';
94
95         egCore.net.request(
96             'open-ils.actor', method, egCore.auth.token(), name, org_id)
97
98         .then(function(resp) {
99
100             if (evt = egCore.evt.parse(resp)) {
101                 console.log('register returned ' + evt.toString());
102
103                 if (evt.textcode == 'WORKSTATION_NAME_EXISTS' && !override) {
104
105                     egConfirmDialog.open(
106                         egCore.strings.WS_EXISTS, base_name, {  
107                             ok : function() {
108                                 service.register_ws_api(
109                                     base_name, name, org_id, true, deferred)
110                             },
111                             cancel : function() {
112                                 deferred.reject();
113                             }
114                         }
115                     );
116
117                 } else {
118                     alert(evt.toString());
119                     deferred.reject();
120                 }
121             } else if (resp) {
122                 console.log('Resolving register promise with: ' + resp);
123                 deferred.resolve(resp);
124             }
125         });
126
127         return deferred.promise;
128     }
129
130     service.track_new_ws = function(ws_id, ws_name, owning_lib) {
131         console.log('Tracking newly created WS with ID ' + ws_id);
132         var new_ws = {id : ws_id, name : ws_name, owning_lib : owning_lib};
133
134         return service.get_all()
135         .then(function(all) {
136             all.push(new_ws);
137             return egCore.hatch.setItem('eg.workstation.all', all)
138             .then(function() { return new_ws });
139         });
140     }
141
142     // Remove all traces of the workstation locally.
143     // This does not remove the WS from the server.
144     service.remove_workstation = function(name) {
145         console.debug('Removing workstation: ' + name);
146
147         return egCore.hatch.getItem('eg.workstation.all')
148
149         // remove from list of all workstations
150         .then(function(all) {
151             if (!all) all = [];
152             var keep = all.filter(function(ws) {return ws.name != name});
153             return egCore.hatch.setItem('eg.workstation.all', keep)
154
155         }).then(function() { 
156
157             return service.get_default()
158
159         }).then(function(def) {
160             if (def == name) {
161                 console.debug('Removing default workstation: ' + name);
162                 return egCore.hatch.removeItem('eg.workstation.default');
163             }
164         });
165     }
166
167     return service;
168 }])
169
170
171 .controller('SplashCtrl',
172        ['$scope','$window','$location','egCore','egConfirmDialog',
173 function($scope , $window , $location , egCore , egConfirmDialog) {
174
175     egCore.hatch.getItem('eg.audio.disable').then(function(val) {
176         $scope.disable_sound = val;
177     });
178
179     egCore.hatch.getItem('eg.search.search_lib').then(function(val) {
180         $scope.search_lib = egCore.org.get(val);
181     });
182     $scope.handle_search_lib_changed = function(org) {
183         egCore.hatch.setItem('eg.search.search_lib', org.id());
184     };
185
186     egCore.hatch.getItem('eg.search.pref_lib').then(function(val) {
187         $scope.pref_lib = egCore.org.get(val);
188     });
189     $scope.handle_pref_lib_changed = function(org) {
190         egCore.hatch.setItem('eg.search.pref_lib', org.id());
191     };
192
193     $scope.adv_pane = 'advanced'; // default value if not explicitly set
194     egCore.hatch.getItem('eg.search.adv_pane').then(function(val) {
195         $scope.adv_pane = val;
196     });
197     $scope.$watch('adv_pane', function(newVal, oldVal) {
198         if (typeof newVal != 'undefined' && newVal != oldVal) {
199             egCore.hatch.setItem('eg.search.adv_pane', newVal);
200         }
201     });
202
203     $scope.apply_sound = function() {
204         if ($scope.disable_sound) {
205             egCore.hatch.setItem('eg.audio.disable', true);
206         } else {
207             egCore.hatch.removeItem('eg.audio.disable');
208         }
209     }
210
211     $scope.test_audio = function(sound) {
212         egCore.audio.play(sound);
213     }
214
215 }])
216
217 .controller('PrintConfigCtrl',
218        ['$scope','egCore',
219 function($scope , egCore) {
220
221     $scope.printConfig = {};
222     $scope.setContext = function(ctx) { 
223         $scope.context = ctx; 
224         $scope.isTestView = false;
225     }
226     $scope.setContext('default');
227
228     $scope.setContentType = function(type) { $scope.contentType = type }
229     $scope.setContentType('text/plain');
230
231     $scope.useHatchPrinting = function() {
232         return egCore.hatch.usePrinting();
233     }
234
235     $scope.hatchIsOpen = function() {
236         return egCore.hatch.hatchAvailable;
237     }
238
239     $scope.getPrinterByAttr = function(attr, value) {
240         var printer;
241         angular.forEach($scope.printers, function(p) {
242             if (p[attr] == value) printer = p;
243         });
244         return printer;
245     }
246
247     $scope.resetPrinterSettings = function(context) {
248         $scope.printConfig[context] = {
249             context : context,
250             printer : $scope.defaultPrinter ? $scope.defaultPrinter.name : null,
251             autoMargins : true, 
252             allPages : true,
253             pageRanges : []
254         };
255     }
256
257     $scope.savePrinterSettings = function(context) {
258         return egCore.hatch.setPrintConfig(
259             context, $scope.printConfig[context]);
260     }
261
262     $scope.printerConfString = function() {
263         if ($scope.printConfigError) return $scope.printConfigError;
264         if (!$scope.printConfig) return;
265         if (!$scope.printConfig[$scope.context]) return;
266         return JSON.stringify(
267             $scope.printConfig[$scope.context], undefined, 2);
268     }
269
270     function loadPrinterOptions(name) {
271         egCore.hatch.getPrinterOptions(name).then(
272             function(options) {$scope.printerOptions = options});
273     }
274
275     $scope.setPrinter = function(name) {
276         $scope.printConfig[$scope.context].printer = name;
277         loadPrinterOptions(name);
278     }
279
280     $scope.testPrint = function(withDialog) {
281         if ($scope.contentType == 'text/plain') {
282             egCore.print.print({
283                 context : $scope.context, 
284                 content_type : $scope.contentType, 
285                 content : $scope.textPrintContent,
286                 show_dialog : withDialog
287             });
288         } else {
289             egCore.print.print({
290                 context : $scope.context,
291                 content_type : $scope.contentType, 
292                 content : $scope.htmlPrintContent, 
293                 scope : {
294                     value1 : 'Value One', 
295                     value2 : 'Value Two',
296                     date_value : '2015-02-04T14:04:34-0400'
297                 },
298                 show_dialog : withDialog
299             });
300         }
301     }
302
303     // Load startup data....
304     // Don't bother talking to Hatch if it's not there.
305     if (!egCore.hatch.hatchAvailable) return;
306
307     // fetch info on all remote printers
308     egCore.hatch.getPrinters()
309     .then(function(printers) { 
310         $scope.printers = printers;
311
312         var def = $scope.getPrinterByAttr('is-default', true);
313         if (!def && printers.length) def = printers[0];
314
315         if (def) {
316             $scope.defaultPrinter = def;
317             loadPrinterOptions(def.name);
318         }
319     }).then(function() {
320         angular.forEach(
321             ['default','receipt','label','mail','offline'],
322             function(ctx) {
323                 egCore.hatch.getPrintConfig(ctx).then(function(conf) {
324                     if (conf) {
325                         $scope.printConfig[ctx] = conf;
326                     } else {
327                         $scope.resetPrinterSettings(ctx);
328                     }
329                 });
330             }
331         );
332     });
333
334 }])
335
336 .controller('PrintTemplatesCtrl',
337        ['$scope','$q','egCore','ngToast',
338 function($scope , $q , egCore , ngToast) {
339
340     $scope.print = {
341         template_name : 'bills_current',
342         template_output : '',
343         template_context : 'default'
344     };
345
346     // print preview scope data
347     // TODO: consider moving the template-specific bits directly
348     // into the templates or storing template- specific script files
349     // alongside the templates.
350     // NOTE: A lot of this data can be shared across templates.
351     var seed_user = {
352         first_given_name : 'Slow',
353         second_given_name : 'Joe',
354         family_name : 'Jones',
355         card : {
356             barcode : '30393830393'
357         }
358     }
359     var seed_addr = {
360         street1 : '123 Apple Rd',
361         street2 : 'Suite B',
362         city : 'Anywhere',
363         state : 'XX',
364         country : 'US',
365         post_code : '12345'
366     }
367
368     var seed_record = {
369         title : 'Traveling Pants!!',
370         author : 'Jane Jones',
371         isbn : '1231312123'
372     };
373
374     var seed_copy = {
375         barcode : '33434322323',
376         call_number : {
377             label : '636.8 JON',
378             record : {
379                 simple_record : {
380                     'title' : 'Test Title'
381                 }
382             }
383         },
384         location : {
385             name : 'General Collection'
386         },
387         // flattened versions for item status template
388         // TODO - make this go away
389         'call_number.label' : '636.8 JON',
390         'call_number.record.simple_record.title' : 'Test Title',
391         'location.name' : 'General Colleciton'
392     }
393
394     var one_hold = {
395         behind_desk : 'f',
396         phone_notify : '111-222-3333',
397         sms_notify : '111-222-3333',
398         email_notify : 'user@example.org',
399         request_time : new Date().toISOString(),
400         hold_type : 'T'
401     }
402
403     var seed_transit = {
404         source : {
405             name : 'Library Y',
406             shortname : 'LY',
407             holds_address : seed_addr
408         },
409         dest : {
410             name : 'Library X',
411             shortname : 'LX',
412             holds_address : seed_addr
413         },
414         source_send_time : new Date().toISOString(),
415         target_copy : seed_copy
416     }
417
418     $scope.preview_scope = {
419         //bills
420         transactions : [
421             {
422                 id : 1,
423                 xact_start : new Date().toISOString(),
424                 summary : {
425                     xact_type : 'circulation',
426                     last_billing_type : 'Overdue materials',
427                     total_owed : 1.50,
428                     last_payment_note : 'Test Note 1',
429                     last_payment_type : 'cash_payment',
430                     total_paid : 0.50,
431                     balance_owed : 1.00
432                 }
433             }, {
434                 id : 2,
435                 xact_start : new Date().toISOString(),
436                 summary : {
437                     xact_type : 'circulation',
438                     last_billing_type : 'Overdue materials',
439                     total_owed : 2.50,
440                     last_payment_note : 'Test Note 2',
441                     last_payment_type : 'credit_payment',
442                     total_paid : 0.50,
443                     balance_owed : 2.00
444                 }
445             }
446         ],
447
448         copy : seed_copy,
449         copies : [ seed_copy ],
450
451         checkins : [
452             {
453                 due_date : new Date().toISOString(),
454                 circ_lib : 1,
455                 duration : '7 days',
456                 target_copy : seed_copy,
457                 copy_barcode : seed_copy.barcode,
458                 call_number : seed_copy.call_number,
459                 title : seed_record.title
460             },
461         ],
462
463         circulations : [
464             {
465                 circ : {
466                     due_date : new Date().toISOString(),
467                     circ_lib : 1,
468                     duration : '7 days'
469                 },
470                 copy : seed_copy,
471                 title : seed_record.title,
472                 author : seed_record.author
473             },
474         ],
475
476         in_house_uses : [
477             {
478                 num_uses : 3,
479                 copy : seed_copy,
480                 title : seed_record.title
481             }
482         ],
483
484         previous_balance : 8.45,
485         payment_total : 2.00,
486         payment_applied : 2.00,
487         new_balance : 6.45,
488         amount_voided : 0,
489         change_given : 0,
490         payment_type : 'cash_payment',
491         payment_note : 'Here is a payment note',
492         note : {
493             create_date : new Date().toISOString(), 
494             title : 'Test Note Title',
495             usr : seed_user,
496             value : 'This patron is super nice!'
497         },
498
499         transit : seed_transit,
500         transits : [ seed_transit ],
501         title : seed_record.title,
502         author : seed_record.author,
503         patron : seed_user,
504         address : seed_addr,
505         dest_location : egCore.idl.toHash(egCore.org.get(egCore.auth.user().ws_ou())),
506         dest_address : seed_addr,
507         hold : one_hold,
508         holds : [
509             {
510                 hold : one_hold, title : 'Some Title 1', author : 'Some Author 1',
511                 volume : { label : '646.4 SOM' }, copy : seed_copy,
512                 part : { label : 'v. 1' },
513                 patron_barcode : 'S52802662',
514                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
515             },
516             {
517                 hold : one_hold, title : 'Some Title 2', author : 'Some Author 2',
518                 volume : { label : '646.4 SOM' }, copy : seed_copy,
519                 part : { label : 'v. 1' },
520                 patron_barcode : 'S52802662',
521                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
522             },
523             {
524                 hold : one_hold, title : 'Some Title 3', author : 'Some Author 3',
525                 volume : { label : '646.4 SOM' }, copy : seed_copy,
526                 part : { label : 'v. 1' },
527                 patron_barcode : 'S52802662',
528                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
529             }
530         ]
531     }
532
533     $scope.preview_scope.payments = [
534         {amount : 1.00, xact : $scope.preview_scope.transactions[0]}, 
535         {amount : 1.00, xact : $scope.preview_scope.transactions[1]}
536     ]
537     $scope.preview_scope.payments[0].xact.title = 'Hali Bote Azikaban de tao fan';
538     $scope.preview_scope.payments[0].xact.copy_barcode = '334343434';
539     $scope.preview_scope.payments[1].xact.title = seed_record.title;
540     $scope.preview_scope.payments[1].xact.copy_barcode = seed_copy.barcode;
541
542     // today, staff, current_location, etc.
543     egCore.print.fleshPrintScope($scope.preview_scope);
544
545     $scope.template_changed = function() {
546         $scope.print.load_failed = false;
547         egCore.print.getPrintTemplate($scope.print.template_name)
548         .then(
549             function(html) { 
550                 $scope.print.template_content = html;
551                 console.log('set template content');
552             },
553             function() {
554                 $scope.print.template_content = '';
555                 $scope.print.load_failed = true;
556             }
557         );
558         egCore.print.getPrintTemplateContext($scope.print.template_name)
559         .then(function(template_context) {
560             $scope.print.template_context = template_context;
561         });
562     }
563
564     $scope.reset_to_default = function() {
565         egCore.print.removePrintTemplate(
566             $scope.print.template_name
567         );
568         egCore.print.removePrintTemplateContext(
569             $scope.print.template_name
570         );
571         $scope.template_changed();
572     }
573
574     $scope.save_locally = function() {
575         egCore.print.storePrintTemplate(
576             $scope.print.template_name,
577             $scope.print.template_content
578         );
579         egCore.print.storePrintTemplateContext(
580             $scope.print.template_name,
581             $scope.print.template_context
582         );
583     }
584
585     $scope.exportable_templates = function() {
586         var templates = {};
587         var contexts = {};
588         var deferred = $q.defer();
589         var promises = [];
590         egCore.hatch.getKeys('eg.print.template').then(function(keys) {
591             angular.forEach(keys, function(key) {
592                 if (key.match(/^eg\.print\.template\./)) {
593                     promises.push(egCore.hatch.getItem(key).then(function(value) {
594                         templates[key.replace('eg.print.template.', '')] = value;
595                     }));
596                 } else {
597                     promises.push(egCore.hatch.getItem(key).then(function(value) {
598                         contexts[key.replace('eg.print.template_context.', '')] = value;
599                     }));
600                 }
601             });
602             $q.all(promises).then(function() {
603                 if (Object.keys(templates).length) {
604                     deferred.resolve({
605                         templates: templates,
606                         contexts: contexts
607                     });
608                 } else {
609                     ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_EXPORT);
610                     deferred.reject();
611                 }
612             });
613         });
614         return deferred.promise;
615     }
616
617     $scope.imported_print_templates = { data : '' };
618     $scope.$watch('imported_print_templates.data', function(newVal, oldVal) {
619         if (newVal && newVal != oldVal) {
620             try {
621                 var data = JSON.parse(newVal);
622                 angular.forEach(data.templates, function(template_content, template_name) {
623                     egCore.print.storePrintTemplate(template_name, template_content);
624                 });
625                 angular.forEach(data.contexts, function(template_context, template_name) {
626                     egCore.print.storePrintTemplateContext(template_name, template_context);
627                 });
628                 $scope.template_changed(); // refresh
629                 ngToast.create(egCore.strings.PRINT_TEMPLATES_SUCCESS_IMPORT);
630             } catch (E) {
631                 ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_IMPORT);
632             }
633         }
634     });
635
636     $scope.template_changed(); // load the default
637 }])
638
639 // 
640 .directive('egPrintTemplateOutput', ['$compile',function($compile) {
641     return function(scope, element, attrs) {
642         scope.$watch(
643             function(scope) {
644                 return scope.$eval(attrs.content);
645             },
646             function(value) {
647                 // create an isolate scope and copy the print context
648                 // data into the new scope.
649                 // TODO: see also print security concerns in egHatch
650                 var result = element.html(value);
651                 var context = scope.$eval(attrs.context);
652                 var print_scope = scope.$new(true);
653                 angular.forEach(context, function(val, key) {
654                     print_scope[key] = val;
655                 })
656                 $compile(element.contents())(print_scope);
657             }
658         );
659     };
660 }])
661
662 .controller('StoredPrefsCtrl',
663        ['$scope','$q','egCore','egConfirmDialog',
664 function($scope , $q , egCore , egConfirmDialog) {
665     console.log('StoredPrefsCtrl');
666
667     $scope.setContext = function(ctx) {
668         $scope.context = ctx;
669     }
670     $scope.setContext('local');
671
672     // grab the edit perm
673     $scope.userHasDeletePerm = false;
674     egCore.perm.hasPermHere('ADMIN_WORKSTATION')
675     .then(function(bool) { $scope.userHasDeletePerm = bool });
676
677     // fetch the keys
678
679     function refreshKeys() {
680         $scope.keys = {local : [], remote : []};
681
682         if (egCore.hatch.hatchAvailable) {
683             egCore.hatch.getRemoteKeys().then(
684                 function(keys) { $scope.keys.remote = keys.sort() })
685         }
686     
687         // local calls are non-async
688         $scope.keys.local = egCore.hatch.getLocalKeys();
689     }
690     refreshKeys();
691
692     $scope.selectKey = function(key) {
693         $scope.currentKey = key;
694         $scope.currentKeyContent = null;
695
696         if ($scope.context == 'local') {
697             $scope.currentKeyContent = egCore.hatch.getLocalItem(key);
698         } else {
699             egCore.hatch.getRemoteItem(key)
700             .then(function(content) {
701                 $scope.currentKeyContent = content
702             });
703         }
704     }
705
706     $scope.getCurrentKeyContent = function() {
707         return JSON.stringify($scope.currentKeyContent, null, 2);
708     }
709
710     $scope.removeKey = function(key) {
711         egConfirmDialog.open(
712             egCore.strings.PREFS_REMOVE_KEY_CONFIRM, '',
713             {   deleteKey : key,
714                 ok : function() {
715                     if ($scope.context == 'local') {
716                         egCore.hatch.removeLocalItem(key);
717                         refreshKeys();
718                     } else {
719                         egCore.hatch.removeItem(key)
720                         .then(function() { refreshKeys() });
721                     }
722                 },
723                 cancel : function() {} // user canceled, nothing to do
724             }
725         );
726     }
727 }])
728
729 .controller('WSRegCtrl',
730        ['$scope','$q','$window','$location','egCore','egAlertDialog','workstationSvc',
731 function($scope , $q , $window , $location , egCore , egAlertDialog , workstationSvc) {
732
733     var all_workstations = [];
734     var reg_perm_orgs = [];
735
736     $scope.page_loaded = false;
737     $scope.contextOrg = egCore.org.get(egCore.auth.user().ws_ou());
738     $scope.wsOrgChanged = function(org) { $scope.contextOrg = org; }
739
740     console.log('set context org to ' + $scope.contextOrg);
741
742     // fetch workstation reg perms
743     egCore.perm.hasPermAt('REGISTER_WORKSTATION', true)
744     .then(function(orgList) { 
745         reg_perm_orgs = orgList;
746
747         // hide orgs in the context org selector where this login
748         // does not have the reg_ws perm or the org can't have users
749         $scope.wsOrgHidden = function(id) {
750             return reg_perm_orgs.indexOf(id) == -1
751                 || $scope.cant_have_users(id);
752         }
753
754     // fetch the locally stored workstation data
755     }).then(function() {
756         return workstationSvc.get_all()
757         
758     }).then(function(all) {
759         all_workstations = all || [];
760         $scope.workstations = 
761             all_workstations.map(function(w) { return w.name });
762         return workstationSvc.get_default()
763
764     // fetch the default workstation
765     }).then(function(def) { 
766         $scope.defaultWS = def;
767         $scope.activeWS = $scope.selectedWS = egCore.auth.workstation() || def;
768
769     // Handle any URL commands.
770     }).then(function() {
771         var remove = $location.search().remove;
772          if (remove) {
773             console.log('Removing WS via URL request: ' + remove);
774             return $scope.remove_ws(remove).then(
775                 function() { $scope.page_loaded = true; });
776         }
777         $scope.page_loaded = true;
778     });
779
780     $scope.get_ws_label = function(ws) {
781         return ws == $scope.defaultWS ? 
782             egCore.strings.$replace(egCore.strings.DEFAULT_WS_LABEL, {ws:ws}) : ws;
783     }
784
785     $scope.set_default_ws = function(name) {
786         delete $scope.removing_ws;
787         $scope.defaultWS = name;
788         workstationSvc.set_default(name);
789     }
790
791     $scope.cant_have_users = 
792         function (id) { return !egCore.org.CanHaveUsers(id); };
793     $scope.cant_have_volumes = 
794         function (id) { return !egCore.org.CanHaveVolumes(id); };
795
796     // Log out and return to login page with selected WS 
797     $scope.use_now = function() {
798         egCore.auth.logout();
799         $window.location.href = $location
800             .path('/login')
801             .search({ws : $scope.selectedWS})
802             .absUrl();
803     }
804
805     $scope.can_delete_ws = function(name) {
806         var ws = all_workstations.filter(
807             function(ws) { return ws.name == name })[0];
808         return ws && reg_perm_orgs.indexOf(ws.owning_lib) != -1;
809     }
810
811     $scope.remove_ws = function(remove_me) {
812         $scope.removing_ws = remove_me;
813
814         // Perm is used to disable Remove button in UI, but have to check
815         // again here in case we're removing a WS based on URL params.
816         if (!$scope.can_delete_ws(remove_me)) return $q.when();
817
818         $scope.is_removing = true;
819         return workstationSvc.remove_workstation(remove_me)
820         .then(function() {
821
822             all_workstations = all_workstations.filter(
823                 function(ws) { return ws.name != remove_me });
824
825             $scope.workstations = $scope.workstations.filter(
826                 function(ws) { return ws != remove_me });
827
828             if ($scope.selectedWS == remove_me) 
829                 $scope.selectedWS = $scope.workstations[0];
830
831             if ($scope.defaultWS == remove_me) 
832                 $scope.defaultWS = '';
833
834             $scope.is_removing = false;
835         });
836     }
837
838     $scope.register_ws = function() {
839         delete $scope.removing_ws;
840
841         var full_name = 
842             $scope.contextOrg.shortname() + '-' + $scope.newWSName;
843
844         if ($scope.workstations.indexOf(full_name) > -1) {
845             // avoid duplicate local registrations
846             return egAlertDialog.open(egCore.strings.WS_USED);
847         }
848
849         $scope.is_registering = true;
850         workstationSvc.register_workstation(
851             $scope.newWSName, full_name,
852             $scope.contextOrg.id()
853
854         ).then(function(new_ws) {
855             $scope.workstations.push(new_ws.name);
856             all_workstations.push(new_ws);  
857             $scope.is_registering = false;
858
859             if (!$scope.selectedWS) {
860                 $scope.selectedWS = new_ws.name;
861             }
862             if (!$scope.defaultWS) {
863                 return $scope.set_default_ws(new_ws.name);
864             }
865             $scope.newWSName = '';
866         }, function(err) {
867             $scope.is_registering = false;
868         });
869     }
870 }])
871
872 .controller('HatchCtrl',
873        ['$scope','egCore','ngToast',
874 function($scope , egCore , ngToast) {
875     var hatch = egCore.hatch;  // convenience
876
877     $scope.hatch_available = hatch.hatchAvailable;
878     $scope.hatch_printing = hatch.usePrinting();
879     $scope.hatch_settings = hatch.useSettings();
880     $scope.hatch_offline  = hatch.useOffline();
881
882     // Apply Hatch settings as changes occur in the UI.
883     
884     $scope.$watch('hatch_printing', function(newval) {
885         if (typeof newval != 'boolean') return;
886         hatch.setLocalItem('eg.hatch.enable.printing', newval);
887     });
888
889     $scope.$watch('hatch_settings', function(newval) {
890         if (typeof newval != 'boolean') return;
891         hatch.setLocalItem('eg.hatch.enable.settings', newval);
892     });
893
894     $scope.$watch('hatch_offline', function(newval) {
895         if (typeof newval != 'boolean') return;
896         hatch.setLocalItem('eg.hatch.enable.offline', newval);
897     });
898
899     $scope.copy_to_hatch = function() {
900         hatch.copySettingsToHatch().then(
901             function() {
902                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
903             function() {
904                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
905         );
906     }
907
908     $scope.copy_to_local = function() {
909         hatch.copySettingsToLocal().then(
910             function() {
911                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
912             function() {
913                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
914         );
915     }
916
917 }])
918
919