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