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