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