]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/web/js/ui/default/staff/admin/workstation/app.js
06a908d3c3a0eef3ea539b66fa543732b69d57a4
[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() {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                 target_copy : seed_copy,
453                 copy_barcode : seed_copy.barcode,
454                 call_number : seed_copy.call_number,
455                 title : seed_record.title
456             },
457         ],
458
459         circulations : [
460             {
461                 circ : {
462                     due_date : new Date().toISOString(),
463                 },
464                 copy : seed_copy,
465                 title : seed_record.title,
466                 author : seed_record.author
467             },
468         ],
469
470         in_house_uses : [
471             {
472                 num_uses : 3,
473                 copy : seed_copy,
474                 title : seed_record.title
475             }
476         ],
477
478         previous_balance : 8.45,
479         payment_total : 2.00,
480         payment_applied : 2.00,
481         new_balance : 6.45,
482         amount_voided : 0,
483         change_given : 0,
484         payment_type : 'cash_payment',
485         payment_note : 'Here is a payment note',
486         note : {
487             create_date : new Date().toISOString(), 
488             title : 'Test Note Title',
489             usr : seed_user,
490             value : 'This patron is super nice!'
491         },
492
493         transit : seed_transit,
494         transits : [ seed_transit ],
495         title : seed_record.title,
496         author : seed_record.author,
497         patron : seed_user,
498         address : seed_addr,
499         dest_location : egCore.idl.toHash(egCore.org.get(egCore.auth.user().ws_ou())),
500         dest_address : seed_addr,
501         hold : one_hold,
502         holds : [
503             {
504                 hold : one_hold, title : 'Some Title 1', author : 'Some Author 1',
505                 volume : { label : '646.4 SOM' }, copy : seed_copy,
506                 part : { label : 'v. 1' },
507                 patron_barcode : 'S52802662',
508                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
509             },
510             {
511                 hold : one_hold, title : 'Some Title 2', author : 'Some Author 2',
512                 volume : { label : '646.4 SOM' }, copy : seed_copy,
513                 part : { label : 'v. 1' },
514                 patron_barcode : 'S52802662',
515                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
516             },
517             {
518                 hold : one_hold, title : 'Some Title 3', author : 'Some Author 3',
519                 volume : { label : '646.4 SOM' }, copy : seed_copy,
520                 part : { label : 'v. 1' },
521                 patron_barcode : 'S52802662',
522                 patron_alias : 'XYZ', patron_last : 'Smith', patron_first : 'Jane'
523             }
524         ]
525     }
526
527     $scope.preview_scope.payments = [
528         {amount : 1.00, xact : $scope.preview_scope.transactions[0]}, 
529         {amount : 1.00, xact : $scope.preview_scope.transactions[1]}
530     ]
531     $scope.preview_scope.payments[0].xact.title = 'Hali Bote Azikaban de tao fan';
532     $scope.preview_scope.payments[0].xact.copy_barcode = '334343434';
533     $scope.preview_scope.payments[1].xact.title = seed_record.title;
534     $scope.preview_scope.payments[1].xact.copy_barcode = seed_copy.barcode;
535
536     // today, staff, current_location, etc.
537     egCore.print.fleshPrintScope($scope.preview_scope);
538
539     $scope.template_changed = function() {
540         $scope.print.load_failed = false;
541         egCore.print.getPrintTemplate($scope.print.template_name)
542         .then(
543             function(html) { 
544                 $scope.print.template_content = html;
545                 console.log('set template content');
546             },
547             function() {
548                 $scope.print.template_content = '';
549                 $scope.print.load_failed = true;
550             }
551         );
552         egCore.print.getPrintTemplateContext($scope.print.template_name)
553         .then(function(template_context) {
554             $scope.print.template_context = template_context;
555         });
556     }
557
558     $scope.reset_to_default = function() {
559         egCore.print.removePrintTemplate(
560             $scope.print.template_name
561         );
562         egCore.print.removePrintTemplateContext(
563             $scope.print.template_name
564         );
565         $scope.template_changed();
566     }
567
568     $scope.save_locally = function() {
569         egCore.print.storePrintTemplate(
570             $scope.print.template_name,
571             $scope.print.template_content
572         );
573         egCore.print.storePrintTemplateContext(
574             $scope.print.template_name,
575             $scope.print.template_context
576         );
577     }
578
579     $scope.exportable_templates = function() {
580         var templates = {};
581         var contexts = {};
582         var deferred = $q.defer();
583         var promises = [];
584         egCore.hatch.getKeys('eg.print.template').then(function(keys) {
585             angular.forEach(keys, function(key) {
586                 if (key.match(/^eg\.print\.template\./)) {
587                     promises.push(egCore.hatch.getItem(key).then(function(value) {
588                         templates[key.replace('eg.print.template.', '')] = value;
589                     }));
590                 } else {
591                     promises.push(egCore.hatch.getItem(key).then(function(value) {
592                         contexts[key.replace('eg.print.template_context.', '')] = value;
593                     }));
594                 }
595             });
596             $q.all(promises).then(function() {
597                 if (Object.keys(templates).length) {
598                     deferred.resolve({
599                         templates: templates,
600                         contexts: contexts
601                     });
602                 } else {
603                     ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_EXPORT);
604                     deferred.reject();
605                 }
606             });
607         });
608         return deferred.promise;
609     }
610
611     $scope.imported_print_templates = { data : '' };
612     $scope.$watch('imported_print_templates.data', function(newVal, oldVal) {
613         if (newVal && newVal != oldVal) {
614             try {
615                 var data = JSON.parse(newVal);
616                 angular.forEach(data.templates, function(template_content, template_name) {
617                     egCore.print.storePrintTemplate(template_name, template_content);
618                 });
619                 angular.forEach(data.contexts, function(template_context, template_name) {
620                     egCore.print.storePrintTemplateContext(template_name, template_context);
621                 });
622                 $scope.template_changed(); // refresh
623                 ngToast.create(egCore.strings.PRINT_TEMPLATES_SUCCESS_IMPORT);
624             } catch (E) {
625                 ngToast.warning(egCore.strings.PRINT_TEMPLATES_FAIL_IMPORT);
626             }
627         }
628     });
629
630     $scope.template_changed(); // load the default
631 }])
632
633 // 
634 .directive('egPrintTemplateOutput', ['$compile',function($compile) {
635     return function(scope, element, attrs) {
636         scope.$watch(
637             function(scope) {
638                 return scope.$eval(attrs.content);
639             },
640             function(value) {
641                 // create an isolate scope and copy the print context
642                 // data into the new scope.
643                 // TODO: see also print security concerns in egHatch
644                 var result = element.html(value);
645                 var context = scope.$eval(attrs.context);
646                 var print_scope = scope.$new(true);
647                 angular.forEach(context, function(val, key) {
648                     print_scope[key] = val;
649                 })
650                 $compile(element.contents())(print_scope);
651             }
652         );
653     };
654 }])
655
656 .controller('StoredPrefsCtrl',
657        ['$scope','$q','egCore','egConfirmDialog',
658 function($scope , $q , egCore , egConfirmDialog) {
659     console.log('StoredPrefsCtrl');
660
661     $scope.setContext = function(ctx) {
662         $scope.context = ctx;
663     }
664     $scope.setContext('local');
665
666     // grab the edit perm
667     $scope.userHasDeletePerm = false;
668     egCore.perm.hasPermHere('ADMIN_WORKSTATION')
669     .then(function(bool) { $scope.userHasDeletePerm = bool });
670
671     // fetch the keys
672
673     function refreshKeys() {
674         $scope.keys = {local : [], remote : []};
675
676         if (egCore.hatch.hatchAvailable) {
677             egCore.hatch.getRemoteKeys().then(
678                 function(keys) { $scope.keys.remote = keys.sort() })
679         }
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 or the org can't have users
743         $scope.wsOrgHidden = function(id) {
744             return reg_perm_orgs.indexOf(id) == -1
745                 || $scope.cant_have_users(id);
746         }
747
748     // fetch the locally stored workstation data
749     }).then(function() {
750         return workstationSvc.get_all()
751         
752     }).then(function(all) {
753         all_workstations = all || [];
754         $scope.workstations = 
755             all_workstations.map(function(w) { return w.name });
756         return workstationSvc.get_default()
757
758     // fetch the default workstation
759     }).then(function(def) { 
760         $scope.defaultWS = def;
761         $scope.activeWS = $scope.selectedWS = egCore.auth.workstation() || def;
762
763     // Handle any URL commands.
764     }).then(function() {
765         var remove = $location.search().remove;
766          if (remove) {
767             console.log('Removing WS via URL request: ' + remove);
768             return $scope.remove_ws(remove).then(
769                 function() { $scope.page_loaded = true; });
770         }
771         $scope.page_loaded = true;
772     });
773
774     $scope.get_ws_label = function(ws) {
775         return ws == $scope.defaultWS ? 
776             egCore.strings.$replace(egCore.strings.DEFAULT_WS_LABEL, {ws:ws}) : ws;
777     }
778
779     $scope.set_default_ws = function(name) {
780         delete $scope.removing_ws;
781         $scope.defaultWS = name;
782         workstationSvc.set_default(name);
783     }
784
785     $scope.cant_have_users = 
786         function (id) { return !egCore.org.CanHaveUsers(id); };
787     $scope.cant_have_volumes = 
788         function (id) { return !egCore.org.CanHaveVolumes(id); };
789
790     // Log out and return to login page with selected WS 
791     $scope.use_now = function() {
792         egCore.auth.logout();
793         $window.location.href = $location
794             .path('/login')
795             .search({ws : $scope.selectedWS})
796             .absUrl();
797     }
798
799     $scope.can_delete_ws = function(name) {
800         var ws = all_workstations.filter(
801             function(ws) { return ws.name == name })[0];
802         return ws && reg_perm_orgs.indexOf(ws.owning_lib) != -1;
803     }
804
805     $scope.remove_ws = function(remove_me) {
806         $scope.removing_ws = remove_me;
807
808         // Perm is used to disable Remove button in UI, but have to check
809         // again here in case we're removing a WS based on URL params.
810         if (!$scope.can_delete_ws(remove_me)) return $q.when();
811
812         $scope.is_removing = true;
813         return workstationSvc.remove_workstation(remove_me)
814         .then(function() {
815
816             all_workstations = all_workstations.filter(
817                 function(ws) { return ws.name != remove_me });
818
819             $scope.workstations = $scope.workstations.filter(
820                 function(ws) { return ws != remove_me });
821
822             if ($scope.selectedWS == remove_me) 
823                 $scope.selectedWS = $scope.workstations[0];
824
825             if ($scope.defaultWS == remove_me) 
826                 $scope.defaultWS = '';
827
828             $scope.is_removing = false;
829         });
830     }
831
832     $scope.register_ws = function() {
833         delete $scope.removing_ws;
834
835         var full_name = 
836             $scope.contextOrg.shortname() + '-' + $scope.newWSName;
837
838         if ($scope.workstations.indexOf(full_name) > -1) {
839             // avoid duplicate local registrations
840             return egAlertDialog.open(egCore.strings.WS_USED);
841         }
842
843         $scope.is_registering = true;
844         workstationSvc.register_workstation(
845             $scope.newWSName, full_name,
846             $scope.contextOrg.id()
847
848         ).then(function(new_ws) {
849             $scope.workstations.push(new_ws.name);
850             all_workstations.push(new_ws);  
851             $scope.is_registering = false;
852
853             if (!$scope.selectedWS) {
854                 $scope.selectedWS = new_ws.name;
855             }
856             if (!$scope.defaultWS) {
857                 return $scope.set_default_ws(new_ws.name);
858             }
859             $scope.newWSName = '';
860         });
861     }
862 }])
863
864 .controller('HatchCtrl',
865        ['$scope','egCore','ngToast',
866 function($scope , egCore , ngToast) {
867     var hatch = egCore.hatch;  // convenience
868
869     $scope.hatch_available = hatch.hatchAvailable;
870     $scope.hatch_printing = hatch.usePrinting();
871     $scope.hatch_settings = hatch.useSettings();
872     $scope.hatch_offline  = hatch.useOffline();
873
874     // Apply Hatch settings as changes occur in the UI.
875     
876     $scope.$watch('hatch_printing', function(newval) {
877         if (typeof newval != 'boolean') return;
878         hatch.setLocalItem('eg.hatch.enable.printing', newval);
879     });
880
881     $scope.$watch('hatch_settings', function(newval) {
882         if (typeof newval != 'boolean') return;
883         hatch.setLocalItem('eg.hatch.enable.settings', newval);
884     });
885
886     $scope.$watch('hatch_offline', function(newval) {
887         if (typeof newval != 'boolean') return;
888         hatch.setLocalItem('eg.hatch.enable.offline', newval);
889     });
890
891     $scope.copy_to_hatch = function() {
892         hatch.copySettingsToHatch().then(
893             function() {
894                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
895             function() {
896                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
897         );
898     }
899
900     $scope.copy_to_local = function() {
901         hatch.copySettingsToLocal().then(
902             function() {
903                 ngToast.create(egCore.strings.HATCH_SETTINGS_MIGRATION_SUCCESS)},
904             function() {
905                 ngToast.warning(egCore.strings.HATCH_SETTINGS_MIGRATION_FAILURE)}
906         );
907     }
908
909 }])
910
911